Search code examples
pythonopencvwebcam

Does not show the video on the screen cv2


What is the problem ? It does not give an error. Keeps working until it freezes

My camera lights up but does not show the video on the screen

#my cam "0"
cap = cv2.VideoCapture(0)
frame = None
while True:
    ret, frame = cap.read()
    cv2.imshow("Frame", frame)
cap.release()
cv2.destroyAllWindows()

Here screen

enter image description here


Solution

  • You'll need to add a cv2.waitKey call to set the delay time for each frame. Currently your code is like 0 milliseconds per frames, which is causing the problem.

    Try:

    cap = cv2.VideoCapture(0)
    frame = None
    while True:
        ret, frame = cap.read()
        cv2.imshow("Frame", frame)
        cv2.waitKey(1) # 1 millisecond per frame
    cap.release()
    cv2.destroyAllWindows()
    

    Or, you could make the closing process easier by adding this if statement:

    cap = cv2.VideoCapture(0)
    frame = None
    while True:
        ret, frame = cap.read()
        cv2.imshow("Frame", frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    cap.release()
    cv2.destroyAllWindows()
    

    Where the camera would close when you press the q key.