I do some image processing with OpenCV. I want to invert this bitmap (black to white, white to black) and i have some problems with it.
I got this Bitmap after doing this:
// to grey
Imgproc.cvtColor(mat, mat, Imgproc.COLOR_RGB2GRAY, 4);
Imgproc.adaptiveThreshold(mat, mat, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY_INV, 15, 4);
Utils.matToBitmap(mat, bitmapCopy);
This is the result after inverting.
This is my code:
// to grey
Imgproc.cvtColor(mat, mat, Imgproc.COLOR_RGB2GRAY, 4);
Imgproc.adaptiveThreshold(mat, mat, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY_INV, 15, 4);
Utils.matToBitmap(mat, bitmapCopy);
for(int y = 0; y < bitmapCopy.getHeight(); y++){
for(int x = 0; x < bitmapCopy.getWidth(); x++){
int pixel = bitmapCopy.getPixel(x,y);
if (pixel == Color.WHITE){
bitmapCopy.setPixel(x, y, Color.BLACK);
} else {
bitmapCopy.setPixel(x, y, Color.WHITE);
}
}
}
The white lines from the first image should be inverted to black lines, but it´s not working. I checked the file with Adobe Photoshop. When i point at a white area of the image it shows that the color is white (#FFFFFF).
What am i missing? Can anybody enlighten me?
2
Answers
Your input is a grayscale image. So only pure white will be turned to black, everything else will be white.
I’m not familiar with opencv, so this might not work. But it is worth a shot.
You can use a bitwise-not to invert the image. In general, you want to avoid iterating through each pixel as it is very slow.
Original
Result
Here are two methods to invert an image. Using the built in
cv2.bitwise_not()
function or just subtracting 255. It’s implemented in Python but the same idea can be used in Java.