meanshift.py 1.6 KB

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