【Opencv系列】关键点追踪--光流估计

2024-01-17 17:19:03 浏览数 (1)

光流估计,会捕获第一帧的关键点然后对关键点进行追踪

详细代码如下:

代码语言:javascript复制
import numpy as np
import cv2

cap = cv2.VideoCapture(0)
feature_params = dict(maxCorners=100, qualityLevel=0.5, minDistance=7) #角点加测的参数

lk_params = dict(winSize=(30, 30), maxLevel=3)#Lucas kanade参数
#宽度和最大金字塔数
color = np.random.randint(0, 255, (100, 3))#随机颜色条

ret, old_frame = cap.read()
old_gray = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY)
p0 = cv2.goodFeaturesToTrack(old_gray, mask=None, **feature_params)  # 第一帧角点
mask = np.zeros_like(old_frame)

while True:
    re, frame = cap.read()
    frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    p1, st, err = cv2.calcOpticalFlowPyrLK(old_gray, frame_gray, p0, None, **lk_params)
    good_new = p1[st == 1] #找到的点
    good_old = p0[st == 1]
    for i, (new, old) in enumerate(zip(good_new, good_old)):
        # enumerate同时列出数据和数据下标
        #zip()将对象中对应元素打包成远组,返回元组列表
        a, b = new.ravel() #将多维数组转换为一堆数组
        c, d = old.ravel()
        line = cv2.line(mask, (a, b), (c, d), (0, 0, 255), 2) #将矩阵和数组转化为列表
        frame = cv2.circle(frame, (a, b), 5, (255, 0, 0), -1)#将矩阵和数组转化为列表
    img = cv2.add(frame, mask)#两个图像相加
    cv2.imshow('frame', img)
    cv2.imshow("line", frame)
    cv2.imshow('mask', line)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cv2.destroyAllWindows()
cap.release()

0 人点赞