feature_homography.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #!/usr/bin/env python
  2. '''
  3. Feature homography
  4. ==================
  5. Example of using features2d framework for interactive video homography matching.
  6. ORB features and FLANN matcher are used. The actual tracking is implemented by
  7. PlaneTracker class in plane_tracker.py
  8. Inspired by http://www.youtube.com/watch?v=-ZNYoL8rzPY
  9. video: http://www.youtube.com/watch?v=FirtmYcC0Vc
  10. Usage
  11. -----
  12. feature_homography.py [<video source>]
  13. Keys:
  14. SPACE - pause video
  15. Select a textured planar object to track by drawing a box with a mouse.
  16. '''
  17. # Python 2/3 compatibility
  18. from __future__ import print_function
  19. import numpy as np
  20. import cv2 as cv
  21. # local modules
  22. import video
  23. from video import presets
  24. import common
  25. from common import getsize, draw_keypoints
  26. from plane_tracker import PlaneTracker
  27. class App:
  28. def __init__(self, src):
  29. self.cap = video.create_capture(src, presets['book'])
  30. self.frame = None
  31. self.paused = False
  32. self.tracker = PlaneTracker()
  33. cv.namedWindow('plane')
  34. self.rect_sel = common.RectSelector('plane', self.on_rect)
  35. def on_rect(self, rect):
  36. self.tracker.clear()
  37. self.tracker.add_target(self.frame, rect)
  38. def run(self):
  39. while True:
  40. playing = not self.paused and not self.rect_sel.dragging
  41. if playing or self.frame is None:
  42. ret, frame = self.cap.read()
  43. if not ret:
  44. break
  45. self.frame = frame.copy()
  46. w, h = getsize(self.frame)
  47. vis = np.zeros((h, w*2, 3), np.uint8)
  48. vis[:h,:w] = self.frame
  49. if len(self.tracker.targets) > 0:
  50. target = self.tracker.targets[0]
  51. vis[:,w:] = target.image
  52. draw_keypoints(vis[:,w:], target.keypoints)
  53. x0, y0, x1, y1 = target.rect
  54. cv.rectangle(vis, (x0+w, y0), (x1+w, y1), (0, 255, 0), 2)
  55. if playing:
  56. tracked = self.tracker.track(self.frame)
  57. if len(tracked) > 0:
  58. tracked = tracked[0]
  59. cv.polylines(vis, [np.int32(tracked.quad)], True, (255, 255, 255), 2)
  60. for (x0, y0), (x1, y1) in zip(np.int32(tracked.p0), np.int32(tracked.p1)):
  61. cv.line(vis, (x0+w, y0), (x1, y1), (0, 255, 0))
  62. draw_keypoints(vis, self.tracker.frame_points)
  63. self.rect_sel.draw(vis)
  64. cv.imshow('plane', vis)
  65. ch = cv.waitKey(1)
  66. if ch == ord(' '):
  67. self.paused = not self.paused
  68. if ch == 27:
  69. break
  70. if __name__ == '__main__':
  71. print(__doc__)
  72. import sys
  73. try:
  74. video_src = sys.argv[1]
  75. except:
  76. video_src = 0
  77. App(video_src).run()