首页 > 解决方案 > select specific face from multiple detected faces inside image from Haar-cascade in python

问题描述

I have some images containing single or multiple faces, but I want to select only one face if image have multiple faces inside. I used OpenCV python to detect face with haar-cascade which is do perfectly, but I cannot select specific face from images with multiple face detector. My code is as bellow:

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()

This code work successfully if image contains only one face, but when there are multiple face and I want to select one of them by entering the index of it, I get the following error.

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

Can anyone please help me when is the problem, I select the already founded rectangle, why reject it.

标签: pythonface-detection

解决方案


Can you print the faces object before you iterate, run your code, and show us what the output is? Which line exactly is the error on?


推荐阅读