common.py 6.2 KB

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