OpenCV2窗口启动时冻结并关闭问题求助(人脸识别项目)
人脸识别程序摄像头窗口冻结/崩溃问题修复方案
核心问题分析与修复点:
- 循环内错误释放资源:
video_capture.release()和cv2.destroyAllWindows()被放在while True循环内部,第一次循环就会执行资源释放和窗口销毁,导致窗口直接关闭。需将这两行移到循环结束后执行。 - 帧处理逻辑缺失:
self.process_current_frame = not self.process_current_frame导致程序仅交替处理帧,且显示操作只在处理帧时执行,后续无画面更新引发窗口未响应。需移除该交替逻辑,保证每帧都处理并显示。 - 路径大小写不统一:加载人脸图片时,
os.listdir("Faces")与f'faces/{image}'路径大小写不一致,在区分大小写的系统中会导致人脸编码失败,需统一路径写法。 - 颜色参数无效:矩形框颜色
(0,0,25)数值过小,几乎不可见,改为标准BGR红色值(0,0,255)。
修正后的完整代码:
import face_recognition import os, sys import cv2 import numpy as np import math def face_confidence(face_distance, face_match_threshold=0.6): range_val = (1.0 - face_match_threshold) linear_val = (1.0 - face_distance) / (range_val * 2.0) if face_distance > face_match_threshold: return str(round(linear_val * 100, 2)) + '%' else: value = (linear_val + ((1.0 - linear_val) * math.pow((linear_val - 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 = [] def __init__(self): self.encode_faces() 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(os.path.splitext(image)[0]) else: print(f"警告:图片 {image} 中未检测到人脸,已跳过") print("已编码的人脸名单:", self.known_face_names) def run_recognition(self): video_capture = cv2.VideoCapture(0) if not video_capture.isOpened(): sys.exit('未找到视频源') while True: ret, frame = video_capture.read() # 判断是否成功读取帧 if not ret: print("无法读取视频帧") break # 处理每一帧,移除交替处理逻辑 small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25) rgb_small_frame = small_frame[:, :, ::-1] # 检测人脸位置和编码 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_names = [] for face_encoding in self.face_encodings: matches = face_recognition.compare_faces(self.known_face_encodings, face_encoding) name = 'Unknown' confidence = 'Unknown' face_distances = face_recognition.face_distance(self.known_face_encodings, face_encoding) if len(face_distances) > 0: best_match_index = np.argmin(face_distances) if matches[best_match_index]: name = self.known_face_names[best_match_index] confidence = face_confidence(face_distances[best_match_index]) self.face_names.append(f'{name}: ({confidence})') # 在原帧上绘制标注 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_SIMPLEX, 0.8, (255, 255, 255), 1) # 显示画面 cv2.imshow('Face Recognition', frame) # 按下q键退出循环 if cv2.waitKey(1) == ord('q'): break # 循环结束后再释放资源 video_capture.release() cv2.destroyAllWindows() if __name__ == "__main__": fr = FaceRecognition() fr.run_recognition()
内容的提问来源于stack exchange,提问作者Augustas Judickas
相关产品推荐
相关产品推荐

