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