问题
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)
#pragma rs_fp_relaxed
uint count; // initialized in Java
void countPixels(uchar4* unused, uint x, uint y) {
rsAtomicInc(&count);
}
Java
Application context = ...; // The application context
RenderScript rs = RenderScript.create(applicationContext);
Bitmap bitmap = ...; // A random bitmap
Allocation allocation = Allocation.createFromBitmap(rs, bitmap);
ScriptC_Counter script = new ScriptC_Counter(rs);
script.set_count(0);
script.forEach_countPixels(allocation);
allocation.syncAll(Allocation.USAGE_SCRIPT);
long count = script.get_count();
Error
This is the error message I get:
ERROR: Address not found for count
Questions
- Why doesn't my code work?
- How can I fix it?
Links
- RenderScript (on developer.android.com)
- rsAtomicInc(uint* addr);
回答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:
AtomicTest.rs
AtomicTest.java
回答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;
void countPixels(uchar4* unused, uint x, uint y) {
rsAtomicInc(&count);
rsSetElementAt_int(rsAllocationCount, count, 0);
}
- rsAtomicInc()
- rsSetElementAt_int()
Java
Context context = ...;
RenderScript renderScript = RenderScript.create(context);
Bitmap bitmap = ...; // A random bitmap
Allocation allocationBitmap = Allocation.createFromBitmap(renderScript, bitmap);
Allocation allocationCount = Allocation.createTyped(renderScript, Type.createX(renderScript, Element.I32(renderScript), 1));
ScriptC_Counter script = new ScriptC_Counter(renderScript);
script.set_rsAllocationCount(allocationCount);
script.forEach_countPixels(allocationBitmap);
int[] count = new int[1];
allocationBitmap.syncAll(Allocation.USAGE_SCRIPT);
allocationCount.copyTo(count);
// The count can now be accessed via
count[0];
来源:https://stackoverflow.com/questions/41288051/increment-a-count-variable-in-renderscript