Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/samples/python/common.py
16337 views
1
#!/usr/bin/env python
2
3
'''
4
This module contains some common routines used by other samples.
5
'''
6
7
# Python 2/3 compatibility
8
from __future__ import print_function
9
import sys
10
PY3 = sys.version_info[0] == 3
11
12
if PY3:
13
from functools import reduce
14
15
import numpy as np
16
import cv2 as cv
17
18
# built-in modules
19
import os
20
import itertools as it
21
from contextlib import contextmanager
22
23
image_extensions = ['.bmp', '.jpg', '.jpeg', '.png', '.tif', '.tiff', '.pbm', '.pgm', '.ppm']
24
25
class Bunch(object):
26
def __init__(self, **kw):
27
self.__dict__.update(kw)
28
def __str__(self):
29
return str(self.__dict__)
30
31
def splitfn(fn):
32
path, fn = os.path.split(fn)
33
name, ext = os.path.splitext(fn)
34
return path, name, ext
35
36
def anorm2(a):
37
return (a*a).sum(-1)
38
def anorm(a):
39
return np.sqrt( anorm2(a) )
40
41
def homotrans(H, x, y):
42
xs = H[0, 0]*x + H[0, 1]*y + H[0, 2]
43
ys = H[1, 0]*x + H[1, 1]*y + H[1, 2]
44
s = H[2, 0]*x + H[2, 1]*y + H[2, 2]
45
return xs/s, ys/s
46
47
def to_rect(a):
48
a = np.ravel(a)
49
if len(a) == 2:
50
a = (0, 0, a[0], a[1])
51
return np.array(a, np.float64).reshape(2, 2)
52
53
def rect2rect_mtx(src, dst):
54
src, dst = to_rect(src), to_rect(dst)
55
cx, cy = (dst[1] - dst[0]) / (src[1] - src[0])
56
tx, ty = dst[0] - src[0] * (cx, cy)
57
M = np.float64([[ cx, 0, tx],
58
[ 0, cy, ty],
59
[ 0, 0, 1]])
60
return M
61
62
63
def lookat(eye, target, up = (0, 0, 1)):
64
fwd = np.asarray(target, np.float64) - eye
65
fwd /= anorm(fwd)
66
right = np.cross(fwd, up)
67
right /= anorm(right)
68
down = np.cross(fwd, right)
69
R = np.float64([right, down, fwd])
70
tvec = -np.dot(R, eye)
71
return R, tvec
72
73
def mtx2rvec(R):
74
w, u, vt = cv.SVDecomp(R - np.eye(3))
75
p = vt[0] + u[:,0]*w[0] # same as np.dot(R, vt[0])
76
c = np.dot(vt[0], p)
77
s = np.dot(vt[1], p)
78
axis = np.cross(vt[0], vt[1])
79
return axis * np.arctan2(s, c)
80
81
def draw_str(dst, target, s):
82
x, y = target
83
cv.putText(dst, s, (x+1, y+1), cv.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 0), thickness = 2, lineType=cv.LINE_AA)
84
cv.putText(dst, s, (x, y), cv.FONT_HERSHEY_PLAIN, 1.0, (255, 255, 255), lineType=cv.LINE_AA)
85
86
class Sketcher:
87
def __init__(self, windowname, dests, colors_func):
88
self.prev_pt = None
89
self.windowname = windowname
90
self.dests = dests
91
self.colors_func = colors_func
92
self.dirty = False
93
self.show()
94
cv.setMouseCallback(self.windowname, self.on_mouse)
95
96
def show(self):
97
cv.imshow(self.windowname, self.dests[0])
98
99
def on_mouse(self, event, x, y, flags, param):
100
pt = (x, y)
101
if event == cv.EVENT_LBUTTONDOWN:
102
self.prev_pt = pt
103
elif event == cv.EVENT_LBUTTONUP:
104
self.prev_pt = None
105
106
if self.prev_pt and flags & cv.EVENT_FLAG_LBUTTON:
107
for dst, color in zip(self.dests, self.colors_func()):
108
cv.line(dst, self.prev_pt, pt, color, 5)
109
self.dirty = True
110
self.prev_pt = pt
111
self.show()
112
113
114
# palette data from matplotlib/_cm.py
115
_jet_data = {'red': ((0., 0, 0), (0.35, 0, 0), (0.66, 1, 1), (0.89,1, 1),
116
(1, 0.5, 0.5)),
117
'green': ((0., 0, 0), (0.125,0, 0), (0.375,1, 1), (0.64,1, 1),
118
(0.91,0,0), (1, 0, 0)),
119
'blue': ((0., 0.5, 0.5), (0.11, 1, 1), (0.34, 1, 1), (0.65,0, 0),
120
(1, 0, 0))}
121
122
cmap_data = { 'jet' : _jet_data }
123
124
def make_cmap(name, n=256):
125
data = cmap_data[name]
126
xs = np.linspace(0.0, 1.0, n)
127
channels = []
128
eps = 1e-6
129
for ch_name in ['blue', 'green', 'red']:
130
ch_data = data[ch_name]
131
xp, yp = [], []
132
for x, y1, y2 in ch_data:
133
xp += [x, x+eps]
134
yp += [y1, y2]
135
ch = np.interp(xs, xp, yp)
136
channels.append(ch)
137
return np.uint8(np.array(channels).T*255)
138
139
def nothing(*arg, **kw):
140
pass
141
142
def clock():
143
return cv.getTickCount() / cv.getTickFrequency()
144
145
@contextmanager
146
def Timer(msg):
147
print(msg, '...',)
148
start = clock()
149
try:
150
yield
151
finally:
152
print("%.2f ms" % ((clock()-start)*1000))
153
154
class StatValue:
155
def __init__(self, smooth_coef = 0.5):
156
self.value = None
157
self.smooth_coef = smooth_coef
158
def update(self, v):
159
if self.value is None:
160
self.value = v
161
else:
162
c = self.smooth_coef
163
self.value = c * self.value + (1.0-c) * v
164
165
class RectSelector:
166
def __init__(self, win, callback):
167
self.win = win
168
self.callback = callback
169
cv.setMouseCallback(win, self.onmouse)
170
self.drag_start = None
171
self.drag_rect = None
172
def onmouse(self, event, x, y, flags, param):
173
x, y = np.int16([x, y]) # BUG
174
if event == cv.EVENT_LBUTTONDOWN:
175
self.drag_start = (x, y)
176
return
177
if self.drag_start:
178
if flags & cv.EVENT_FLAG_LBUTTON:
179
xo, yo = self.drag_start
180
x0, y0 = np.minimum([xo, yo], [x, y])
181
x1, y1 = np.maximum([xo, yo], [x, y])
182
self.drag_rect = None
183
if x1-x0 > 0 and y1-y0 > 0:
184
self.drag_rect = (x0, y0, x1, y1)
185
else:
186
rect = self.drag_rect
187
self.drag_start = None
188
self.drag_rect = None
189
if rect:
190
self.callback(rect)
191
def draw(self, vis):
192
if not self.drag_rect:
193
return False
194
x0, y0, x1, y1 = self.drag_rect
195
cv.rectangle(vis, (x0, y0), (x1, y1), (0, 255, 0), 2)
196
return True
197
@property
198
def dragging(self):
199
return self.drag_rect is not None
200
201
202
def grouper(n, iterable, fillvalue=None):
203
'''grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx'''
204
args = [iter(iterable)] * n
205
if PY3:
206
output = it.zip_longest(fillvalue=fillvalue, *args)
207
else:
208
output = it.izip_longest(fillvalue=fillvalue, *args)
209
return output
210
211
def mosaic(w, imgs):
212
'''Make a grid from images.
213
214
w -- number of grid columns
215
imgs -- images (must have same size and format)
216
'''
217
imgs = iter(imgs)
218
if PY3:
219
img0 = next(imgs)
220
else:
221
img0 = imgs.next()
222
pad = np.zeros_like(img0)
223
imgs = it.chain([img0], imgs)
224
rows = grouper(w, imgs, pad)
225
return np.vstack(map(np.hstack, rows))
226
227
def getsize(img):
228
h, w = img.shape[:2]
229
return w, h
230
231
def mdot(*args):
232
return reduce(np.dot, args)
233
234
def draw_keypoints(vis, keypoints, color = (0, 255, 255)):
235
for kp in keypoints:
236
x, y = kp.pt
237
cv.circle(vis, (int(x), int(y)), 2, color)
238
239