关于detectMultiScale返回值为元组的解决办法
1 网上纠错
完整代码:
import os
import cv2
def face_dateset():
cam = cv2.VideoCapture(0, cv2.CAP_DSHOW)
cam.set(3, 640) # set video width
cam.set(4, 480) # set video height
i = 0
face_detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# For each person, enter one numeric face id
face_id = input('\n enter user id end press <return> ==> ')
#face_id = 10
print("\n [INFO] Initializing face capture. Look the camera and wait ...")
# Initialize individual sampling face count
count = 0
files = './dataset/'+str(face_id)
folder = os.path.exists(files)
if not folder:
os.makedirs(files)
os.chmod(files, 0o777)
while (True):
ret, img = cam.read()
img = cv2.flip(img, 1) # flip video image vertically
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_detector.detectMultiScale(
gray,
scaleFactor=1.2,
minNeighbors=5
,
minSize=(20, 20)
)
if len(faces)>0:
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
count += 1
# Save the captured image into the datasets folder
cv2.imwrite(files + '.' + str(count) + ".jpg", gray[y:y + h, x:x + w])
cv2.imshow('image', img)
k = cv2.waitKey(100) & 0xff # Press 'ESC' for exiting video
if k == 27:
break
elif count >= 30: # Take 30 face sample and stop video
break
# Do a bit of cleanup
print("\n [INFO] Exiting Program and cleanup stuff")
cam.release()
cv2.destroyAllWindows()
return face_id
找了很多网上教程,说什么face_detector = cv2.CascadeClassifier(‘haarcascade_frontalface_default.xml’) 没有正确调用。
最后发现问题是:
cv2.imshow('image', img)
需要把这个写在循环if len(faces)>0:的外面,当启动这个界面后,需要把人脸放到摄像头下面,当检测到人脸后,detectMultiScale的返回元组就不为空咯