Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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

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!