Python OpenCv 实现实时单人人脸识别及面部距离测量,写代码
时间: 2024-04-25 12:05:26 浏览: 73
好的,我可以为您提供代码示例:
首先,需要调用OpenCV和dlib库,安装方法可以使用pip进行安装。
```
import cv2
import dlib
import numpy as np
```
下面是初始化函数,包括人脸特征检测器和距离测量工具的初始化:
```
def initialize():
# 初始化人脸特征检测器和距离测量工具
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
return detector, predictor
```
接下来编写实时视频处理函数,包括人脸检测、脸部特征获取和距离测量:
```
def process(frame, detector, predictor):
# 将帧转换为灰度图像以进行更好的检测
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 使用人脸检测器检测出现位置
rects = detector(gray)
# 处理每个检测到的人脸
for rect in rects:
# 检测出脸部特征
shape = predictor(gray, rect)
shape = np.array([(shape.part(i).x, shape.part(i).y) for i in range(68)])
# 计算左右眼之间的距离
left = shape[36]
right = shape[45]
euclidean_distance = np.linalg.norm(left - right)
# 绘制人脸轮廓
cv2.rectangle(frame, (rect.left(), rect.top()), (rect.right(), rect.bottom()), (0, 255, 0), 2)
# 显示距离
cv2.putText(frame, f"Distance: {euclidean_distance:.2f}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 2)
return frame
```
最后,我们需要打开电脑摄像头并循环处理实时视频:
```
def main():
# 初始化
detector, predictor = initialize()
cap = cv2.VideoCapture(0)
# 循环帧,处理每个帧
while True:
ret, frame = cap.read()
if not ret:
break
frame = process(frame, detector, predictor)
cv2.imshow("Face Detection and Distance Measurement", frame)
if cv2.waitKey(1) == ord('q'):
break
# 清理资源
cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
main()
```
希望这个代码示例可以帮助你实现实时单人人脸识别及面部距离测量。如果您有任何疑问,请随时联系我。
阅读全文