1import numpy as np 2import cv2 as cv 3import argparse 4 5parser = argparse.ArgumentParser(description='This sample demonstrates the meanshift algorithm. \ 6 The example file can be downloaded from: \ 7 https://www.bogotobogo.com/python/OpenCV_Python/images/mean_shift_tracking/slow_traffic_small.mp4') 8parser.add_argument('image', type=str, help='path to image file') 9args = parser.parse_args() 10 11cap = cv.VideoCapture(args.image) 12 13# take first frame of the video 14ret,frame = cap.read() 15 16# setup initial location of window 17x, y, w, h = 300, 200, 100, 50 # simply hardcoded the values 18track_window = (x, y, w, h) 19 20# set up the ROI for tracking 21roi = frame[y:y+h, x:x+w] 22hsv_roi = cv.cvtColor(roi, cv.COLOR_BGR2HSV) 23mask = cv.inRange(hsv_roi, np.array((0., 60.,32.)), np.array((180.,255.,255.))) 24roi_hist = cv.calcHist([hsv_roi],[0],mask,[180],[0,180]) 25cv.normalize(roi_hist,roi_hist,0,255,cv.NORM_MINMAX) 26 27# Setup the termination criteria, either 10 iteration or move by atleast 1 pt 28term_crit = ( cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 10, 1 ) 29 30while(1): 31 ret, frame = cap.read() 32 33 if ret == True: 34 hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV) 35 dst = cv.calcBackProject([hsv],[0],roi_hist,[0,180],1) 36 37 # apply meanshift to get the new location 38 ret, track_window = cv.meanShift(dst, track_window, term_crit) 39 40 # Draw it on image 41 x,y,w,h = track_window 42 img2 = cv.rectangle(frame, (x,y), (x+w,y+h), 255,2) 43 cv.imshow('img2',img2) 44 45 k = cv.waitKey(30) & 0xff 46 if k == 27: 47 break 48 else: 49 break 50