How to detect multiple faces from the same image?

2.5k views Asked by At

I am trying to crop multiple faces from the same image using python and opencv but it is showing me error. If there is any other way of doing it please let me know. Below is the code along with the error.

import cv2

# Load some pre-trained data on face frontals from opencv (haar cascade algorithm)
trained_face_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

# Choose an image to detect faces in
img = cv2.imread('mask.png')
    
# Must convert to greyscale
grayscaled_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
# Detect Faces 
face_coordinates = trained_face_data.detectMultiScale(grayscaled_img)

img_crop = []

# Draw rectangles around the faces
for (x, y, w, h) in face_coordinates:
    cv2.rectangle(img, (x,y), (x+w, y+h), (0, 255, 0), 2)
    img_crop.append(img[y:y+h, x:x+w])

    
cv2.imshow('Cropped', img_crop)

cv2.waitKey()

**TypeError**                                 Traceback (most recent call last)
<ipython-input-4-7c85402c34e9> in <module>
     32 [enter image description here][1]
     33 
---> 34 cv2.imshow('Cropped', img_crop)
     35 #cv2.imshow('crop', img_crop2)
     36 #cv2.imshow('Face Detector',  img)

TypeError: Expected Ptr<cv::UMat> for argument 'mat'e here
1

There are 1 answers

0
Ahx On BEST ANSWER

One solution is, after storing all images in the list:

Display each image one at a time

for cropped in img_crop:
    cv2.imshow('Cropped', cropped)
    cv2.waitKey(0)

Assume your input image:

enter image description here

Result:

enter image description here enter image description here

If you want to save them, you could do:

for counter, cropped in enumerate(img_crop):
    cv2.imshow('Cropped', cropped)
    cv2.imwrite("pose_result_{}.png".format(counter), cropped)
    cv2.waitKey(0)

Code:

import cv2
import numpy as np

# Load some pre-trained data on face frontal from opencv (haar cascade algorithm)
trained_face_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

# Choose an image to detect faces in
img = cv2.imread('mask.png')

# Must convert to greyscale
grayscaled_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Detect Faces
face_coordinates = trained_face_data.detectMultiScale(grayscaled_img)

img_crop = []

# Draw rectangles around the faces
for (x, y, w, h) in face_coordinates:
    cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
    img_crop.append(img[y:y + h, x:x + w])

for counter, cropped in enumerate(img_crop):
    cv2.imshow('Cropped', cropped)
    cv2.imwrite("pose_result_{}.png".format(counter), cropped)
    cv2.waitKey(0)