lk_track.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. #!/usr/bin/env python
  2. '''
  3. Lucas-Kanade tracker
  4. ====================
  5. Lucas-Kanade sparse optical flow demo. Uses goodFeaturesToTrack
  6. for track initialization and back-tracking for match verification
  7. between frames.
  8. Usage
  9. -----
  10. lk_track.py [<video_source>]
  11. Keys
  12. ----
  13. ESC - exit
  14. '''
  15. # Python 2/3 compatibility
  16. from __future__ import print_function
  17. import numpy as np
  18. import cv2 as cv
  19. import video
  20. from common import anorm2, draw_str
  21. lk_params = dict( winSize = (15, 15),
  22. maxLevel = 2,
  23. criteria = (cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 10, 0.03))
  24. feature_params = dict( maxCorners = 500,
  25. qualityLevel = 0.3,
  26. minDistance = 7,
  27. blockSize = 7 )
  28. class App:
  29. def __init__(self, video_src):
  30. self.track_len = 10
  31. self.detect_interval = 5
  32. self.tracks = []
  33. self.cam = video.create_capture(video_src)
  34. self.frame_idx = 0
  35. def run(self):
  36. while True:
  37. _ret, frame = self.cam.read()
  38. frame_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
  39. vis = frame.copy()
  40. if len(self.tracks) > 0:
  41. img0, img1 = self.prev_gray, frame_gray
  42. p0 = np.float32([tr[-1] for tr in self.tracks]).reshape(-1, 1, 2)
  43. p1, _st, _err = cv.calcOpticalFlowPyrLK(img0, img1, p0, None, **lk_params)
  44. p0r, _st, _err = cv.calcOpticalFlowPyrLK(img1, img0, p1, None, **lk_params)
  45. d = abs(p0-p0r).reshape(-1, 2).max(-1)
  46. good = d < 1
  47. new_tracks = []
  48. for tr, (x, y), good_flag in zip(self.tracks, p1.reshape(-1, 2), good):
  49. if not good_flag:
  50. continue
  51. tr.append((x, y))
  52. if len(tr) > self.track_len:
  53. del tr[0]
  54. new_tracks.append(tr)
  55. cv.circle(vis, (int(x), int(y)), 2, (0, 255, 0), -1)
  56. self.tracks = new_tracks
  57. cv.polylines(vis, [np.int32(tr) for tr in self.tracks], False, (0, 255, 0))
  58. draw_str(vis, (20, 20), 'track count: %d' % len(self.tracks))
  59. if self.frame_idx % self.detect_interval == 0:
  60. mask = np.zeros_like(frame_gray)
  61. mask[:] = 255
  62. for x, y in [np.int32(tr[-1]) for tr in self.tracks]:
  63. cv.circle(mask, (x, y), 5, 0, -1)
  64. p = cv.goodFeaturesToTrack(frame_gray, mask = mask, **feature_params)
  65. if p is not None:
  66. for x, y in np.float32(p).reshape(-1, 2):
  67. self.tracks.append([(x, y)])
  68. self.frame_idx += 1
  69. self.prev_gray = frame_gray
  70. cv.imshow('lk_track', vis)
  71. ch = cv.waitKey(1)
  72. if ch == 27:
  73. break
  74. def main():
  75. import sys
  76. try:
  77. video_src = sys.argv[1]
  78. except:
  79. video_src = 0
  80. App(video_src).run()
  81. print('Done')
  82. if __name__ == '__main__':
  83. print(__doc__)
  84. main()
  85. cv.destroyAllWindows()