Python OpenCV人脸识别视频卡顿 跳帧优化后不显示识别框如何解决
问题原因分析
- 第一,帧率间隔逻辑写错:你原本想实现每10帧处理1次,但是代码里写的是
count%(10*fps) == 0,fps是摄像头每秒帧率,一般默认是30,这就变成每300帧(也就是10秒)才处理1次,自然很难看到标注 - 第二,识别结果没有缓存:你仅在处理帧的时候给当前帧画标注,剩下9帧都是新读取的原始画面,没有复用之前的识别结果画框,所以非处理帧不会显示任何标注
修复方案
- 修正间隔判断逻辑,改为每10帧处理1次:把
if count%(10*fps) == 0改成if count % 10 == 0 - 新增变量缓存上一次识别到的人脸位置、匹配姓名列表,每次处理帧更新缓存,所有帧都用缓存的结果绘制标注
- 可以根据需要调整间隔帧数,比如改成每5帧处理一次,平衡流畅度和识别实时性
修改后的完整代码
import cv2 import os import face_recognition KNOWN_FACES_DIR = 'known_faces' TOLERANCE = 0.5 FRAME_THICKNESS = 3 FONT_THICKNESS = 2 MODEL = 'hog' # 可选'cnn',有CUDA加速时性能更好 video = cv2.VideoCapture(0) fps = int(video.get(cv2.CAP_PROP_FPS)) print('Loading known faces...') known_faces = [] known_names = [] for name in os.listdir(KNOWN_FACES_DIR): for filename in os.listdir(f'{KNOWN_FACES_DIR}/{name}'): image = face_recognition.load_image_file(f'{KNOWN_FACES_DIR}/{name}/{filename}') encoding = face_recognition.face_encodings(image)[0] known_faces.append(encoding) known_names.append(name) def check_face(known_faces, known_names): count = 0 # 新增缓存变量,保存上一次识别的人脸位置和对应姓名 last_face_info = [] while True: ret, image = video.read() if not ret: break if count % 10 == 0: # 每10帧处理一次识别 current_face_info = [] locations = face_recognition.face_locations(image, model=MODEL) encodings = face_recognition.face_encodings(image, locations) for face_encoding, face_location in zip(encodings, locations): results = face_recognition.compare_faces(known_faces, face_encoding, TOLERANCE) match = None if True in results: match = known_names[results.index(True)] print(f"Match found: {match}") # 把识别到的位置和姓名存入临时列表 current_face_info.append((face_location, match)) # 更新缓存 last_face_info = current_face_info # 所有帧都用缓存的人脸信息画标注 for face_location, match in last_face_info: if match is None: continue # 画人脸框 top_left = (face_location[3], face_location[0]) bottom_right = (face_location[1], face_location[2]) color = [0,255,0] cv2.rectangle(image, top_left, bottom_right, color, FRAME_THICKNESS) # 画姓名标签 top_left = (face_location[3], face_location[2]) bottom_right = (face_location[1], face_location[2] + 22) cv2.rectangle(image, top_left, bottom_right, color, cv2.FILLED) cv2.putText(image, match, (face_location[3] + 10, face_location[2] + 15), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (200, 200, 200), FONT_THICKNESS) count += 1 # 显示画面 cv2.imshow("", image) if cv2.waitKey(1) & 0xFF == ord("q"): cv2.destroyAllWindows() break check_face(known_faces, known_names)
优化建议
如果人物移动速度快,觉得标注滞后明显,可以把间隔帧数从10调低到5~8,兼顾流畅度和标注跟随性。
内容的提问来源于stack exchange,提问作者user572575
相关产品推荐
相关产品推荐

