我有一些包含单张或多张面孔的图像,但是如果图像中有多张面孔,我只想选择一个面孔。我使用OpenCV python通过haar-cascade来检测人脸,这是完美的方法,但是我无法使用多个人脸检测器从图像中选择特定的人脸。我的代码如下:
cascPath = "Python35\\Lib\\site-packages\\cv\\data\\haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
listing = os.listdir(path\of\images)
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
出现问题时,有人可以帮我吗,我选择了已经建立的矩形,为什么要拒绝呢?
答案 0 :(得分:0)
可以在迭代,运行代码并向我们显示输出之前打印出faces对象吗?错误到底在哪一行上?
答案 1 :(得分:0)
我按照以下方法解决了与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