Check if the camera is opened or not using OpenCV python

This Python code allows user to easily check if their system’s built-in camera or an external webcam is accessible. It uses OpenCV’s cv2 module to interact with the camera, making it a flexible tool for real-time video streaming and webcam-based applications.When the code runs, it first checks if the default system camera is available. If it is, then the user is prompted to start the webcam. If not, then the code automatically switches to an external camera, if connected. After determining which camera to use, the user can choose whether to open the webcam view or not. If yes, the the live video stream starts, and user can stop it anytime by pressing the ‘q’ key.

Each time a new frame is captured, the code displays it in real time. It handles several errors such as issues while capturing frames or incorrect user inputs, to ensure smooth operation. This functionality is useful for a variety of projects, including surveillance, video conferencing, and more. Whether you’re looking to build a simple webcam tool or a more complex video streaming application, this script serves as an easy-to-use base for webcam interactions.This implementation is flexible and simple to modify for different use cases. You can easily add additional features or customize it to fit the specific needs of your project.

To check if the camera is opened or not using OpenCV , a practical approach.

 

Initially we start the code by importing the OpenCV library, which is used for computer vision tasks. In this case, it helps to interact with webcams and capture frames.Here, the function cam_opened_or_not() is defined. Initially, the cam_index is set to 0, which is the default index for the system’s built-in camera. cv2.videoCapture(cam_index) attempts to open the camera.

import cv2
def cam_opened_or_not():
    cam_index = 0
    camera_capture = cv2.VideoCapture(cam_index)

In the next step the isOpened() method checks if the camera is accessible. If the camera is available, it prints a message confirming the webcam can be accessed otherwise, it moves to check the external camera with index 1.If the system camera is unavailable, the code tries to open the external camera by setting cam_index to 1.

if camera_capture.isOpened():
    print(f"Camera with default index {cam_index} for system webcam can be accessed.")
else:
    print(f"The system/inbuilt camera with default index {cam_index} is not accessible.")
cam_index = 1
camera_capture = cv2.VideoCapture(cam_index)

Again, the code checks if the external camera can be accessed. If yes, it prints a confirmation message.The user is prompted to decide whether they want to open the webcam window or not.If the user answers “yes,” the script enters a loop to display the live webcam window. The camera.capture.read captures a frame from the camera.If the frame is not captured successfully, it prints an error message and exits the loop.The captured frame is displayed in a window titled “Camera View.”

if camera_capture.isOpened():
    print(f"Camera with index {cam_index} for secondary/external camera can be accessed.")
user_choice = input("Your camera is accessible. Do you want to open the webcam? Enter Yes or No: ").lower()
if user_choice == "yes":
    print("Enter 'q' to stop the live webcam:")
    while True:
        ret, frame = camera_capture.read()
if not ret:
    print("Failed to capture the frame from the webcam.")
    break
cv2.imshow('Camera View:', frame)

Finally to stop the webcam window press ‘q’ .The camera is released, and all OpenCV windows are destroyed.

if cv2.waitKey(1) & 0xFF == ord('q'):
    break
camera_capture.release()
cv2.destroyAllWindows()
elif user_choice == "no":
    print("Thank you for your input, exiting the code!")
else:
    print("Please enter a valid input: 'yes' or 'no'.")

Click here for reference

Output:-

Camera with default index 0 for system webcam can be accessed.
Your camera is accessible. Do you want to open the webcam? Enter Yes or No: yes
(your webcam will be activated in a small window)
Enter 'q' to stop the live webcam:

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top