I am trying to make a color detection from the default camera using python, to do this I am using OpenCV and NumPy. My program suddenly closes the camera.
This is code I’m trying to run:
import cv2
import numpy as np
pict=cv2.VideoCapture(0)
while True:
ret,frame=pict.read()
_hsv=cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)
low_red= np.array([347,100,100])
high_red=np.array([0,100.100])
red_mask=cv2.inRange(_hsv, low_red, high_red)
cv2.imshow("Kamera", frame)
cv2.imshow("Kamera HSV", red_mask)
if cv2.waitKey(1)== 27 :
break
pict.release()
cv2.destroyAllWindows()
Advertisement
Answer
There are three stages to do this task:
- Firstly you need to make a color boundries
low_red = np.array([347, 100, 100]) # lower boundry high_red = np.array([0, 100, 100]) # upper boundry
- Color detection
red_mask = cv2.inRange(_hsv, low_red, high_red) # finding the mask output = cv2.bitwise_and(_hsv, _hsv, mask=red_mask) # applying the mask with `hsv` image
- Stack them horizontally.
final = np.hstack([_hsv, output]) # horizontally stacking
cv2.imshow("Imshow", final)