camshift.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. #!/usr/bin/env python
  2. '''
  3. Camshift tracker
  4. ================
  5. This is a demo that shows mean-shift based tracking
  6. You select a color objects such as your face and it tracks it.
  7. This reads from video camera (0 by default, or the camera number the user enters)
  8. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.14.7673
  9. Usage:
  10. ------
  11. camshift.py [<video source>]
  12. To initialize tracking, select the object with mouse
  13. Keys:
  14. -----
  15. ESC - exit
  16. b - toggle back-projected probability visualization
  17. '''
  18. # Python 2/3 compatibility
  19. from __future__ import print_function
  20. import sys
  21. PY3 = sys.version_info[0] == 3
  22. if PY3:
  23. xrange = range
  24. import numpy as np
  25. import cv2 as cv
  26. # local module
  27. import video
  28. from video import presets
  29. class App(object):
  30. def __init__(self, video_src):
  31. self.cam = video.create_capture(video_src, presets['cube'])
  32. _ret, self.frame = self.cam.read()
  33. cv.namedWindow('camshift')
  34. cv.setMouseCallback('camshift', self.onmouse)
  35. self.selection = None
  36. self.drag_start = None
  37. self.show_backproj = False
  38. self.track_window = None
  39. def onmouse(self, event, x, y, flags, param):
  40. if event == cv.EVENT_LBUTTONDOWN:
  41. self.drag_start = (x, y)
  42. self.track_window = None
  43. if self.drag_start:
  44. xmin = min(x, self.drag_start[0])
  45. ymin = min(y, self.drag_start[1])
  46. xmax = max(x, self.drag_start[0])
  47. ymax = max(y, self.drag_start[1])
  48. self.selection = (xmin, ymin, xmax, ymax)
  49. if event == cv.EVENT_LBUTTONUP:
  50. self.drag_start = None
  51. self.track_window = (xmin, ymin, xmax - xmin, ymax - ymin)
  52. def show_hist(self):
  53. bin_count = self.hist.shape[0]
  54. bin_w = 24
  55. img = np.zeros((256, bin_count*bin_w, 3), np.uint8)
  56. for i in xrange(bin_count):
  57. h = int(self.hist[i])
  58. cv.rectangle(img, (i*bin_w+2, 255), ((i+1)*bin_w-2, 255-h), (int(180.0*i/bin_count), 255, 255), -1)
  59. img = cv.cvtColor(img, cv.COLOR_HSV2BGR)
  60. cv.imshow('hist', img)
  61. def run(self):
  62. while True:
  63. _ret, self.frame = self.cam.read()
  64. vis = self.frame.copy()
  65. hsv = cv.cvtColor(self.frame, cv.COLOR_BGR2HSV)
  66. mask = cv.inRange(hsv, np.array((0., 60., 32.)), np.array((180., 255., 255.)))
  67. if self.selection:
  68. x0, y0, x1, y1 = self.selection
  69. hsv_roi = hsv[y0:y1, x0:x1]
  70. mask_roi = mask[y0:y1, x0:x1]
  71. hist = cv.calcHist( [hsv_roi], [0], mask_roi, [16], [0, 180] )
  72. cv.normalize(hist, hist, 0, 255, cv.NORM_MINMAX)
  73. self.hist = hist.reshape(-1)
  74. self.show_hist()
  75. vis_roi = vis[y0:y1, x0:x1]
  76. cv.bitwise_not(vis_roi, vis_roi)
  77. vis[mask == 0] = 0
  78. if self.track_window and self.track_window[2] > 0 and self.track_window[3] > 0:
  79. self.selection = None
  80. prob = cv.calcBackProject([hsv], [0], self.hist, [0, 180], 1)
  81. prob &= mask
  82. term_crit = ( cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 10, 1 )
  83. track_box, self.track_window = cv.CamShift(prob, self.track_window, term_crit)
  84. if self.show_backproj:
  85. vis[:] = prob[...,np.newaxis]
  86. try:
  87. cv.ellipse(vis, track_box, (0, 0, 255), 2)
  88. except:
  89. print(track_box)
  90. cv.imshow('camshift', vis)
  91. ch = cv.waitKey(5)
  92. if ch == 27:
  93. break
  94. if ch == ord('b'):
  95. self.show_backproj = not self.show_backproj
  96. cv.destroyAllWindows()
  97. if __name__ == '__main__':
  98. print(__doc__)
  99. import sys
  100. try:
  101. video_src = sys.argv[1]
  102. except:
  103. video_src = 0
  104. App(video_src).run()