使用dlib进行稀疏光流跟踪人脸
时间: 2023-07-20 09:40:53 浏览: 134
使用dlib进行稀疏光流跟踪人脸可以实现对人脸的实时追踪。下面是一个简单的代码示例:
```
import cv2
import dlib
# 初始化dlib的人脸检测器和稀疏光流跟踪器
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
tracker = dlib.correlation_tracker()
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
# 读取视频帧
ret, frame = cap.read()
if not ret:
break
# 转为灰度图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 检测人脸
face_rects = detector(gray, 0)
# 遍历每个人脸
for face_rect in face_rects:
# 获取人脸关键点
landmarks = predictor(gray, face_rect)
landmarks = [[p.x, p.y] for p in landmarks.parts()]
# 提取左眼和右眼的中心点
left_eye = [(landmarks[36][0] + landmarks[39][0]) // 2,
(landmarks[36][1] + landmarks[39][1]) // 2]
right_eye = [(landmarks[42][0] + landmarks[45][0]) // 2,
(landmarks[42][1] + landmarks[45][1]) // 2]
# 初始化跟踪器
tracker.start_track(frame, dlib.rectangle(*face_rect))
# 跟踪人脸运动
while True:
# 读取下一帧
ret, frame = cap.read()
if not ret:
break
# 跟踪人脸
tracker.update(frame)
pos = tracker.get_position()
# 提取人脸区域
rect = pos.left(), pos.top(), pos.right(), pos.bottom()
x1, y1, x2, y2 = rect
face = frame[y1:y2, x1:x2]
# 将人脸区域转为灰度图像
gray = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)
# 计算光流
p1, p2, st = cv2.calcOpticalFlowPyrLK(prev_gray, gray, np.array([left_eye, right_eye]), None, **lk_params)
# 计算运动矢量
dx, dy = p2[0] - p1[0]
# 更新眼睛中心点位置
left_eye[0] += dx
left_eye[1] += dy
right_eye[0] += dx
right_eye[1] += dy
# 可视化结果
cv2.circle(face, tuple(p1[0]), 2, (0, 255, 0), -1)
cv2.circle(face, tuple(p2[0]), 2, (0, 0, 255), -1)
cv2.circle(face, tuple(left_eye), 2, (255, 0, 0), -1)
cv2.circle(face, tuple(right_eye), 2, (255, 0, 0), -1)
cv2.imshow("Face Tracking", face)
# 保存当前帧的灰度图像
prev_gray = gray.copy()
# 按下Esc键退出
if cv2.waitKey(1) == 27:
break
# 按下Esc键退出
if cv2.waitKey(1) == 27:
break
# 释放摄像头并关闭窗口
cap.release()
cv2.destroyAllWindows()
```
在代码中,先使用dlib进行人脸检测和关键点定位,然后选择左右眼的中心点作为跟踪目标,并使用dlib的correlation_tracker()函数进行稀疏光流跟踪。在每个跟踪周期内,使用OpenCV的calcOpticalFlowPyrLK()函数计算光流,并计算左右眼的运动矢量,然后更新眼睛中心点的位置。最后将结果可视化并显示在窗口中。
阅读全文
相关推荐















