Check if the camera is opened or not using OpenCV Python


OpenCV is an Open Source Computer Vision Library in python. It provides numerous functions to perform various Image or video processing operations. The library uses the python Numpy module to represent all the video or image arrays as a ndarray type.

OpenCV-python needs the numpy library, we need to make sure that the numpy module is also installed in our python interpreter. In this article, we will see how to check if the camera is opened or not using OpenCV Python.

Checking if the camera is opened

We may not be sure about the status of the camera like whether it is opened by any other application or it is not working properly. In these situations, our program will throw an error instead of creating an empty frame. To avoid such cases initially we need to check the status of the camera.

Example

The following example simply opens the camera and captures the video frames if the camera is working properly otherwise it will raise the error like below.

import cv2
cam = cv2.VideoCapture(0)
ret, frame = cam.read()
cv2.imwrite('image.jpg', frame)
cam.release()
cv2.destroyAllWindows()

Output

---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_8052\746690897.py in 
      2 cam = cv2.VideoCapture(0)
      3 ret, frame = cam.read()
----> 4 cv2.imwrite('image.jpg', frame)
      5 cam.release()
      6 cv2.destroyAllWindows()

error: OpenCV(4.7.0) D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp:783: error: (-215:Assertion failed) !_img.empty() in function 'cv::imwrite'

To avoid error like above we need to check the camera status initially.

Using cv2.VideoCapture.isOpend() function

The function checks whether the cv2.VideoCapture() object has started capturing the frames or not. It will return True if the object starts capturing the video frames otherwise it will return False.

Example

In this example, we will use the isOpend() function to check the status of the camera.

import numpy as np
import cv2  
cap = cv2.VideoCapture(0)
while(cap.isOpened()):   # true when camera is open
    while True:
        ret, img_array = cap.read()
        cv2.imshow('img', img_array)
        if cv2.waitKey(1) & 0xff == ord('q'):
            break
    cap.release()
    cv2.destroyAllWindows()
else:
    print("Camera is disconnected")

Output

However, this approach will throw an error if the camera is already accessed/opened by any other application.

Let’s see the below example to avoid the above circumstance, here we will use the cap.read() function.

Using cv2.VideoCapture.read() function

The cv2.VideoCapture.read() funsion/method reads the frames. This function returns a tuple of 2 values (ex: (False, none)) −

  • ret: This is a Boolean value that is true if the frame is read successfully, else false, with this value, we check whether the reading was successful or not.

  • frame: This is the actual input frame that is recorded from the camera. This frame can be stored in a variable and the data type is ndarry.

Example

In this example, we will use the read() function to check the camera status.

import cv2
cap=cv2.VideoCapture(0)
while True:
    if cap.read()[0]==False:
        print("Camera is disconnected")
        break
    else:
        ret, frame=cap.read()
        cv2.imshow("image",frame)

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

Output

Camera is disconnected

This way we can check if the camera is working or not working using the python OpenCV. If the camera is disconnected or already accessed/opened by any other application, then the above program will display a message as above.

Updated on: 30-May-2023

807 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements