【发布时间】:2025-12-07 20:40:01
【问题描述】:
我尝试使用从 pc cam 捕获图像/视频的 OpenCV 进行人脸检测和识别。但是当我运行它时会发生这个错误
$ python face_recog.py
Traceback (most recent call last):
File "face_recog.py", line 28, in <module>
if face_extractor(frame) is not None:
File "face_recog.py", line 19, in face_extractor
return cropped_face | ''
UnboundLocalError: local variable 'cropped_face' referenced before assignment
这里是我的应用程序的完整代码。基本上,它导入库并读取 XML 文件中的 haar 级联对象库。然后使用 face_extractor 函数从摄像头读取图像/视频
import cv2
import numpy as np
face_path = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
def face_extractor(img):
#img_umat = cv2.UMat(img)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
face = face_path.detectMultiScale(gray, 1.3, 5)
if face in ():
return None
for(x, y, w, h) in face:
cropped_face = img[y: y+h, x: x+w]
return cropped_face
capture = cv2.VideoCapture(0, cv2.CAP_DSHOW) #captureDevice = camera
count = 0
while True:
ret, frame = capture.read()
if face_extractor(frame) is not None:
count = count + 1
face = cv2.resize(face_extractor(frame), (200, 200))
#face_umat = cv2.UMat(face)
face = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)
output_path = "C:/Users/bryan/Desktop/test/Cascade/Output_img/user"+str(count)+".jpg"
cv2.imwrite(output_path, face)
cv2.putText(face, str(count), (50, 50), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 0), 2)
cv2.imshow("face cropper", face)
else:
print("FACE NOT FOUND !")
pass
if cv2.waitKey(1) == 13 or count == 100:
break
capture.release()
cv2.destroyAllWindows()
print("ALL SAMPLES COLLECTED !!")
【问题讨论】:
-
if face in ():永远是 False,AFAIK。因此,如果face为空,则cropped_face未定义。尝试将if face in ():更改为if not face:。 -
什么是
type(face)? -
尝试
if not face.length():或其他测试face是否为空的方法。这完全取决于type(face)是什么。 -
面值来自face_path.detectMultiScale
标签: python opencv image-processing face-detection haar-classifier