Face Recognizing and Creating EC2 instance and EBS in AWS, Sending Whatsapp Message using ML model and python.
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 the 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.
- To recognize the face I have used a Pre-built model i.e. Haarcascade_frontalface which is an OpenCV algorithm model used to detect a face. And it can detect one face at a time so if your requirement is to detect multiple objects then we can use CNN, multi-classification.
Let's jump to the code:
- I have commented everything in my code so if you don't understand the code please check those comments.
Step 1 - Create Training Data In [1]: import cv2 import smtplib import pywhatkit import os from twilio.rest import Client from email import message import numpy as np # Load HAAR face classifier face_classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') # Load functions def face_extractor(img): # Function detects faces and returns the cropped face # If no face detected, it returns the input image gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) faces = face_classifier.detectMultiScale(gray, 1.3, 5) if faces is (): return None # Crop all faces found for (x,y,w,h) in faces: cropped_face = img[y:y+h, x:x+w] return cropped_face # Initialize Webcam cap = cv2.VideoCapture(0) count = 0 # Collect 100 samples of your face from webcam input while True: ret, frame = cap.read() if face_extractor(frame) is not None: count += 1 face = cv2.resize(face_extractor(frame), (200, 200)) face = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY) # Save file in specified directory with unique name file_name_path = './faces/user/' + str(count) + '.jpg' cv2.imwrite(file_name_path, face) # Put count on images and display live count cv2.putText(face, str(count), (50, 50), cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,0), 2) cv2.imshow('Face Cropper', face) else: print("Face not found") pass if cv2.waitKey(1) == 13 or count == 100: #13 is the Enter Key break cap.release() cv2.destroyAllWindows()
print("Collecting Samples Complete")
Step 2 - Train Model In [2]: cap.release() In [3]: import cv2 import numpy as np from os import listdir from os.path import isfile, join # Get the training data we previously made data_path = './faces/user/' onlyfiles = [f for f in listdir(data_path) if isfile(join(data_path, f))] # Create arrays for training data and labels Training_Data, Labels = [], [] # Open training images in our datapath # Create a numpy array for training data for i, files in enumerate(onlyfiles): image_path = data_path + onlyfiles[i] images = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE) Training_Data.append(np.asarray(images, dtype=np.uint8)) Labels.append(i) # Create a numpy array for both training data and labels Labels = np.asarray(Labels, dtype=np.int32) # Initialize facial recognizer # model = cv2.face.createLBPHFaceRecognizer() # NOTE: For OpenCV 3.0 use cv2.face.createLBPHFaceRecognizer() # pip install opencv-contrib-python # model = cv2.createLBPHFaceRecognizer() #change moodel name as per your name ranjit_model = cv2.face_LBPHFaceRecognizer.create() # Let's train our model ranjit_model.train(np.asarray(Training_Data), np.asarray(Labels))
print("Model trained sucessefully")
Step 3 - Run Our Facial Recognition In [9]: import cv2 import numpy as np import os 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) xyz=0 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 = ranjit_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 Ranjit", (250, 450), cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,0), 2) cv2.imshow('Face Recognition', image ) gmail_user= '' # Sender mailID gmail_password= '' # Sender Mail Password mail_from =gmail_user mail_to = '' # Receiver MailID mail_subject= 'hello' mail_message_body ='Your Face recognized!' mail_message= '''\ From:%s To:%s subject:%s %s '''%(mail_from,mail_to,mail_subject,mail_message_body) server= smtplib.SMTP_SSL('smtp.gmail.com',465) server.login(gmail_user,gmail_password) server.sendmail(mail_from,mail_to,mail_message) server.close() xyz=999 break elif confidence <=80 || confidence <=90: os.system("terraform init") os.system("terraform apply ec2EBS.tf -auto-approve") print("AWS Infra Creation Completed!") break else: cv2.putText(image, "I dont know, how r u", (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() if xyz==999:
pywhatkit.sendwhatmsg("+917xxxxxxxxx", "Hii This Is Ranjit !", 18,41)
- Let's see the terraform code.
- You must have an AWS profile configured and to configure you have to provide a Private key and public key. the command is: "aws configure --profile Your_name"
provider "aws" { region = "ap-south-1" profile = "ranjit" } resource "tls_private_key" "generated_key" { algorithm = "RSA" rsa_bits = 2048 } resource "local_file" "the_key" { content = tls_private_key.generated_key.private_key_pem filename = "mykey.pem" file_permission = 0400 } resource "aws_key_pair" "key" { //key_name = "my_private_key" public_key = tls_private_key.generated_key.public_key_openssh } resource "aws_default_vpc" "default" { tags = { Name = "Default VPC" } } resource "aws_security_group" "security_groups_created" { //name = "allow_ssh_http" description = "Allow ssh inbound traffic" vpc_id = aws_default_vpc.default.id ingress { description = "http" from_port = 80 to_port = 80 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } ingress { description = "ssh" from_port = 22 to_port = 22 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } egress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] } tags = { Name = "allowing http ssh" } } //output "security"{ //value=aws_security_group.allow_tls //} resource "aws_instance" "web" { ami = "ami-0447a12f28fddb066" instance_type = "t2.micro" key_name = aws_key_pair.key.key_name security_groups = [ aws_security_group.security_groups_created.name ] connection { type = "ssh" user = "ec2-user" private_key = tls_private_key.generated_key.private_key_pem host = aws_instance.web.public_ip } provisioner "remote-exec" { inline = [ "sudo yum install git httpd php -y", "sudo systemctl restart httpd", "sudo systemctl enable httpd" ] } tags = { Name = "ranjit AWS EC2 Instance" } } resource "aws_ebs_volume" "ebs1" { availability_zone = aws_instance.web.availability_zone size = 1 tags = { Name = "EBS volume" } } resource "aws_volume_attachment" "ebs_att" { device_name = "/dev/sdh" volume_id = aws_ebs_volume.ebs1.id instance_id = aws_instance.web.id force_detach = true } resource "null_resource" "null1"{ depends_on=[ aws_volume_attachment.ebs_att ] connection { type = "ssh" user = "ec2-user" private_key = tls_private_key.generated_key.private_key_pem host = aws_instance.web.public_ip } provisioner "remote-exec" { inline = [ "sudo mkfs.ext4 /dev/xvdh", "sudo mount /dev/xvdh /var/www/html", "sudo rm -rf /var/www/html/*", "sudo git clone https://github.com/ranjitben10/cloudtask.git /var/www/html" ] }
}
- Here I am coping some images and installing required packages to make OS a server that will show some images in the web app. We are mounting the /var/www/html with /dev/xvdh so if OS goes down we won't lose our data.
Task Completed...
Thank You.