Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To invert colours from black to white in opencv python

I have a condition where I want to detect white line incase of black background and black line incase of white background. I used bitwise_not operation something like this:

cv2.bitwise_not(mask_black)

It is working perfectly until and unless i give a condition like this:

if mask_black == cv2.bitwise_not(mask_black):

I get an error

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I am having doubts about using conditions where if black background occurs white line is to be detected and if white background occurs black line is to be detected

mask_black = cv2.inRange(hsv, low_black, high_black)
mask_not=cv2.bitwise_not(mask_black)

if mask_black==cv2.bitwise_and(mask_black, mask_not):
    body 
else:
    body

This is returning the above error

like image 828
Spartan Avatar asked Jan 25 '23 18:01

Spartan


1 Answers

The idea is to check the background for white pixels with cv2.countNonZero(). We set a threshold, say 50%. If more than 50% of the background is white pixels then it means we are looking for the black line. Similarly, if the majority of the background is black then we are looking for the white line.

import cv2

image = cv2.imread('1.png', 0)
w, h = image.shape[:2]

if cv2.countNonZero(image) > ((w*h)//2):
    # Detect black line
    ...
else:
    # Detect white line
    ...

To invert an image, you can do this

invert = cv2.bitwise_not(image) # OR
#invert = 255 - image

like image 183
nathancy Avatar answered Jan 31 '23 23:01

nathancy