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?
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.
import cv2
image = cv2.imread('1.png')
result = 255 - image
alternative_result = cv2.bitwise_not(image)
cv2.imshow('image', image)
cv2.imshow('result', result)
cv2.imshow('alternative_result', alternative_result)
cv2.waitKey(0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With