从 Python 中 Haar-Cascade 的图像内检测到的多个人脸中选择特定的人脸



我有一些包含单个或多个面的图像,但如果图像内部有多个面,我只想选择一张面。我使用 OpenCV python 通过 haar-cascade 检测人脸,这很完美,但我无法从具有多个人脸检测器的图像中选择特定的人脸。我的代码如下:

cascPath = "Python35\Lib\site-packages\cv\data\haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)

listing = os.listdir(pathofimages)
print("Detection face of new individual images")
for file in listing:
im = (path1 + '\' + imagePath + '\' + file)
imag = cv2.imread(im)
imag = imutils.resize(imag, width=500)
gray = cv2.cvtColor(imag, cv2.COLOR_BGR2GRAY)
# Detect faces in the image
faces = faceCascade.detectMultiScale(gray)
print("Founded face is {} faces which are {}".format(len(faces), faces))
if len(faces)>1:
i = 0
for (x, y, w, h) in faces:
cv2.rectangle(imag, (x, y), (x + w, y + h), (255, 0, 0), 2)
cv2.putText(imag, "Face #{}".format(i), (x - 10, y - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
i = i + 1
cv2.imshow("im", imag)
cv2.waitKey(0)
cv2.destroyAllWindows()
var = int(input("Which face you want to detect it"))
faces = faces[var]
print("Selected face is", faces)
print("type of selected face",type(faces))

print("the drawing face is", faces)
# Draw a rectangle around the face
for (x, y, w, h) in faces:
cv2.rectangle(imag, (x, y), (x + w, y + h), (255, 0, 0), 2)
roi_gray = gray[y:y + h, x:x + w]
roi_color = imag[y:y + h, x:x + w]
cv2.imshow("face", roi_color)
cv2.waitKey(0)
cv2.destroyAllWindows()

如果图像仅包含一张脸,则此代码可以成功工作,但是当有多个人脸并且我想通过输入其索引来选择其中一张时,我收到以下错误。

for (x, y, w, h) in faces:
TypeError: 'numpy.int32' object is not iterable

当问题出现时,任何人都可以帮助我,我选择已经建立的矩形,为什么要拒绝它。

你能在迭代之前打印 faces 对象,运行你的代码,并向我们展示输出是什么吗?错误究竟在哪一行?

我解决了与面部迭代器相关的问题,如下所示并成功工作。

if len(faces) > 1:
i = 0
for f in faces:
face = faces[i]
(x, y, w, h) = face
cv2.rectangle(imag, (x, y), (x + w, y + h), (255, 0, 0), 2)
cv2.putText(imag, "Face #{}".format(i), (x - 10, y - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
i = i + 1

最新更新