使用meanShift、CamShift捕捉对象
import cv2
import numpy as np
capture = cv2.VideoCapture('dance1.mp4')
ret,frame = capture.read()
x,y,w,h = 700,0,160,160
track_window = (x,y,w,h )
roi = frame[y:y+h, x:x+w]
hsv_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv_roi, np.array((0, 60,32)), np.array((180,255,255)))
roi_hist = cv2.calcHist([hsv_roi],[0],mask,[180],[0,180])
cv2.normalize(roi_hist,roi_hist,0,255,cv2.NORM_MINMAX)
# 设置终止条件,
term_crit = (cv2.TERM_CRITERIA_COUNT, 6, 1 )
while(1):
ret, frame = capture.read()
if ret == True:
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
dst = cv2.calcBackProject([hsv],[0],roi_hist,[0,180],1)
# 应用meanshift或者来获取新位置
ret, track_window = cv2.CamShift(dst, track_window, term_crit)
# 在图像上绘制
x,y,w,h = track_window
img2 = cv2.rectangle(frame, (x,y), (x+w,y+h), 255,2)
cv2.imshow('img2',img2)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
else:
break