Face recognition with Python and OpenCV

Face detection with Python

Here is how you can implement Face detection with Python and OpenCV in less than 25 lines of code:

  1. Install OpenCV.
  2. Now download the code from repo
  3. Now Let’s break down the code

# Get user supplied values

imagePath = sys.argv[1]

cascPath = sys.argv[2]

The above lines takes image and cascade as input. The default cascade will help in detecting image with OpenCV.

# Create the haar cascade

faceCascade = cv2.CascadeClassifier(cascPath)

Now we create a cascade, this loads the face cascade into memory for its use. Cascade is just an XML which contains data to detect faces.

# Read the image

image = cv2.imread(imagePath)

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

Here we read the image and convert it into Grayscale. A lot of operations in OpenCV are done in GrayScale.

# Detect faces in the image

faces = faceCascade.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags = cv2.cv.CV_HAAR_SCALE_IMAGE )

This function is the main function, which detects the actual face. The function detectMultiScale is a general function that detects objects. Since we are using face cascade it detects faces. It sends a GrayScale image as input.

Some faces may be closer to the camera, they would appear bigger than those faces in the back. ScaleFactor compensates for this. The detection algo uses a moving window to detect objects. MinNeighbours defines how many objects are detected near the current one before it declares the face around and minsize gives the size around.

The function returns a list of rectangles where it believes it found a face.

Thanks for dropping by !!! Feel free to comment to this post or you can drop me an email at naik899@gmail.com.

 

Leave a Reply

Your email address will not be published. Required fields are marked *