lk_homography.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. #!/usr/bin/env python
  2. '''
  3. Lucas-Kanade homography tracker
  4. ===============================
  5. Lucas-Kanade sparse optical flow demo. Uses goodFeaturesToTrack
  6. for track initialization and back-tracking for match verification
  7. between frames. Finds homography between reference and current views.
  8. Usage
  9. -----
  10. lk_homography.py [<video_source>]
  11. Keys
  12. ----
  13. ESC - exit
  14. SPACE - start tracking
  15. r - toggle RANSAC
  16. '''
  17. # Python 2/3 compatibility
  18. from __future__ import print_function
  19. import numpy as np
  20. import cv2 as cv
  21. import video
  22. from common import draw_str
  23. from video import presets
  24. lk_params = dict( winSize = (19, 19),
  25. maxLevel = 2,
  26. criteria = (cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 10, 0.03))
  27. feature_params = dict( maxCorners = 1000,
  28. qualityLevel = 0.01,
  29. minDistance = 8,
  30. blockSize = 19 )
  31. def checkedTrace(img0, img1, p0, back_threshold = 1.0):
  32. p1, _st, _err = cv.calcOpticalFlowPyrLK(img0, img1, p0, None, **lk_params)
  33. p0r, _st, _err = cv.calcOpticalFlowPyrLK(img1, img0, p1, None, **lk_params)
  34. d = abs(p0-p0r).reshape(-1, 2).max(-1)
  35. status = d < back_threshold
  36. return p1, status
  37. green = (0, 255, 0)
  38. red = (0, 0, 255)
  39. class App:
  40. def __init__(self, video_src):
  41. self.cam = self.cam = video.create_capture(video_src, presets['book'])
  42. self.p0 = None
  43. self.use_ransac = True
  44. def run(self):
  45. while True:
  46. _ret, frame = self.cam.read()
  47. frame_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
  48. vis = frame.copy()
  49. if self.p0 is not None:
  50. p2, trace_status = checkedTrace(self.gray1, frame_gray, self.p1)
  51. self.p1 = p2[trace_status].copy()
  52. self.p0 = self.p0[trace_status].copy()
  53. self.gray1 = frame_gray
  54. if len(self.p0) < 4:
  55. self.p0 = None
  56. continue
  57. H, status = cv.findHomography(self.p0, self.p1, (0, cv.RANSAC)[self.use_ransac], 10.0)
  58. h, w = frame.shape[:2]
  59. overlay = cv.warpPerspective(self.frame0, H, (w, h))
  60. vis = cv.addWeighted(vis, 0.5, overlay, 0.5, 0.0)
  61. for (x0, y0), (x1, y1), good in zip(self.p0[:,0], self.p1[:,0], status[:,0]):
  62. if good:
  63. cv.line(vis, (int(x0), int(y0)), (int(x1), int(y1)), (0, 128, 0))
  64. cv.circle(vis, (int(x1), int(y1)), 2, (red, green)[good], -1)
  65. draw_str(vis, (20, 20), 'track count: %d' % len(self.p1))
  66. if self.use_ransac:
  67. draw_str(vis, (20, 40), 'RANSAC')
  68. else:
  69. p = cv.goodFeaturesToTrack(frame_gray, **feature_params)
  70. if p is not None:
  71. for x, y in p[:,0]:
  72. cv.circle(vis, (int(x), int(y)), 2, green, -1)
  73. draw_str(vis, (20, 20), 'feature count: %d' % len(p))
  74. cv.imshow('lk_homography', vis)
  75. ch = cv.waitKey(1)
  76. if ch == 27:
  77. break
  78. if ch == ord(' '):
  79. self.frame0 = frame.copy()
  80. self.p0 = cv.goodFeaturesToTrack(frame_gray, **feature_params)
  81. if self.p0 is not None:
  82. self.p1 = self.p0
  83. self.gray0 = frame_gray
  84. self.gray1 = frame_gray
  85. if ch == ord('r'):
  86. self.use_ransac = not self.use_ransac
  87. def main():
  88. import sys
  89. try:
  90. video_src = sys.argv[1]
  91. except:
  92. video_src = 0
  93. App(video_src).run()
  94. print('Done')
  95. if __name__ == '__main__':
  96. print(__doc__)
  97. main()
  98. cv.destroyAllWindows()