Open In App

Python – Face detection and sending notification

Last Updated : 03 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Nowadays python has become one of the most popular languages as well as favorite programming language among developers. The simplified syntax and pattern of this language make the presence of this language in the trending list.

The biggest strength of Python is a huge collection of standard library which can be used for the following:

  • Machine Learning
  • GUI Applications (like Kivy, Tkinter, PyQt etc. )
  • Web frameworks like Django (used by YouTube, Instagram, Dropbox)
  • Image processing (like OpenCV, Pillow)
  • Web scraping (like Scrapy, BeautifulSoup, Selenium)
  • Test frameworks
  • Multimedia
  • Scientific computing
  • Text processing and many more..

For Machine learning and AI python language is the first priority for the developers because pre-built libraries of python language (like NumPy, Pandas, Pybrain, and SciPy)  help expedite AI development.

In this article , A simple method is implemented using python how to detect human face and after detecting sends notifications to the user. If face is not recognized it does not send notifications to the owner.

Technologies used:

  • OpenCV: OpenCV is a huge open-source library for computer vision, machine learning, and image processing. OpenCV supports a wide variety of programming languages like Python, C++, Java, etc. It can process images and videos to identify objects, faces, or even the handwriting of a human. When it is integrated with various libraries, such as Numpy which is a highly optimized library for numerical operations, then the number of weapons increases in your Arsenal i.e whatever operations one can do in Numpy can be combined with OpenCV.This OpenCV tutorial will help you learn the Image-processing from Basics to Advance, like operations on Images, Videos using a huge set of Opencv-programs and projects.

Sinch : Sinch is used to send messages to the user whenever the camera will detect any face. The user will have to make an account on sinch then he/she can get the ‘service_plan_id’ and ‘token’ from them. After which the user can input the latter in the code. The sender and recipients number also needs to be changed accordingly.

Steps to SMS Token:

  1. Create a new account on Sinch (Refer this link)

Click on Sign – Up

2. Click on messaging and conversations Panel  :

Click on messaging and conservations

3.  Click on SMS option on the Home window:

Click on sms

4.You will get your code from there.

We are using Harcascade Classifier front face file download that file and specify the path.

Clx-sdk-xms 1.0.0 : It is a Python SDK for the CLX Communications REST API (also called XMS) for sending and receiving single or batch SMS messages. It also supports scheduled sends, organizing your frequent recipients into groups, and customizing your message for each recipient using parameterization. Sinch uses clx-sdk-xms to create API’S.

Python3




# OpenCV program to detect face in real time
# import libraries of python OpenCV
# where its functionality resides
  
from cv2 import cv2
  
import clx.xms
import requests
# By creating an account in sinch sms You can get your code.
# code for sms starts here 
#client is a object that carries your unique token.
client = clx.xms.Client(service_plan_id='your_service id',
                        token='token_id')
  
create = clx.xms.api.MtBatchTextSmsCreate()
create.sender = 'sender no.'
create.recipients = {'recipients no.'}
create.body = 'This is a test message from your Sinch account'
# code for sms ends here
# Face Recognition starts from here.
# load the required trained XML classifiers
#/data/haarcascades/haarcascade_frontalface_default.xml
# Trained XML classifiers describes some features of some
# object we want to detect a cascade function is trained
# from a lot of positive(faces) and negative(non-faces)
# images.
  
detector = cv2.CascadeClassifier(
    "path")
  
# capture frames from a camera
  
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
#We want to send sms only once not until the face is there and for that we are
#initializing the counter
counter = 0
# loop runs if capturing has been initialized.
  
while True:
    # reads frames from a camera
  
    ret, img = cap.read()
  
    if ret:
        # convert to gray scale of each frames
  
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # Detects faces of different sizes in the input image
  
        faces = detector.detectMultiScale(gray, 1.1, 4)
  
        for face in faces:
              
            x, y, w, h = face
            # if there is any face and counter is zero then only it will send notification to the sender
            if(face.any() and counter ==0):
                try:
                   batch = client.create_batch(create)
                except (requests.exceptions.RequestException, clx.xms.exceptions.ApiException) as ex:
                    print('Failed to communicate with XMS: %s' % str(ex))
                #sms ends here
            # To draw a rectangle in a face
            cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
      
          
        cv2.imshow("Face", img)
        counter = 1
       # Wait for 'q' key to stop
  
    key = cv2.waitKey(1)
    if key == ord("q"):
        break
