0

My problem is to get the amount of transparent parts/pixels in an image which is changed because of an OnTouchEvent by the user.

So I would like to transform the following java code into renderscript code:

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;
}

Please add code snippets from the rs and java file.

Thanks in advance!

Fynn
  • 3
  • 1
  • 4
  • Hi Fynn, I found some problems in my old answer, I have updated it, please have a look. – Corey Jan 11 '19 at 03:26
  • @KuanlinChen I tried your solution as well as the solution of winklerrr, even though it's just for counting the amount of pixel in an image. Your solution returned 0 and the the other one 1. Is there maybe a different way of live counting transparent pixels from a bitmap without using RenderScript? – Fynn Jan 11 '19 at 19:05
  • What do you mean by "live counting" ? – Corey Jan 24 '19 at 02:11
  • 1
    The bitmap changes all the time, because the user can draw transparent pixel on it. So my goal is to count the transparent pixel after every time the user draws on the bitmap – Fynn Jan 25 '19 at 05:11

1 Answers1

0

Reference: RenderScript Docs and rsAtomicInc.

Here is my sample code. Refer to winklerrr's solution here.

RSexample.rs

use in->a to retrive alpha and check its value.

#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

acts as context between MainActivity.java and 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];
}

MainActivity.java

RSContext rsContext = new RSContext();
rsContext.init(this);
rsContext.setup(bitmap.getWidth(), bitmap.getHeight());
rsContext.addPic(bitmap);
int transparentPixel = rsContext.getCount();
Corey
  • 1,217
  • 3
  • 22
  • 39