borisk
borisk

Reputation: 49

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

Upvotes: 1

Views: 1020

Answers (2)

J.D.
J.D.

Reputation: 4561

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

Upvotes: 1

furas
furas

Reputation: 142641

f is numpy's array and to check it is not None you have to check

 if f is None:

instead of

 if f == None: 

When f has array then you compare array == None and it tries to compare None with every element in array and it is ambiguous - so it ask to use any() or all()

Upvotes: 1

Related Questions