Increment A Count Variable In Renderscript
I want to count the pixels of a bitmap using the following RenderScript code RenderScript Filename: counter.rs #pragma version(1) #pragma rs java_package_name(com.mypackage) #pragm
Solution 1:
As a side note, it is usually not a good practice to use atomic operations in parallel computing unless you have to. RenderScript actually provide the reduction kernel for this kind of application. Maybe you can give it a try.
There several problems with the code:
- The variable "count" should have been declared "volatile"
- countPixels should have been "void RS_KERNEL countPixels(uchar4 in)"
- script.get_count() will not get you the up-to-date value of "count", you have to get the value back with an Allocation.
If you have to use rsAtomicInc, a good example is actually the RenderScript CTS tests:
Solution 2:
Here is my working solution.
RenderScript
Filename: counter.rs
#pragma version(1)#pragma rs java_package_name(com.mypackage)#pragma rs_fp_relaxed
int32_t count = 0;
rs_allocation rsAllocationCount;
voidcountPixels(uchar4* unused, uint x, uint y) {
rsAtomicInc(&count);
rsSetElementAt_int(rsAllocationCount, count, 0);
}
Java
Contextcontext= ...;
RenderScriptrenderScript= RenderScript.create(context);
Bitmapbitmap= ...; // A random bitmapAllocationallocationBitmap= Allocation.createFromBitmap(renderScript, bitmap);
AllocationallocationCount= Allocation.createTyped(renderScript, Type.createX(renderScript, Element.I32(renderScript), 1));
ScriptC_Counterscript=newScriptC_Counter(renderScript);
script.set_rsAllocationCount(allocationCount);
script.forEach_countPixels(allocationBitmap);
int[] count = newint[1];
allocationBitmap.syncAll(Allocation.USAGE_SCRIPT);
allocationCount.copyTo(count);
// The count can now be accessed via
count[0];
Post a Comment for "Increment A Count Variable In Renderscript"