python识别对象移动轨迹

安装cv2

pycharm开发环境。无法单独安装cv2,直接安装opencv-python即可。

python识别对象移动轨迹_第1张图片

 

报错:

cv2.error: OpenCV(4.7.0) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\shapedescr.cpp:315: error: (-215:Assertion failed) npoints >= 0 && (depth == CV_32F || depth == CV_32S) in function 'cv::contourArea'

方法一,识别两点的坐标

import numpy as np
import cv2 as cv
frameWidth = 640
frameHeight = 480
cap = cv.VideoCapture('.\VID20230519045724.mp4')
size = (frameWidth, frameHeight)
fgbg = cv.createBackgroundSubtractorMOG2()
feature_params = dict(maxCorners=1,qualityLevel=.6,minDistance=25,blockSize=9)
result = cv.VideoWriter('output.avi',
                         cv.VideoWriter_fourcc(*'MJPG'),
                         10, size)
while True:
    ret, oframe = cap.read()
    if oframe is None:
        break
    oframe = cv.resize(oframe, (frameWidth, frameHeight))

    mask = fgbg.apply(oframe)
    frame = cv.morphologyEx(mask,cv.MORPH_OPEN,np.ones((5,5),np.uint8))

    ball = cv.goodFeaturesToTrack(frame,**feature_params)
    if ball is not None:
        x,y = ball[0][0]
        cv.circle(oframe,(int(x),int(y)),8,(180,180,0),2)
        print("(x,y)=(",x,",",y,")")

    cv.imshow("Track", oframe)
    result.write(oframe)

    key = cv.waitKey(30)
    if key == ord('q') or key == 27:
        break

result.release()

效果

python识别对象移动轨迹_第2张图片

方法二:

ROI,绘制轨迹

import cv2 as cv
import numpy as np

cap = cv.VideoCapture('720p.mp4')
#cap = cv.VideoCapture('object_tracking_example.mp4')

# 读取第一帧
ret,frame = cap.read()
cv.namedWindow("Demo", cv.WINDOW_AUTOSIZE)

# 选择ROI区域
x, y, w, h = cv.selectROI("Demo", frame, True, False)
track_window = (x, y, w, h)
print("selectROI:x=",x, "y=",y, "w=",w, "h=",h)

# 获取ROI直方图
roi = frame[y:y+h, x:x+w]
hsv_roi = cv.cvtColor(roi, cv.COLOR_BGR2HSV)
#mask = cv.inRange(hsv_roi, (26, 43, 46), (34, 255, 255))
mask = cv.inRange(hsv_roi, (0, 0, 0), (255, 255, 255))
roi_hist = cv.calcHist([hsv_roi],[0],mask,[180],[0,180])
cv.normalize(roi_hist,roi_hist,0,255,cv.NORM_MINMAX)

tracking_path = []
# 设置迭代的终止标准,最多十次迭代
term_crit = ( cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 10, 1 )
while True:
    ret, frame = cap.read()
    if ret is False:
        break;
    hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
    dst = cv.calcBackProject([hsv],[0],roi_hist,[0,180],1)

    # 搜索更新roi区域
    ret, track_box = cv.CamShift(dst, track_window, term_crit)

    #print(type(ret)," CamShift=",ret)

    # 可变角度的矩形框
    pts = cv.boxPoints(ret)
    pts = np.int0(pts)
    cv.polylines(frame, [pts], True, (0, 255, 0), 2)

    # 更新窗口
    track_window = track_box
    #print(track_box)

    # 椭圆中心
    pt = np.int32(ret[0])
    if pt[0] > 0 and pt[1] > 0:
        tracking_path.append(pt)
        print(pt[0],",",pt[1])

    # 绘制跟踪对象位置窗口与对象运行轨迹
    #cv.ellipse(frame, ret, (0, 0, 255), 3, 8)
    for i in range(1, len(tracking_path)):
        cv.line(frame, (tracking_path[i - 1][0], tracking_path[i - 1][1]),
                (tracking_path[i][0], tracking_path[i][1]), (0, 255, 0), 2, 6, 0)

    # 绘制窗口CAM,目标椭圆图
    cv.ellipse(frame, ret, (0, 0, 255), 3, 8)
    cv.imshow('Demo',frame)
    k = cv.waitKey(50) & 0xff
    if k == 27:
        break
    else:
        cv.imwrite(chr(k)+".jpg",frame)

cv.destroyAllWindows()
cap.release()

 效果

python识别对象移动轨迹_第3张图片

 

参考:

OpenCV视频分析-Meanshift、Camshift&运动轨迹绘制 - 知乎

GitHub - woonyee28/Table-Tennis-Ball-Tracker: This project aims to track the movement of a table tennis ball in a video using OpenCV. The process involves filtering out the ball, generating a foreground mask, and then adding circles to the original frames to visualize the ball's movement.

你可能感兴趣的:(积累跬步,python,python,opencv,开发语言)