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