参考资料:
opencv/python标定时用到的几个函数意义_criteria opencv_是三水不是泗水的博客-CSDN博客
python+OpenCV笔记(二十六):视频追踪(meanshift、Camshift)_cv2.meanshift_ReadyGo!!!的博客-CSDN博客
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
#打开视频
video = cv.VideoCapture("../SampleVideos/milo.mp4")
#读取第一帧图像
ret,frame = video.read()
plt.figure(figsize=(16,16))
plt.imshow(frame[:,:,::-1])
cv.imwrite("tmp.jpg", frame)
#设置跟踪目标的位置(行,高,列,宽)
row,height,col,width = 650,115,350,140
obj_track_window = (col, row, width, height)
#设置ROI区域
roi = frame[row:row+height,col:col+width]
plt.imshow(roi[:,:,::-1])
#计算ROI的直方图
#1. 转换到HSV色彩空间
roi_hsv = cv.cvtColor(roi, cv.COLOR_BGR2HSV)
#2. 计算ROI区域直方图
roi_hist = cv.calcHist([roi_hsv],[0],None,[180],[0,180])
# 直方图归一化
cv.normalize(roi_hist, roi_hist, 0, 255, cv.NORM_MINMAX)
#进行目标追踪
#1. 设置窗口搜索终止条件:最大迭代次数,窗口中心漂移最小值
#参考资料:https://blog.csdn.net/csg3140100993/article/details/102613843
term_crit = (cv.TERM_CRITERIA_EPS|cv.TERM_CRITERIA_COUNT, 10, 1)
#2. 处理每一帧
while (True):
ret,frame = video.read()
if ret == False:
break;
#计算直方图反向投影
#cv.calcBackProject(image, channels, hist, ranges, scale[, dst])
#image:输入图像(HSV),要用中括号[]括起来
#channels:用于计算反向投影的通道列表,通道数必须与直方图的维度匹配
#hist:模板图像的直方图
#ranges:直方图中每个维度bin的取值范围
#scale:缩放因子,一般为1
#参考资料:https://www.jianshu.com/p/d0a2c70cf99e
hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
target = cv.calcBackProject([hsv],[0],roi_hist,[0,180],1)
#使用MeanShit追踪
#cv.meanShift(probImage, window, criteria)
#probImage:ROI区域,即目标直方图的反向投影
#window:初始搜索窗口,就是定义ROI的rect
#criteria:确定窗口搜索停止的准则,主要有迭代次数达到设置的最大值,窗口中心的漂移值大于某个设定的限值等
#参考资料:https://blog.csdn.net/qq_45832961/article/details/122627993
ret,obj_track_window = cv.meanShift(target, obj_track_window, term_crit)
#显示追踪矩形
x,y,w,h = obj_track_window
img_track = cv.rectangle(frame, (x,y), (x+w, y+h), (0,255,0), 2)
cv.imshow('MeanShift Demo', img_track)
if cv.waitKey(30) & 0xFF == ord('q'):
break;
video.release()
cv.destroyAllWindows()