python - 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.
解决方案
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?
推荐阅读
- java - 当我们在 java 中创建 Integer 类的实例时会发生什么
- android - 如何在 Unity Split Binary Build 中获得 Application.dataPath 等结果
- android - 如何通过appium执行模拟器命令
- php - 如何ajaxify在后端执行SQL的PHP函数?
- c# - 如何在 xamarin.forms 应用程序中实现附有真钱的虚拟硬币
- reactjs - 如果道具改变了,我可以通过什么方式给出初始值,以避免反模式效应
- orbeon - 如何使屏幕阅读器可以使用提示文本?
- arrays - 如何找到数字数组中的所有范围
- ruby-on-rails - Watir:元素存在但.exists?返回假
- git - 删除分支后测试 Git 存储库大小减少