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!