Create Training Data
import cv2
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 = r’F:\programs\computervision folder\face-detection/faces’+ 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
cap.release()
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 = ‘\F:\programs\computervision folder\face-detection\faces’
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)
if image is None:
image = DEFAULT_VALUE
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()
#face_model = cv2.face.LBPHFaceRecognizer.create()
face_model = cv2.face.LBPHFaceRecognizer_create()
# Let’s train our model
#face_model.train(np.asarray(Training_Data), np.asarray(Labels))
#AttributeError: ‘NonType’ object has no attribute ‘shape’
face_model.train( np.asarray(Training_Data) ,np.asarray(Labels) )
print(“done”)
print(“Model trained sucessefully”)
Step 3 — Run Our Facial Recognition
Step 3 — Run Our Facial Recognition
import cv2
import numpy as np
import os
import time
#import pywhatkit
import smtplib
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)
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 = vimal_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 narmada”, (250, 450), cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,0), 2)
cv2.imshow(‘Face Recognition’, image )
email = ‘muhamedelias.cs18@bitsathy.ac.in’ # Your email
password = ‘xxxxxx’ # Your email account password
send_to_email = ‘narmada.cs18@bitsathy.ac.in’ # Who you are sending the message to
message = ‘This Mail has sent’ # The message in the email
server = smtplib.SMTP(‘smtp.gmail.com’, 587) # Connect to the server
server.starttls() # Use TLS
server.login(email, password) # Login to the email server
server.sendmail(email, send_to_email , message) # Send the email
server.quit()
print(“Email sent successfully”)
# Logout of the email server
pywhatkit.sendwhatmsg_instantly(phone_no=”+919025734898",
message=”Hey your face has recoginzed succesfully”)
print(“Whatsapp Message sent Successfully!!”)
break
else:
os.system(“aws ec2 run-instances — image-id ami-010aff33ed5991201 — instance-type t2.micro — subnet-id subnet-d1a9bdb9 — count 1 — security-group-ids sg-0c7ede89d9fa09455 — key-name Awsclikey1 > ec2.txt”)
print(“Instance Launched Successfully”)
os.system(“aws ec2 create-volume — availability-zone ap-south-1a — size 5 — volume-type gp2 — tag-specification ResourceType=volume,Tags=[{Key=face,Value=volume}] > ebs.txt”)
print(“Volume Created Successfully”)
print(“Please wait till the instance is initializing”)
time.sleep(60)
ec2_id = open(“ec2.txt”, ‘r’).read().split(‘,’)[3].split(‘:’)[1].split(‘“‘)[1]
ebs_id = open(“ebs.txt”, ‘r’).read().split(‘,’)[6].split(‘:’)[1].split(‘“‘)[1]
os.system(“aws ec2 attach-volume — instance-id “ + ec2_id +” — volume-id “ + ebs_id +” — device /dev/xvdf”)
print(“Volume Successfully attached to the instance”)
break
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()
Create a program that perform below mentioned task upon recognizing a particular face.
📌 When it recognize your face then -
👉 It send mail to your mail id by writing this is face of your_name.
👉 Second it send whatsapp message to your friend, it can be anything.
📌 When it recognize second face, it can be your friend or family members face.
👉 Create EC2 instance in the AWS using CLI.
👉 Create 5 GB EBS volume and attach it to the instance.
#worldrecordholder #training #internship #makingindiafutureready #summer #summertraining #python #machinelearning #aws #awscli #cv2 #rightmentor #linuxworld #vimaldaga #righteducation