common.py 6.5 KB

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