Search code examples
pythonopencvwebcam

How do I know if my webcam is currently working? python, opencv


How do I know if my webcam is currently working? I tried to check " stream.read () " because it returns "None" when the camera is not active. But when the camera is active " stream.read () " returns an array and I get an error "The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()". How do I fix this? my code:

import cv2
import time
from tkinter import *

stream = cv2.VideoCapture(0)
time.sleep(10)
while True:

    r, f = stream.read ()
    a=f
    print(a)
    if a==None:
        print("No active")
    else:
        print("Active")

    cv2.imshow('IP Camera stream',f)
    # f = imutils.resize(f, width=400)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cv2.destroyAllWindows()

Solution

  • read() returns both an array and a boolean to indicate whether it was successful in reading a frame, the r in your code. Use that value instead:

    if r == False:
            print("No frame read")
        else:
            print("Succes")
    

    docs

    That checks if a frame was read. However, a frame might not be read even when the camera is active. The best way to check if the camera is active is to check :

    open = stream.isOpened()
    
    if open:
        print('Camera active')
    

    docs