Locating a Face with Live Web Cam using OpenCV Python

In previous post we did simple WebCam interfacing in that code we provided the method to read webcam and grab frame from camera and displaying that frame.

In today's post we are going to do some image processing. First step we are going to do is locating if the face is present in front of web cam? and if it is, then draw a rectangle across that Face.





Here is the code in python for face detection and localization in live video fed from webcam




#================================================================
#
#   IN THE NAME OF ALLAH,THE MOST BENEFICENT, THE MOST MERCIFUL
#
# 1-NOV-2015  10:50PM
#===============================================================

import cv2
import numpy as np


video_capture = cv2.VideoCapture(0)

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')



if __name__ == '__main__':
    
    while True:
        #=============================================================
        # Capture frame-by-frame
        #--------------------------------------------------------------
        
        ret, frame = video_capture.read()
        
        #===================================
        #do all processing Here
        #-----------------------------------
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(
                gray,
                scaleFactor=1.1,
                minSize=(50, 50),
                flags=cv2.cv.CV_HAAR_SCALE_IMAGE


                )
        for (x,y,w,h) in faces:
            c_gray = gray[y:y+h,x:x+w]
            cv2.rectangle(frame,(x,y),(x+w,y+h), (0,0,255),2)






        #===================================
        # Display the resulting frame
        #-----------------------------------
        cv2.imshow('Video', frame)
        k=cv2.waitKey(1)
        if k & 0xFF == ord('q'):            
            break



    # When everything is done, release the capture
    video_capture.release()
    cv2.destroyAllWindows()




#========================={End of the Code}===================================

        



Comments