Open In App

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

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.

Approach:



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(cap.isOpened()):
      
    while True:
          
        ret, img = cap.read()
        cv2.imshow('img', img)
        if cv2.waitKey(30) & 0xff == ord('q'):
            break
              
    cap.release()
    cv2.destroyAllWindows()
else:
    print("Alert ! Camera disconnected")

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

Approach:

Below is the implementation.




# Python program to send 
# the mail
  
  
import smtplib
  
  
conn = smtplib.SMTP('smtp.gmail.com', 587)
  
conn.ehlo()
conn.starttls()
  
# 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')
  
conn.quit()


Article Tags :