Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to crop and save the detected faces in OpenCV Python?
OpenCV provides Haar cascade classifiers for detecting faces in images. When a face is detected, you get coordinates (x, y, w, h) representing the face's position and dimensions. To crop and save the detected face, we use array slicing: image[y:y+h, x:x+w].
How to Download Haar Cascades
You can find different Haar cascades on the GitHub repository:
https://github.com/opencv/opencv/tree/master/data/haarcascadesTo download the Haar cascade for human face detection, click on the haarcascade_frontalface_default.xml or haarcascade_frontalface_alt.xml file. Open it in raw format, right-click and save the file.
Note: Save all Haar cascade XML files in a dedicated folder for easy access.
Steps to Crop and Save Detected Faces
Import the required library OpenCV and ensure it's installed.
Read the input image using cv2.imread() and convert it to grayscale.
Create a Haar cascade classifier object using cv2.CascadeClassifier() with the XML file path.
Detect faces using face_cascade.detectMultiScale() which returns coordinates in (x,y,w,h) format.
Loop through detected faces, crop using image[y:y+h, x:x+w], and save with cv2.imwrite().
Optionally display the cropped faces for visualization.
Example 1: Single Face Detection
This example demonstrates cropping and saving a single face from an image ?
# import required libraries
import cv2
# read the input image
img = cv2.imread('woman.jpg')
# convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# read the haarcascade to detect faces
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_default.xml')
# detect faces in the input image
faces = face_cascade.detectMultiScale(gray, 1.3, 4)
print('Number of detected faces:', len(faces))
# loop over all detected faces
if len(faces) > 0:
for i, (x, y, w, h) in enumerate(faces):
# draw rectangle around face
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 255), 2)
# crop the face
face = img[y:y + h, x:x + w]
# save the cropped face
cv2.imwrite(f'face{i}.jpg', face)
print(f"face{i}.jpg is saved")
# display cropped face
cv2.imshow("Cropped Face", face)
# display the image with detected faces
cv2.imshow("image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
The output of the above code is ?
Number of detected faces: 1 face0.jpg is saved
Example 2: Multiple Face Detection
This example shows cropping and saving multiple faces from a single image ?
# import required libraries
import cv2
# read the input image
img = cv2.imread('two-men.jpg')
# convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# read the haarcascade to detect faces
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')
# detect faces in the input image
faces = face_cascade.detectMultiScale(gray, 1.1, 4)
print('Number of detected faces:', len(faces))
# loop over all detected faces
if len(faces) > 0:
for i, (x, y, w, h) in enumerate(faces):
# draw rectangle around face
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 255), 2)
# crop the face
face = img[y:y + h, x:x + w]
# save the cropped face
cv2.imwrite(f'face{i}.jpg', face)
print(f"face{i}.jpg is saved")
# display each cropped face
cv2.imshow(f"Cropped Face {i}", face)
# display the image with detected faces
cv2.imshow("image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
The output of the above code is ?
Number of detected faces: 2 face0.jpg is saved face1.jpg is saved
Key Parameters
The detectMultiScale() function accepts important parameters:
scaleFactor: Specifies how much the image size is reduced at each scale (e.g., 1.1, 1.3)
minNeighbors: How many neighbors each face rectangle should retain (higher values = fewer false positives)
minSize: Minimum possible face size (smaller faces are ignored)
Conclusion
OpenCV's Haar cascades provide an effective way to detect and crop faces from images. Use detectMultiScale() to find face coordinates, then apply array slicing to extract and save individual face regions.
