camera suddenly close when i run the code

Tags: ,



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

Answer

There are three stages to do this task:

  1. 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
  1. 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
  1. Stack them horizontally.
final = np.hstack([_hsv, output])  # horizontally stacking
cv2.imshow("Imshow", final) 


Source: stackoverflow