Friday, December 27, 2024
Google search engine
HomeLanguagesCheck if the camera is opened or not using OpenCV-Python

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:

  • 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(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:

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


RELATED ARTICLES

Most Popular

Recent Comments