Advertisement
Guest User

Untitled

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