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!
You should modify the
imageData
and then call oncesource.put(imageData )
. Callingsource.put(i,j,d)
in the loop is not efficient. See this tutorial for some Java examples.So you will still have to loop - but then collect the new values and change them in one go?
extractChannel() -> (255 - mask) -> setTo() w. mask