Smarter way to set all transparent pixel to white using Java openCV

asked 2019-10-09 18:06:20 -0500

Jill gravatar image

I have an input picture where some transparent pixels are not white in RGB value, e.g. I have some pixels with BGRA [100, 100, 100, 0], I want to change all pixel whose alpha value is 0 to [255, 255, 255, 255], but I cannot figure out a way to do this instead of for loop. What I am doing now is like this:

byte[] imageData = Files.readAllBytes(Paths.get(file));
MatOfByte matOfByte = new MatOfByte(imageData);
Mat source = Imgcodecs.imdecode(matOfByte, Imgcodecs.IMREAD_UNCHANGED);

for (int i = 0; i < source.rows(); i++) {
  for (int j = 0; j < source.cols(); j++) {
    double[] d = source.get(i,j);
    if (Double.compare(d[3], 0) == 0) {
      d[0] = 255;
      d[1] = 255;
      d[2] = 255;
      d[3] = 255;
      source.put(i,j,d);
    }
  }
}

Can we do anything better than this? Thanks a lot!

edit retag flag offensive close merge delete

Comments

1

You should modify the imageData and then call once source.put(imageData ). Calling source.put(i,j,d) in the loop is not efficient. See this tutorial for some Java examples.

Eduardo gravatar imageEduardo ( 2019-10-10 13:39:02 -0500 )edit

So you will still have to loop - but then collect the new values and change them in one go?

holger gravatar imageholger ( 2019-10-10 19:51:01 -0500 )edit
1

extractChannel() -> (255 - mask) -> setTo() w. mask

berak gravatar imageberak ( 2019-10-11 01:54:50 -0500 )edit