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:
JavaScript
x
22
22
1
import cv2
2
import numpy as np
3
4
pict=cv2.VideoCapture(0)
5
6
while True:
7
ret,frame=pict.read()
8
_hsv=cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)
9
10
low_red= np.array([347,100,100])
11
high_red=np.array([0,100.100])
12
red_mask=cv2.inRange(_hsv, low_red, high_red)
13
14
cv2.imshow("Kamera", frame)
15
cv2.imshow("Kamera HSV", red_mask)
16
17
if cv2.waitKey(1)== 27 :
18
break
19
20
pict.release()
21
cv2.destroyAllWindows()
22
Advertisement
Answer
There are three stages to do this task:
- Firstly you need to make a color boundries
JavaScript
1
3
1
low_red = np.array([347, 100, 100]) # lower boundry
2
high_red = np.array([0, 100, 100]) # upper boundry
3
- Color detection
JavaScript
1
3
1
red_mask = cv2.inRange(_hsv, low_red, high_red) # finding the mask
2
output = cv2.bitwise_and(_hsv, _hsv, mask=red_mask) # applying the mask with `hsv` image
3
- Stack them horizontally.
JavaScript
1
3
1
final = np.hstack([_hsv, output]) # horizontally stacking
2
cv2.imshow("Imshow", final)
3