基于OpenCV与dlib人脸关键点检测器的人脸计数及指标标注代码需求
Got it, let's break down how to solve both of your OpenCV + dlib tasks clearly:
1. 实现人脸数量统计(结合OpenCV与dlib Facial Landmark Detector)
First, you'll need to set up the basic pipeline for face detection and landmark prediction. Here's a complete working example:
Step 1: Install dependencies
Make sure you have these packages installed:
pip install opencv-python dlib imutils
Step 2: Full code to count face numbers
import cv2 import dlib from imutils import face_utils # Load dlib's pre-trained face detector and landmark predictor detector = dlib.get_frontal_face_detector() # 你需要下载dlib官方的68点人脸关键点模型,保存为这个文件名 predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") # Initialize video capture (0 for webcam, or replace with video file path) cap = cv2.VideoCapture(0) while True: ret, frame = cap.read() if not ret: break # Convert frame to grayscale (dlib detector works better on grayscale) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Detect faces in the frame face_rects = detector(gray, 0) # **Count and print the number of faces** face_count = len(face_rects) print(f"当前检测到人脸数量: {face_count}") # Optional: Draw bounding boxes on faces for visualization for (i, rect) in enumerate(face_rects): (x, y, w, h) = face_utils.rect_to_bb(rect) cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.putText(frame, f"Face {i+1}", (x - 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) # Show the frame cv2.imshow("Face Count", frame) if cv2.waitKey(1) & 0xFF == ord('q'): break # Cleanup cap.release() cv2.destroyAllWindows()
Key notes:
- The
detector(gray, 0)returns a list of face bounding rectangles; the length of this list is your face count directly. - Don't forget to download the 68-point landmark model from dlib's official resources and place it in your project folder.
2. 优化人脸指标打印逻辑(添加序号标识)
Assuming you already have code to calculate Eye Aspect Ratio (EAR) and Mouth Aspect Ratio (MAR) for each face, here's how to modify the print logic to add the required "Face X:" prefix:
Modified code snippet for printing metrics
# 假设你已经有了检测到的face_rects,以及计算好的ear_list和mar_list(每个元素对应一张脸的指标) print("=== 单帧人脸指标 ===") # 用enumerate从1开始计数,完美匹配需求的序号格式 for idx, (ear, mar) in enumerate(zip(ear_list, mar_list), start=1): # 保留两位小数让输出更整洁,可根据需求调整 print(f"Face {idx}: ({ear:.2f}), ({mar:.2f})")
Full integration example
If you want to combine this with the face detection pipeline:
# ... (前面的导入、模型加载、视频捕获代码和之前一致) # 先定义EAR和MAR的计算函数(示例实现,可根据需求调整) def calculate_eye_aspect_ratio(eye): # 计算眼部纵横比的标准逻辑 A = ((eye[1][0] - eye[5][0])**2 + (eye[1][1] - eye[5][1])**2)**0.5 B = ((eye[2][0] - eye[4][0])**2 + (eye[2][1] - eye[4][1])**2)**0.5 C = ((eye[0][0] - eye[3][0])**2 + (eye[0][1] - eye[3][1])**2)**0.5 ear = (A + B) / (2.0 * C) return ear def calculate_mouth_aspect_ratio(mouth): # 计算嘴部纵横比的标准逻辑 A = ((mouth[2][0] - mouth[10][0])**2 + (mouth[2][1] - mouth[10][1])**2)**0.5 B = ((mouth[4][0] - mouth[8][0])**2 + (mouth[4][1] - mouth[8][1])**2)**0.5 C = ((mouth[0][0] - mouth[6][0])**2 + (mouth[0][1] - mouth[6][1])**2)**0.5 mar = (A + B) / (2.0 * C) return mar while True: ret, frame = cap.read() if not ret: break gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) face_rects = detector(gray, 0) ear_list = [] mar_list = [] for rect in face_rects: # 预测人脸关键点 shape = predictor(gray, rect) shape = face_utils.shape_to_np(shape) # 计算左右眼EAR并取平均值 left_eye = shape[36:42] right_eye = shape[42:48] ear = (calculate_eye_aspect_ratio(left_eye) + calculate_eye_aspect_ratio(right_eye)) / 2 ear_list.append(ear) # 计算嘴部MAR mouth = shape[48:68] mar = calculate_mouth_aspect_ratio(mouth) mar_list.append(mar) # 打印带序号的指标 print("=== 单帧人脸指标 ===") for idx, (ear, mar) in enumerate(zip(ear_list, mar_list), start=1): print(f"Face {idx}: ({ear:.2f}), ({mar:.2f})") # ... (可视化和退出逻辑和之前一致)
内容的提问来源于stack exchange,提问作者3umar
相关产品推荐
相关产品推荐

