Skip to content
Related Articles

Related Articles

Check if the camera is opened or not using OpenCV-Python

Improve Article
Save Article
  • Last Updated : 07 Oct, 2021
Improve Article
Save Article

OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on Images or videos. OpenCV library can be used to perform multiple operations on videos.

While writing code in Python using OpenCV, we may not be sure whether at the remote end camera is opened and working properly or not. The camera plays an essential role in areas such as Security and Video Surveillance System. In a real-time video monitoring system, to ensure that the camera is opened and working properly we have isOpened() of OpenCV. The idea behind the article is to check whether the camera is connected and if the camera is found to be disconnected then a mail will be sent to the Admin or the concerned person.

1. Check whether the camera is opened/connected or not.


  • Importing necessary libraries(NumPy and OpenCV)
  • Starting camera. Here, in VideoCapture()-0 denotes built-in webcam while 1 will denote the use of external webcams.
  • If the camera is opened, we will loop over frames whereas in the other case, a message “Alert! Camera disconnected” will be printed on the terminal window.

Below is the implementation.

# Python program to check
# whether the camera is opened 
# or not
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
    while True:
        ret, img =
        cv2.imshow('img', img)
        if cv2.waitKey(30) & 0xff == ord('q'):
    print("Alert ! Camera disconnected")

2. Sending Mail if camera is found to be disconnected/not opened.


  • Import the necessary libraries(smtplib is the python library to send mails).
  • Establish a connection with the server and login to the account.
  • Specify the receiver’s email address and message to be sent (“Alert! Camera disconnected!” in this case).
  • Once the mail is sent, close the connection or quit the session.

Below is the implementation.

# Python program to send 
# the mail
import smtplib
conn = smtplib.SMTP('', 587)
# Enter the sender's details
conn.login('Enter sender \'s gmail address'
           'Enter sender\'s password')
conn.sendmail('Enter sender\'s gmail address'
              'Enter Receiver\'s gmail address'
              'Enter message to be sent')

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!