Cropping Faces from Images using OpenCV – Python
Opencv is a python library mainly used for image processing and computer vision. In this article first, we detect faces after that we crop the face from the image. Face detection is the branch of image processing that uses to detect faces.
We will use a pre-trained Haar Cascade model to detect faces from the image. A haar cascade is the object detection method used to detect objects from the image. This algorithm was trained by numerous images. You can download the face haar cascade file by click here.
Let’s Implementation in stepwise:
Step 1: In this step, we will read the image and converted it into grayscale.
Explanation: In this code first we import our opencv library using import cv2. cv2.imread() method loads the image from the given path(ex:mpw.jpeg or filepath/mpw.jpeg) After loading the image we convert the image to a grayscale image using COLOR_BGR2GRAY.
Step 2: Use the Haar Cascade model to detect faces from the image.
Explanation: We use cv2.CascadeClassifier for load haarcascade file in face_cascade. detectMultiScale() function used for detect faces.It takes 3 parameters:
- Gray: input image(gray scale image)
- 1.1: scale factor, it specifies how much the image size is reduced with each scale. It improves detection.
- 4: MinNeighbours, specifies how many neighbors each candidate rectangle should have to retain.
Step 3: Find the face in the image.
Explanation: x,y are pixel location of faces, w,h are width and height of faces. cv2.rectangle() function used for draw rectangle over the detected object, img is input image, (x,y),(x+w, y+h) are locations of rectangle,(0,0,255) is color of a rectangle this argument gets passed as a tuple for BGR,we would use (0,0,255) for red, 2 is thickness of rectangle.
Below is the full implementation:
Image Used –
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course