Using Face Recognition Launch AWS Instance with EBS, Send Mail, and Whatsapp Message.

Task Description 📄

❄️ Create a program that performs the below-mentioned task upon recognizing a particular face.

📌 When it recognizes your face then —
👉 It sends mail to your mail-id by writing this is the face of your_name.
👉 Second, it sends a Whatsapp message to your friend, it can be anything.

📌 When it recognizes a second face, it can be your friend or family member's face.
👉 Create EC2 instance in the AWS using CLI.
👉 Create 5 GB EBS volume and attach it to the instance.

This article shows how you can do this task easily

For Face Recognition here we use the pre-created Haar Cascade Classifier. Haar Cascades can be used to detect any type of object as long as you have the appropriate XML file for it. You can even create your own XML files from scratch to detect whatever type of object you want

Now lets us import NumPy and haar cascade XML file. You can get this any frontal face detection from here: https://github.com/opencv/opencv/blob/master/data/haarcascades/haarcascade_frontalface_default.xml

In the first step, we are detecting the face with the help of the Haar Cascade XML file and then converting those images into grey form and further cropping the image in a way such that only the face is visible. Also, initialized Camera (0) means our python code will use the interior webcam.

The Code snippet is given below:

Then, the webcam will collect 100 samples of the images. For that used a counter operation and then it will save the file in the specified path as shown below

Let’s Train the model

The next step is to train the model using the LBPH Face Recognizer. It is one of the simplest algorithms to find the pattern in the image

Local Binary Pattern Histogram(LBPH) is a very efficient texture operator which labels the pixels of an image by thresholding the neighborhood of each pixel and considers the result as a binary number.

Below given the code snippet

After training is completed it will output as follows

The last step is to check the trained model. In this step, it will start the camera, detects the face, and match it with the model which was created earlier, and compared it with the data of the face images/samples which are collected previously.

While comparing in real-time our model with the current ongoing video it will show the text on the image that it recognized you or not and show the percentage of accuracy(confidence score ) / percentage of similarity of the current user with the previously collected face.

After detecting the real face on which it was trained, it will send a Mail and Whatsapp text to a specified number. Also, it will launch the AWS EC2 instance, then, create an additional 8GB EBS Volume from CLI and attach it with the currently launched EC2 instance.

Below given the sample code snippet:

import os

import cv2

import subprocess

import threading

import numpy as np

import sendmail as sd

face_classifier = cv2.CascadeClassifier(‘haarcascade_frontalface_default.xml’)

def face_detector(img, size=0.5):

# Convert image to grayscale

gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

faces = face_classifier.detectMultiScale(gray, 1.3, 5)

if faces is ():

return img, []

for (x,y,w,h) in faces:

cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,255),2)

roi = img[y:y+h, x:x+w]

roi = cv2.resize(roi, (200, 200))

return img, roi

# Open Webcam

cap = cv2.VideoCapture(0)

email_sent = False

while True:

ret, frame = cap.read()

image, face = face_detector(frame)

try:

face = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)

# Pass face to prediction model

# “results” comprises of a tuple containing the label and the confidence value

results = ajmal_model.predict(face)

# harry_model.predict(face)

if results[1] < 500:

confidence = int( 100 * (1 — (results[1])/400) )

display_string = str(confidence) + ‘% Confident it is User’

cv2.putText(image, display_string, (100, 120), cv2.FONT_HERSHEY_COMPLEX, 1, (255,120,150), 2)

if confidence > 90:

cv2.putText(image, “Hey Ajmal”, (250, 450), cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,0), 2)

cv2.imshow(‘Face Recognition’, image)

if not email_sent:

print(“Sending Email”)

email_sent = True

file_name_path = “./faces/email/” + “ajmal” + “.jpg”

cv2.imwrite(file_name_path, face)

t1 = threading.Thread(target=sd.sendmail)

t1.start()

print(“Launching EC2 Instnace”)

ec2_launching = “aws ec2 run-instances — image-id ami-0ad704c126371a549 — count 1 — instance-type t2.micro — key-name summer”

subprocess.call(ec2_launching, shell=True)

print(“Getting the Instance id of Currently launched EC2”)

instance_id = subprocess.getoutput(‘aws ec2 describe-instances — query “sort_by(Reservations[].Instances[], &LaunchTime)[-1].[InstanceId]” — output text’)

print(instance_id)

print(“Getting the avaialbility zone of currently launched EC2 instance”)

instance_availability_zone = subprocess.getoutput(‘aws ec2 describe-instances — query “sort_by(Reservations[].Instances[], &LaunchTime)[-1].[Placement.AvailabilityZone]” — output text’)

print(instance_availability_zone)

print(“Creating EBS of size 5GB”)

subprocess.call(“aws ec2 create-volume — availability-zone {0} — size 5”.format(instance_availability_zone), shell=True)

print(“Getting the Volume Id of EBS”)

volume_id = subprocess.getoutput(‘aws ec2 describe-volumes — query “Volumes[-1].[VolumeId]” — output text’)

print(volume_id)

print(“Attaching the newly created EBS Volume with previously launched EC2 Instnace”)

subprocess.call(‘aws ec2 attach-volume — device /dev/xvdj — instance-id {0} — volume-id {1}’.format(instance_id, id_volume), shell=True)

print(“Successfully Attached EBS Volume with EC2 Instance”)

else:

cv2.putText(image, “I dont know, whow are you”, (250, 450), cv2.FONT_HERSHEY_COMPLEX, 1, (0,0,255), 2)

cv2.imshow(‘Face Recognition’, image )

except:

cv2.putText(image, “No Face Found”, (220, 120) , cv2.FONT_HERSHEY_COMPLEX, 1, (0,0,255), 2)

cv2.putText(image, “looking for face”, (250, 450), cv2.FONT_HERSHEY_COMPLEX, 1, (0,0,255), 2)

cv2.imshow(‘Face Recognition’, image )

pass

if cv2.waitKey(1) == 13: #13 is the Enter Key

break

cap.release()

cv2.destroyAllWindows()

So, we successfully accomplished the task using face detection

For more detailed visit this GitHub link: https://github.com/ajmalmohammedn/summer_program_2021.git

Thank You!

--

--

--

Python Enthusiast

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Deep Dive Into Adversarial Attacks

Released ailia SDK 1.2.5

Unlocking the True Power of Support Vector Regression

Meta Ensemble Self-Learning Model with Optimization

Various types of support vector Machines in Machine-Learning

How to formalize a task for a Computer Vision project

Machine Learning model in Docker container with Python..

Multi-Task Learning with Deep Neural Networks

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ajmal Muhammed

Ajmal Muhammed

Python Enthusiast

More from Medium

Free simple database cloud storage with Repl.it

Code preparation for Hash Code 2022 with Apps Script

A simple bot to send emails in Google Cloud

Start learning cloud with Oracle cloud free tier

Clear sky with clouds