Ask Your Question
0

black and white image detection

asked 2019-10-03 04:56:03 -0600

I am trying to identify if an image is black and white or a color image using Open CV in python language. i have created a black and white image using MS paint to check the same. even though the image is black white it still has RGB values other than 0 and 255. below is the code i have used and images i have used. the output i am getting is color image. I checked the RGB values they have values other than 0 and 255, i am not able to debug why, can some one help me with this?

image_pixel =img.flatten()

bnw_cnt = sum(np.where((image_pixel == 0) | (image_pixel == 255), 1, 0))

if np.vectorize(bnw_cnt) == np.vectorize(image_pixel):
    print("Black and white image")
else:
    print ("Color image")

image description

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
1

answered 2019-10-03 15:06:46 -0600

kbarni gravatar image

There are several problems with your approach.

Classically the grayscale images are called "black and white" (so the images that don't have color pixels), not the images that contain only black and white pixels.

Your algorithm tries check only for black and white colors, not for grayscale.

The second problem is that flatten will put all your values in a vector. So for the green color (0,255,0) you will get 3 values, and all of them are either 0 or 255. So a totally green image will be considered a black and white image.

The second problem is that Paint uses a technique named antialiasing, which means that the contour pixels are in fact gray pixels. This is used to eliminate the jagged, pixelated edges.

If you want to detect if an image is grayscale, convert it to HSV color space (using cv2.cvtColor), split it to the 3 channels (h,s,v = cv2.split(hsvimg)) and check the saturation channel for every pixel to be 0. If you want to see that it contains only black and white color, then after the pre vious step check the value channel for 0 and 255.

You can find below your image in true black and white (notice the pixelated edges).

black_and_white

edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2019-10-03 04:56:03 -0600

Seen: 9,767 times

Last updated: Oct 03 '19