Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inverting black and white on a bitmap is not working

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);

enter image description here

This is the result after inverting. enter image description here

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?

like image 500
Nao Kreuzeder Avatar asked Sep 08 '19 17:09

Nao Kreuzeder


Video Answer


1 Answers

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

enter image description here

Result

enter image description here

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)
like image 54
nathancy Avatar answered Oct 11 '22 16:10

nathancy