Python face_recognition模块摄像头人脸无识别问题求助
人脸识别摄像头无法检测人脸问题排查
我尝试复现类模式匹配的人脸识别代码,但摄像头无法识别任何人脸。运行两个来源的完整代码后结果一致:程序能加载参考图片、启动摄像头,但无法检测到任何内容,且无报错信息。
代码
import face_recognition import os, sys, cv2, math, dlib import numpy as np def face_confidence(face_distance, face_match_threshold=0.6): range = (1.0 - face_match_threshold) linear_value = (1.0 - face_distance) / (range * 2.0) if face_distance > face_match_threshold: return str(round(linear_value * 100, 2)) + '%' else: value = (linear_value + ((1.0 - linear_value) * math.pow((linear_value - 0.5)*2, 0.2))) * 100 return str(round(value, 2)) + '%' class FaceRecognition: face_locations = [] face_encodings = [] face_names = [] known_face_encodings = [] known_face_names = [] process_current_frame = True def __init__(self) -> None: self.encode_faces() def encode_faces(self): for image in os.listdir('faces'): face_image = face_recognition.load_image_file(f'faces/{image}') face_encoding = face_recognition.face_encodings(face_image) self.known_face_encodings.append(face_encoding) self.known_face_names.append(image) print(self.known_face_names) def run_recognition(self): video_capture = cv2.VideoCapture(0) if not video_capture.isOpened(): sys.exit('camera não encontrada') while True: ret, frame = video_capture.read() if self.process_current_frame: small_frame = cv2.resize(frame, (0,0), fx=0.25, fy=0.25) rgb_small_frame = small_frame[:,:, ::-1] #find all the faces in current frame self.face_locations = face_recognition.face_locations(rgb_small_frame) # self.face_encodings = face_recognition.face_encodings(rgb_small_frame, self.face_locations) self.face_encodings = face_recognition.face_encodings( rgb_small_frame, [dlib.rectangle(*face_location) for face_location in self.face_locations] # Convert face_locations to dlib rectangles ) self.face_names = [] for face_encoding in self.face_encodings: matches = face_recognition.compare_faces(self.known_face_encodings, face_encoding) name = 'Não Autorizado' confidence = 'Unknown' face_distances = face_recognition.face_distance(self.known_face_encodings, face_encoding) best_match_index = np.argmin(face_distances) if matches[best_match_index]: print('aaa') name = self.known_face_names[best_match_index] confidence = face_confidence(face_distances[best_match_index]) # print(confidence) self.face_names.append(f'{name} ({confidence})') self.process_current_frame = not self.process_current_frame #Display Annotations for (top, right, bottom, left), name in zip(self.face_locations, self.face_names): top *= 4 right *= 4 bottom *= 4 left *= 4 cv2.rectangle(frame, (left, top), (right, bottom), (0,0,255), 2) cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0,0,255), -1) cv2.putText(frame, name, (left + 6, bottom - 6), cv2.FONT_HERSHEY_DUPLEX, 0.8, (255,255,255), 1) cv2.imshow("Face Recognition", frame) if cv2.waitKey(1) == ord('q'): break video_capture.release() cv2.destroyAllWindows() if __name__ == '__main__': fr = FaceRecognition() fr.run_recognition()
环境信息
(cv) [hnz@aspire-5 ~/Downloads/source code]$ conda list # packages in environment at /home/hnz/anaconda3/envs/cv: # # Name Version Build Channel _libgcc_mutex 0.1 main _openmp_mutex 5.1 1_gnu bzip2 1.0.8 h7b6447c_0 ca-certificates 2023.12.12 h06a4308_0 click 8.1.7 pypi_0 pypi contourpy 1.2.0 pypi_0 pypi cycler 0.12.1 pypi_0 pypi dlib 19.24.2 pypi_0 pypi expat 2.5.0 h6a678d5_0 face-recognition 1.3.0 pypi_0 pypi face-recognition-models 0.3.0 pypi_0 pypi fonttools 4.47.2 pypi_0 pypi kiwisolver 1.4.5 pypi_0 pypi ld_impl_linux-64 2.38 h1181459_1 libffi 3.4.4 h6a678d5_0 libgcc-ng 11.2.0 h1234567_1 libgomp 11.2.0 h1234567_1 libstdcxx-ng 11.2.0 h1234567_1 libuuid 1.41.5 h5eee18b_0 matplotlib 3.8.2 pypi_0 pypi ncurses 6.4 h6a678d5_0 numpy 1.26.3 pypi_0 pypi opencv-python 4.9.0.80 pypi_0 pypi openssl 3.0.12 h7f8727e_0 packaging 23.2 pypi_0 pypi pillow 10.2.0 pypi_0 pypi pip 23.3.1 py312h06a4308_0 pyparsing 3.1.1 pypi_0 pypi pyqt5 5.15.10 pypi_0 pypi pyqt5-qt5 5.15.2 pypi_0 pypi pyqt5-sip 12.13.0 pypi_0 pypi python 3.12.0 h996f2a0_0 python-dateutil 2.8.2 pypi_0 pypi readline 8.2 h5eee18b_0 setuptools 68.2.2 py312h06a4308_0 six 1.16.0 pypi_0 pypi sqlite 3.41.2 h5eee18b_0 tk 8.6.12 h1ccaba5_0 tzdata 2023d h04d1e81_0 wheel 0.41.2 py312h06a4308_0 xz 5.4.5 h5eee18b_0 zlib 1.2.13 h5eee18b_0
解决方法
修复人脸编码存储错误:
face_recognition.face_encodings返回的是列表,直接存入known_face_encodings会导致后续匹配逻辑错误,需确保提取到有效编码后再存储:def encode_faces(self): for image in os.listdir('faces'): face_image = face_recognition.load_image_file(f'faces/{image}') face_encodings = face_recognition.face_encodings(face_image) if face_encodings: face_encoding = face_encodings[0] self.known_face_encodings.append(face_encoding) self.known_face_names.append(image.split('.')[0]) print(self.known_face_names)移除不必要的dlib矩形转换:
face_recognition.face_encodings可直接使用face_locations的输出格式,无需手动转换,改回原代码注释行:self.face_encodings = face_recognition.face_encodings(rgb_small_frame, self.face_locations)验证人脸检测功能:添加打印语句确认是否检测到人脸位置,定位问题环节:
self.face_locations = face_recognition.face_locations(rgb_small_frame) print(f"检测到人脸数量: {len(self.face_locations)}")调整帧缩放比例:当前0.25倍缩放可能导致低分辨率下人脸检测失败,尝试改为0.5倍并对应调整坐标放大倍数:
small_frame = cv2.resize(frame, (0,0), fx=0.5, fy=0.5) # 后续标注坐标时改为乘以2 top *= 2 right *= 2 bottom *= 2 left *= 2检查摄像头索引:若
cv2.VideoCapture(0)无法调用摄像头,尝试更换索引值(如1):video_capture = cv2.VideoCapture(1)优化拍摄环境:确保光线充足,人脸正对摄像头,无遮挡物。
内容的提问来源于stack exchange,提问作者Vinícius Hansen
相关产品推荐
相关产品推荐

