使用光流的物体检测

时间:2018-10-23 18:12:11

标签: python-3.x opencv opticalflow

我尝试检测并跟踪自动运动。下一个代码可以跟踪运动,但需要用鼠标单击。 我想用绿点或类似的东西来检测运动,并跟踪运动,而无需单击框架。 请任何想法或建议吗? 我正在处理下一个代码。预先感谢。

import cv2
import numpy as np


cap = cv2.VideoCapture(0)


_, frame = cap.read()
old_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)


lk_params = dict(winSize=(15, 15),
                 maxLevel=2, criteria=(cv2.TERM_CRITERIA_EPS | 
cv2.TERM_CRITERIA_COUNT, 10, 0.03))

def punto_seleccionado(event, x, y, flags, params):

    global point, point_selected, old_points

    if event == cv2.EVENT_LBUTTONDOWN:
        point = (x, y)
        point_selected = True
        old_points = np.array([[x, y]], dtype=np.float32)

cv2.namedWindow("Frame")

cv2.setMouseCallback("Frame", punto_seleccionado)

point_selected = False
point = ()
old_points = np.array([[]])


while (1):

    _, frame = cap.read()

    gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    if point_selected is True:
        cv2.circle(frame, point, 5, (0, 0, 255), 2)

        new_points, status, error = cv2.calcOpticalFlowPyrLK(
            old_gray, gray_frame, old_points, None, **lk_params)
        old_gray = gray_frame.copy()
        old_points = new_points
        x, y = new_points.ravel()
       cv2.circle(frame, (x, y), 5, (0, 255, 0), -1)

    cv2.imshow("Frame", frame)

    key = cv2.waitKey(1)
    if key == 27:
        break

cap.release()
cv2.destroyAllWindows()

0 个答案:

没有答案