Real Time Face Detection using Haar Cascade Algorithm and cloning detected face.

Haar Cascade is a machine learning object detection algorithm used to identify objects in an image or video and based on the concept of  features proposed by Paul Viola and Michael Jones in their paper "Rapid Object Detection using a Boosted Cascade of Simple Features" in 2001.

It is a machine learning based approach where a cascade function is trained from a lot of positive and negative images. It is then used to detect objects in other images.

The algorithm has four stages:

  1. Haar Feature Selection
  2. Creating  Integral Images
  3. Adaboost Training
  4. Cascading Classifiers
OpenCV comes with a trainer as well as detector. If you want to train your own classifier for any object like car, planes etc. you can use OpenCV to create one. Its full details are given here: Cascade Classifier Training.
Here we will deal with detection. OpenCV already contains many pre-trained classifiers for face, eyes, smile etc. Those XML files are stored in opencv/data/haarcascades/ folder. Let's create face  detector with OpenCV. in the end one can crop the detected face for making real time face database.


let's do it..
croping_database.py

import numpy as np
import cv2
import time
import os
cap=cv2.VideoCapture(0)
faceCascade = cv2.CascadeClassifier('/home/PycharmProjects/opencv/venv/lib/python3.6/site-packages/cv2/data/haarcascade_frontalface_alt.xml')
# haarcascade _frontalface _alt.xml file  can be download from github:https://github.com/opencv/opencv/blob/master/data/haarcascades/haarcascade_frontalface_alt.xml 


d=0while(True):
    ret, frame= cap.read()
    gray=cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.2,
        minNeighbors=5,
        minSize=(20, 20)
    )
    for (x,y,w,h) in faces:
        cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = frame[y:y+h, x:x+w]
        clone=frame.copy()
        crop_img=clone[y:y+h, x:x+w]
        cv2.imshow("crop",crop_img)


        if d<50:
            path = "/home/dnkembd/Desktop/juhi_opencv/5/_%d.jpg" % d
#folder path where crop image will be stored
            cv2.imwrite(path, crop_img)
            d+=1        else:
            print("data base is created")
    d=0    cv2.imshow("frame",frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()

Figure:1 real time face detection

Figure:2 Face Detection on screen

Figure: 3 Multiple face detection in one frame using haar cascade 

This detected face will be store in folder. every time face detected than square part of the frame will be clone and store that face database in folder or its appropriate path. in next blog we will see Real time Face Recognition.

   

Comments

Popular posts from this blog

Voice Recognition Using web camera and Google API - Raspberry pi 3B (python)