# Close the window
cap.release()
# De-allocate any associated memory usage
  
cv2.destroyAllWindows()


Output:

Detecting image:

Notification:



Similar Reads

Face and Hand Landmarks Detection using Python - Mediapipe, OpenCV
In this article, we will use mediapipe python library to detect face and hand landmarks. We will be using a Holistic model from mediapipe solutions to detect all the face and hand landmarks. We will be also seeing how we can access different landmarks of the face and hands which can be used for different computer vision applications such as sign la
4 min read
Opencv Python program for Face Detection
The objective of the program given is to detect object of interest(face) in real time and to keep tracking of the same object.This is a simple example of how to detect face in Python. You can try to use training samples of any other object of your choice to be detected by training the classifier on required objects. Here is the steps to download th
2 min read
Face detection using Cascade Classifier using OpenCV-Python
In this article, we are going to see how to detect faces using a cascade classifier in OpenCV Python. Face detection has much significance in different fields of today's world. It is a significant step in several applications, face recognition (also used as biometrics), photography (for auto-focus on the face), face analysis (age, gender, emotion r
4 min read
How to create a Face Detection Android App using Machine Learning KIT on Firebase
Pre-requisites: Firebase Machine Learning kitAdding Firebase to Android App Firebase ML KIT aims to make machine learning more accessible, by providing a range of pre-trained models that can use in the iOS and Android apps. Let's use ML Kit’s Face Detection API which will identify faces in photos. By the end of this article, we’ll have an app that
8 min read
Face Detection in Flutter using Firebase ML Kit
Face detection is a technique by which we can locate the human faces in the image given. Face detection is used in many places nowadays, especially websites hosting images like Picasa, Photobucket, and Facebook. The automatic tagging feature adds a new dimension to sharing pictures among the people who are in the picture and also gives the idea to
5 min read
Real-Time Edge Detection using OpenCV in Python | Canny edge detection method
Edge detection is one of the fundamental image-processing tasks used in various Computer Vision tasks to identify the boundary or sharp changes in the pixel intensity. It plays a crucial role in object detection, image segmentation and feature extraction from the image. In Real-time edge detection, the image frame coming from a live webcam or video
5 min read
Python | Corner detection with Harris Corner Detection method using OpenCV
Harris Corner detection algorithm was developed to identify the internal corners of an image. The corners of an image are basically identified as the regions in which there are variations in large intensity of the gradient in all possible dimensions and directions. Corners extracted can be a part of the image features, which can be matched with fea
2 min read
Python | Corner Detection with Shi-Tomasi Corner Detection Method using OpenCV
What is a Corner? A corner can be interpreted as the junction of two edges (where an edge is a sudden change in image brightness). Shi-Tomasi Corner Detection - Shi-Tomasi Corner Detection was published by J.Shi and C.Tomasi in their paper 'Good Features to Track'. Here the basic intuition is that corners can be detected by looking for significant
3 min read
Object Detection with Detection Transformer (DETR) by Facebook
Facebook has just released its State of the art object detection Model on 27 May 2020. They are calling it DERT stands for Detection Transformer as it uses transformers to detect objects.This is the first time that transformer is used for such a task of Object detection along with a Convolutional Neural network. There are other Object detection mod
7 min read
Comparing anomaly detection algorithms for outlier detection on toy datasets in Scikit Learn
Anomaly is a deviation from the expected or normal behavior or pattern. Anomaly detection is the process of identifying these unusual patterns or behaviors in data. It is important because anomalies can indicate important events or problems, such as fraudulent activity, equipment failure, or security breaches. Anomaly detection is used in a variety
9 min read