Face Detection using python

Face Detection using python

Task 06 ???????

Team Task

Task Description ??

?? 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

?? 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.

?? It send mail to your mail id

?? Create EC2 instance in the AWS using CLI.

?? Create 5 GB EBS volume and attach it to the instance.

Here I have integrated TERRAFORM for the above case .


  • Lets initialize the webcam first, load haarcascade model and collect the pictures to create our dataset
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 = './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")
  • Next step is to train the model.
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()


model  = cv2.face_LBPHFaceRecognizer.create()
# Let's train our model 
model.train(np.asarray(Training_Data), np.asarray(Labels))
print("Model trained sucessefully")

  • Next step is to predict according to the conditions mentioned in the task description. For the case where friends face is detected, i have created terraform code for that. Wewill initialize it and run the code using python only.
import cv2
import numpy as np
import os


import smtplib
from email.message import EmailMessage




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 = 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 > 80:
            cv2.putText(image, "Hey Shradha", (250, 450), cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,0), 2)
            cv2.imshow('Face Recognition', image )
            sendmail()
            whatsapp()
            break
         
        else:
            
            os.system("terraform init")
            os.system("terraform apply --auto-approve")


            print(" AWS EC2 Instance Successfully created and 5GB EBS Volume is attched to it.")


    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()

  • code for whatsapp() and sendmail() functions:
def whatsapp():


    import pywhatkit as pwt


    
    number = "+91XXXXXXXXXX"
    
    mess = "Hey, how are you? "
    
    time = 16
    mint = 15
    
    pwt.sendwhatmsg(number,mess,int(time),int(mint))
    
    print("\t\t\t\n======================= Whatsapp message Successfully Sended           ==================================\n")


def sendmail():
    server= smtplib.SMTP('smtp.gmail.com',587)
    server.starttls()
    server.login("shradha.seth98@gmail.com", "PASSWORD")
    email=EmailMessage()
    email['From']="shradha.seth98@gmail.com"
    email['To']="shradha.seth98@gmail.com"
    email['Subject']="hi"
    message="hi"
    email.set_content(message)
    server.send_message(email)
    
    print("\t\t\t\n======================= Email Successfully Sended ==================================\n")


Harshit Mathur

Seeking for Cloud DevOps/Support Role(Immediate Joiner) | AWS DevOps Engineer | Master's in Cloud Computing | Automation/API Tester

3 å¹´

We be done easily.

赞
回复
Harshit Mathur

Seeking for Cloud DevOps/Support Role(Immediate Joiner) | AWS DevOps Engineer | Master's in Cloud Computing | Automation/API Tester

3 å¹´

What if we successful to make this problem sovle?

赞
回复

要查看或添加评论,请登录

Shradha Seth的更多文章

  • k-mean clustering in security domain

    k-mean clustering in security domain

    ? Clustering:- Clustering is one of the most common exploratory data analysis technique used to get an intuition about…

    1 条评论
  • Javascript!!

    Javascript!!

    ?? Task 7.2 - ?? Write a blog explaining the usecase of javascript in any of your favorite industries.

  • Confusion Matrix and cyber security

    Confusion Matrix and cyber security

    Confusion matrix is a fairly common term when it comes to machine learning. Today I would be trying to relate the…

  • GUI Application On Docker Container?? ??????

    GUI Application On Docker Container?? ??????

    ?? Task Description?? ?? GUI container on the Docker ?? Launch a container on docker in GUI mode ?? Run any GUI…

  • Deploying Simple Machine Learning Model inside Docker Container

    Deploying Simple Machine Learning Model inside Docker Container

    Task Description ?? ?? Pull the Docker container image of CentOS image from Docker Hub and Create a new container ??…

    1 条评论
  • Creating VPC Infrastucture and NAT gateway using Terraform

    Creating VPC Infrastucture and NAT gateway using Terraform

    The goal is to create a scenario in which we will create our own virtual private cloud (VPC) with a public and a…

    2 条评论
  • Creating VPC Infrastucture: Terraform & Hosting WordPress

    Creating VPC Infrastucture: Terraform & Hosting WordPress

    We have to create a web portal for our company with all the security as much as possible. So, we use Wordpress software…

  • Creating AWS infrastructure with AWS: EFS using Terraform

    Creating AWS infrastructure with AWS: EFS using Terraform

    Task details: Create the key and security group which allow the port 80. Launch EC2 instance.

  • LAUNCH NEXT CLOUD WITH EKS

    LAUNCH NEXT CLOUD WITH EKS

    AWS (Amazon Web Services) is a comprehensive, evolving cloud computing platform provided by Amazon that includes a…

社区洞察

其他会员也浏览了