Nao Kreuzeder
Nao Kreuzeder

Reputation: 178

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?

Upvotes: 6

Views: 1572

Answers (2)

nathancy
nathancy

Reputation: 46680

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)

Upvotes: 3

k5_
k5_

Reputation: 5568

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.

int invertedPixel = (0xFFFFFF - pixel) | 0xFF000000;
bitmapCopy.setPixel(x,y, invertedPixel);

Upvotes: 0

Related Questions