利用opencv的稀疏光流跟踪人脸
时间: 2023-08-10 07:07:27 浏览: 101
使用OpenCV的稀疏光流算法,可以跟踪人脸的运动。以下是一个简单的示例代码:
```
import cv2
import numpy as np
# 读取视频
cap = cv2.VideoCapture('face_video.mp4')
# 读取第一帧并检测人脸
ret, frame = cap.read()
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
faces = face_cascade.detectMultiScale(frame, scaleFactor=1.1, minNeighbors=5)
# 取第一个人脸的位置作为初始跟踪点
x, y, w, h = faces[0]
prev_pts = np.array([[x + w/2, y + h/2]], dtype=np.float32)
# 创建Lucas-Kanade稀疏光流对象
lk_params = dict(winSize=(15, 15),
maxLevel=2,
criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))
color = (0, 255, 0)
# 逐帧进行跟踪
while True:
# 读取下一帧
ret, frame = cap.read()
if not ret:
break
# 检测人脸
faces = face_cascade.detectMultiScale(frame, scaleFactor=1.1, minNeighbors=5)
# 计算光流
curr_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
curr_pts, status, err = cv2.calcOpticalFlowPyrLK(prev_gray, curr_gray, prev_pts, None, **lk_params)
# 选出跟踪成功的点
good_new = curr_pts[status == 1]
good_old = prev_pts[status == 1]
# 绘制跟踪结果
for i, (new, old) in enumerate(zip(good_new, good_old)):
a, b = new.ravel()
c, d = old.ravel()
frame = cv2.line(frame, (a, b), (c, d), color, 2)
frame = cv2.circle(frame, (a, b), 3, color, -1)
# 更新跟踪点和图像
prev_gray = curr_gray.copy()
prev_pts = good_new.reshape(-1, 1, 2)
# 显示图像
cv2.imshow('frame', frame)
if cv2.waitKey(1) == ord('q'):
break
# 释放资源
cap.release()
cv2.destroyAllWindows()
```
其中,使用了Haar级联分类器来检测人脸,使用calcOpticalFlowPyrLK计算稀疏光流,使用line和circle函数绘制跟踪结果。运行后,程序会打开视频窗口并进行人脸跟踪,直到用户按下q键退出。
阅读全文