face detection using python and opencv

Face Detection using OpenCV

Anime Face Detection using Python OpenCV

In this article, we shall implement a simple code to detect Anime faces from the original Image. Follow along and build your own Face Detection model using Python OpenCV.

Detect Single Face from the Image

Import cv2 Python library and matplotlib library to display Image.

import cv2
import matplotlib.pyplot as plt

Haar Cascade is a popular Object detection algorithm that is widely used to detect a frontal face, eyes, lips, license number plates, etc. This work was first proposed by Paul Viola and Michael Jones in their paper Rapid Object Detection using a Boosted Cascade of Simple Features. We will use this algorithm to detect the face from the Image. To do this you need to download the Haarcascade Frontal Face XML file.

Download the Haarcascade Frontal Face XML file from here and save it in the project folder.

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

Read the input Image

face detection using python and opencv
The left-hand side is the original image
face_img = cv2.imread('gojo.jpg')
plt.imshow(cv2.cvtColor(face_img,cv2.COLOR_BGR2RGB))

Once you read an input image, it’s time to detect the face using facecascade.detectMultiScale on the image.

faces = faceCascade.detectMultiScale(face_img)
print(faces)
Ouput:

array([[180, 178, 364, 364]], dtype=int32)

This will return a 2D array consisting of the vital points of the object detected. Each list consists of 4 elements, first two elements denote x and y coordinates i.e., the center of the object. The next two elements denote the width and height of the detected object.

len(faces) #returns a total number of images detected

#output: 1

With the help of the coordinates x,y,w, and h you can crop the face from the image. Since the returned data is in 2D dimension use a for loop to add a rectangle on the detected face.

for x,y,w,h in faces:
    cv2.rectangle(face_img,(x,y),(x+w,y+h),(0,255,0),3)
    cropped_image = face_img[y:y+h,x:x+w]
    plt.imshow(cv2.cvtColor(cropped_image,cv2.COLOR_BGR2RGB))
    plt.show()
face_detection_opencv

Add the rectangle on the original image denoting the detected face.

plt.imshow(cv2.cvtColor(face_img,cv2.COLOR_BGR2RGB))
plt.axis("off")
plt.savefig("output_with_crop.jpg")
output_image
output

Detect Multiple Faces

Up until now, we were able to crop just a single detected face. If you use the above code to detect multiple faces, you will be disappointed with the results. Instead, use this technique to detect multiple faces in an image.

multipleImg = cv2.imread("some_image_with_multiple_face",0)
#0 as second argument converts image into gray scale

#create Cascade Classifier
faceCascade2 = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
mulFace = faceCascade2.detectMultiScale(multipleImg)

print(mulFace)
print(len(mulFace))
Output:

array([[174,  45,  56,  56],
       [ 81,  55,  71,  71]], dtype=int32)

2 

We have two detected faces in the image.

for x,y,w,h in mulFace:
    temp = multipleImg[y:y+h,x:x+w]
    detectTemp = faceCascade2.detectMultiScale(temp)
    #further check for image
    if len(detectTemp) == 0:
        #return -999 if it detects false image.
        print(-999)
    else:
        for nx,ny,nw,nh in detectTemp:
            plt.imshow(cv2.cvtColor(multipleImg[y:y+h,x:x+w],cv2.COLOR_BGR2RGB))
            plt.show()

Join our Discord Server and become a part of the Anime Vyuh Community. We share content on 100DaysOfCodeAnime ReviewOne Piece Theory, and Character Analysis articles.

Subscribe to our Newsletter to never miss out on the content: https://animevyuh.org/newsletter. Join our Newsletter now for fantastic Anime recommendationsPython, and Machine Learning Content.

Support Us: https://www.buymeacoffee.com/trjtarunhttps://ko-fi.com/tarunrjain751.
GitHub: https://github.com/lucifertrj.
Twitter: https://twitter.com/TRJ_0751.

Want to learn Machine Learning with Proper Roadmap and resources? Then check this Repository: https://github.com/lucifertrj/100DaysOfML

Image Credits: MAPPA Studio- responsible for Animating Jujutsu Kaisen