【问题标题】:How to detect multiple faces from the same image?如何从同一图像中检测多个人脸?
【发布时间】:2021-01-15 11:51:15
【问题描述】:

我正在尝试使用 python 和 opencv 从同一图像中裁剪多个面孔,但它显示错误。 如果有任何其他方法,请告诉我。 以下是错误代码。

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

【问题讨论】:

  • 您使用图像列表 (img_crop) 调用 imshow,但它需要一个图像。您一次只能在打开的单个窗口中显示一张图片,因此,您可以在 img_crop 上执行 for 循环

标签: python opencv crop face-detection viola-jones


【解决方案1】:

一种解决方案是,在将所有图像存储在列表中之后:

每次显示一张图片

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

假设您的输入图像:

结果:

如果你想保存它们,你可以这样做:

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

代码:

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)

【讨论】:

    猜你喜欢
    • 2019-10-11
    • 2013-11-24
    • 2021-11-13
    • 2019-12-01
    • 2012-11-17
    • 2016-02-06
    • 2010-11-10
    • 2019-08-02
    • 2017-06-01
    相关资源
    最近更新 更多