为渲染脚本中位图中的透明像素创建一个计数器



我的问题是获取图像中由于用户的OnTouchEvent而更改的透明部分/像素的数量。

所以我想将以下java代码转换为renderscript代码:

public int transparentPixels(){  
    int amount = 0;
    for(int x = 0; x < sourceBitmap.getWidth(); x++){
        for(int y = 0; y < sourceBitmap.getHeight(); y++){
            if(sourceBitmap.getPixel(x,y) == Color.TRANSPARENT){
                amount += 1;
            }
        }
    }
    return amount;
}

请从 rs 和 java 文件添加代码片段。

提前感谢!

参考:RenderScript Docs 和 rsAtomicInc.

这是我的示例代码。请参阅此处的Winklerrr解决方案。

RSexample.rs

使用 in->a 检索 alpha 并检查其值。

#pragma version(1)
#pragma rs java_package_name(RS)
#pragma rs_fp_relaxed
int32_t count = 0;
rs_allocation rsAllocationCount;
void countPixels(uchar4* in, uint x, uint y) {
  if(in->a==0)rsAtomicInc(&count);
  rsSetElementAt_int(rsAllocationCount, count, 0);
}

RSContext.java

充当 MainActivity.java 和 RSexample.rs 之间的上下文。

public void init(Context context) {
    rs = RenderScript.create(context);
    scriptC_RS = new ScriptC_RSexample(rs);
}
public void setup(int w, int h){
    rgb888Type = Type.createXY(rs, Element.RGBA_8888(rs), w, h);
    allocIn = Allocation.createTyped(rs, rgb888Type, Allocation.USAGE_SCRIPT);
    allocCount = Allocation.createTyped(rs, Type.createX(rs, Element.I32(rs), 1));
}
public void addPic(Bitmap bitmap) {
    allocIn = Allocation.createFromBitmap(rs, bitmap);
}
public int getCount(){
    scriptC_RS.set_rsAllocationCount(allocCount);
    scriptC_RS.forEach_countPixels(allocIn);
    int[] count = new int[1];
    allocIn.syncAll(Allocation.USAGE_SCRIPT);
    allocCount.copyTo(count);
    return count[0];
}

主活动.java

RSContext rsContext = new RSContext();
rsContext.init(this);
rsContext.setup(bitmap.getWidth(), bitmap.getHeight());
rsContext.addPic(bitmap);
int transparentPixel = rsContext.getCount();

最新更新