PageRenderTime 53ms CodeModel.GetById 19ms RepoModel.GetById 2ms app.codeStats 0ms

/python_prototypes/basic/basicpy/lib/python3.5/site-packages/skimage/measure/_marching_cubes_lewiner.py

https://bitbucket.org/xkovacikm2/diplomka
Python | 289 lines | 266 code | 6 blank | 17 comment | 8 complexity | da821da546b4be0afde1c31418b9a15b MD5 | raw file
Possible License(s): BSD-2-Clause, 0BSD, BSD-3-Clause
  1. import sys
  2. import base64
  3. import dis
  4. import inspect
  5. import numpy as np
  6. if sys.version_info >= (3, ):
  7. base64decode = base64.decodebytes
  8. ordornot = lambda x: x
  9. else:
  10. base64decode = base64.decodestring
  11. ordornot = ord
  12. from . import _marching_cubes_lewiner_luts as mcluts
  13. from . import _marching_cubes_lewiner_cy
  14. from .._shared.utils import skimage_deprecation, warn
  15. def _expected_output_args():
  16. """ Get number of expected output args.
  17. Please don't use this to influence the algorithmic bahaviour of a function.
  18. For ``a, b, rest*, c = ...`` syntax, returns n + 0.1 (3.1 in this example).
  19. """
  20. offset = 2 if sys.version_info >= (3, 6) else 3
  21. f = inspect.currentframe().f_back.f_back
  22. i = f.f_lasti + offset
  23. bytecode = f.f_code.co_code
  24. instruction = ordornot(bytecode[i])
  25. while True:
  26. if instruction == dis.opmap['DUP_TOP']:
  27. if ordornot(bytecode[i + 1]) == dis.opmap['UNPACK_SEQUENCE']:
  28. return ordornot(bytecode[i + 2])
  29. i += 4
  30. instruction = ordornot(bytecode[i])
  31. continue
  32. if instruction == dis.opmap['STORE_NAME']:
  33. return 1
  34. if instruction == dis.opmap['UNPACK_SEQUENCE']:
  35. return ordornot(bytecode[i + 1])
  36. if instruction == dis.opmap.get('UNPACK_EX', -1): # py3k
  37. if ordornot(bytecode[i + 2]) < 10:
  38. return ordornot(bytecode[i + 1]) + ordornot(bytecode[i + 2]) + 0.1
  39. else: # 3.6
  40. return ordornot(bytecode[i + 1]) + 0.1
  41. if instruction == dis.opmap.get('EXTENDED_ARG', -1): # py 3.6
  42. if ordornot(bytecode[i + 2]) == dis.opmap.get('UNPACK_EX', -1):
  43. return ordornot(bytecode[i + 1]) + ordornot(bytecode[i + 3]) + 0.1
  44. i += 4
  45. instruction = ordornot(bytecode[i])
  46. continue
  47. return 0
  48. def marching_cubes(volume, level=None, spacing=(1., 1., 1.),
  49. gradient_direction='descent', step_size=1,
  50. allow_degenerate=True, use_classic=False):
  51. """
  52. Lewiner marching cubes algorithm to find surfaces in 3d volumetric data.
  53. In contrast to ``marching_cubes_classic()``, this algorithm is faster,
  54. resolves ambiguities, and guarantees topologically correct results.
  55. Therefore, this algorithm generally a better choice, unless there
  56. is a specific need for the classic algorithm.
  57. Parameters
  58. ----------
  59. volume : (M, N, P) array
  60. Input data volume to find isosurfaces. Will internally be
  61. converted to float32 if necessary.
  62. level : float
  63. Contour value to search for isosurfaces in `volume`. If not
  64. given or None, the average of the min and max of vol is used.
  65. spacing : length-3 tuple of floats
  66. Voxel spacing in spatial dimensions corresponding to numpy array
  67. indexing dimensions (M, N, P) as in `volume`.
  68. gradient_direction : string
  69. Controls if the mesh was generated from an isosurface with gradient
  70. descent toward objects of interest (the default), or the opposite,
  71. considering the *left-hand* rule.
  72. The two options are:
  73. * descent : Object was greater than exterior
  74. * ascent : Exterior was greater than object
  75. step_size : int
  76. Step size in voxels. Default 1. Larger steps yield faster but
  77. coarser results. The result will always be topologically correct
  78. though.
  79. allow_degenerate : bool
  80. Whether to allow degenerate (i.e. zero-area) triangles in the
  81. end-result. Default True. If False, degenerate triangles are
  82. removed, at the cost of making the algorithm slower.
  83. use_classic : bool
  84. If given and True, the classic marching cubes by Lorensen (1987)
  85. is used. This option is included for reference purposes. Note
  86. that this algorithm has ambiguities and is not guaranteed to
  87. produce a topologically correct result. The results with using
  88. this option are *not* generally the same as the
  89. ``marching_cubes_classic()`` function.
  90. Returns
  91. -------
  92. verts : (V, 3) array
  93. Spatial coordinates for V unique mesh vertices. Coordinate order
  94. matches input `volume` (M, N, P).
  95. faces : (F, 3) array
  96. Define triangular faces via referencing vertex indices from ``verts``.
  97. This algorithm specifically outputs triangles, so each face has
  98. exactly three indices.
  99. normals : (V, 3) array
  100. The normal direction at each vertex, as calculated from the
  101. data.
  102. values : (V, ) array
  103. Gives a measure for the maximum value of the data in the local region
  104. near each vertex. This can be used by visualization tools to apply
  105. a colormap to the mesh.
  106. Notes
  107. -----
  108. The algorithm [1] is an improved version of Chernyaev's Marching
  109. Cubes 33 algorithm. It is an efficient algorithm that relies on
  110. heavy use of lookup tables to handle the many different cases,
  111. keeping the algorithm relatively easy. This implementation is
  112. written in Cython, ported from Lewiner's C++ implementation.
  113. To quantify the area of an isosurface generated by this algorithm, pass
  114. verts and faces to `skimage.measure.mesh_surface_area`.
  115. Regarding visualization of algorithm output, to contour a volume
  116. named `myvolume` about the level 0.0, using the ``mayavi`` package::
  117. >>> from mayavi import mlab # doctest: +SKIP
  118. >>> verts, faces, normals, values = marching_cubes(myvolume, 0.0) # doctest: +SKIP
  119. >>> mlab.triangular_mesh([vert[0] for vert in verts],
  120. ... [vert[1] for vert in verts],
  121. ... [vert[2] for vert in verts],
  122. ... faces) # doctest: +SKIP
  123. >>> mlab.show() # doctest: +SKIP
  124. Similarly using the ``visvis`` package::
  125. >>> import visvis as vv # doctest: +SKIP
  126. >>> verts, faces, normals, values = marching_cubes_classic(myvolume, 0.0) # doctest: +SKIP
  127. >>> vv.mesh(np.fliplr(verts), faces, normals, values) # doctest: +SKIP
  128. >>> vv.use().Run() # doctest: +SKIP
  129. References
  130. ----------
  131. .. [1] Thomas Lewiner, Helio Lopes, Antonio Wilson Vieira and Geovan
  132. Tavares. Efficient implementation of Marching Cubes' cases with
  133. topological guarantees. Journal of Graphics Tools 8(2)
  134. pp. 1-15 (december 2003).
  135. DOI: 10.1080/10867651.2003.10487582
  136. See Also
  137. --------
  138. skimage.measure.marching_cubes_classic
  139. skimage.measure.mesh_surface_area
  140. """
  141. # This signature (output args) of this func changed after 0.12
  142. try:
  143. nout = _expected_output_args()
  144. except Exception:
  145. nout = 0 # always warn if, for whaterver reason, the black magic in above call fails
  146. if nout <= 2:
  147. warn(skimage_deprecation('`marching_cubes` now uses a better and '
  148. 'faster algorithm, and returns four instead '
  149. 'of two outputs (see docstring for details). '
  150. 'Backwards compatibility with 0.12 and prior '
  151. 'is available with `marching_cubes_classic`. '
  152. 'This function will be removed in 0.14, '
  153. 'consider switching to `marching_cubes_lewiner`.'))
  154. return marching_cubes_lewiner(volume, level, spacing, gradient_direction,
  155. step_size, allow_degenerate, use_classic)
  156. def marching_cubes_lewiner(volume, level=None, spacing=(1., 1., 1.),
  157. gradient_direction='descent', step_size=1,
  158. allow_degenerate=True, use_classic=False):
  159. """ Alias for ``marching_cubes()``.
  160. """
  161. # Check volume and ensure its in the format that the alg needs
  162. if not isinstance(volume, np.ndarray) or (volume.ndim != 3):
  163. raise ValueError('Input volume should be a 3D numpy array.')
  164. if volume.shape[0] < 2 or volume.shape[1] < 2 or volume.shape[2] < 2:
  165. raise ValueError("Input array must be at least 2x2x2.")
  166. volume = np.ascontiguousarray(volume, np.float32) # no copy if not necessary
  167. # Check/convert other inputs:
  168. # level
  169. if level is None:
  170. level = 0.5 * (volume.min() + volume.max())
  171. else:
  172. level = float(level)
  173. if level < volume.min() or level > volume.max():
  174. raise ValueError("Surface level must be within volume data range.")
  175. # spacing
  176. if len(spacing) != 3:
  177. raise ValueError("`spacing` must consist of three floats.")
  178. # step_size
  179. step_size = int(step_size)
  180. if step_size < 1:
  181. raise ValueError('step_size must be at least one.')
  182. # use_classic
  183. use_classic = bool(use_classic)
  184. # Get LutProvider class (reuse if possible)
  185. L = _get_mc_luts()
  186. # Apply algorithm
  187. func = _marching_cubes_lewiner_cy.marching_cubes
  188. vertices, faces , normals, values = func(volume, level, L, step_size, use_classic)
  189. if not len(vertices):
  190. raise RuntimeError('No surface found at the given iso value.')
  191. # Output in z-y-x order, as is common in skimage
  192. vertices = np.fliplr(vertices)
  193. normals = np.fliplr(normals)
  194. # Finishing touches to output
  195. faces.shape = -1, 3
  196. if gradient_direction == 'descent':
  197. # MC implementation is right-handed, but gradient_direction is left-handed
  198. faces = np.fliplr(faces)
  199. elif not gradient_direction == 'ascent':
  200. raise ValueError("Incorrect input %s in `gradient_direction`, see "
  201. "docstring." % (gradient_direction))
  202. if spacing != (1, 1, 1):
  203. vertices = vertices * np.r_[spacing]
  204. if allow_degenerate:
  205. return vertices, faces, normals, values
  206. else:
  207. fun = _marching_cubes_lewiner_cy.remove_degenerate_faces
  208. return fun(vertices, faces, normals, values)
  209. def _to_array(args):
  210. shape, text = args
  211. byts = base64decode(text.encode('utf-8'))
  212. ar = np.frombuffer(byts, dtype='int8')
  213. ar.shape = shape
  214. return ar
  215. # Map an edge-index to two relative pixel positions. The ege index
  216. # represents a point that lies somewhere in between these pixels.
  217. # Linear interpolation should be used to determine where it is exactly.
  218. # 0
  219. # 3 1 -> 0x
  220. # 2 xx
  221. EDGETORELATIVEPOSX = np.array([ [0,1],[1,1],[1,0],[0,0], [0,1],[1,1],[1,0],[0,0], [0,0],[1,1],[1,1],[0,0] ], 'int8')
  222. EDGETORELATIVEPOSY = np.array([ [0,0],[0,1],[1,1],[1,0], [0,0],[0,1],[1,1],[1,0], [0,0],[0,0],[1,1],[1,1] ], 'int8')
  223. EDGETORELATIVEPOSZ = np.array([ [0,0],[0,0],[0,0],[0,0], [1,1],[1,1],[1,1],[1,1], [0,1],[0,1],[0,1],[0,1] ], 'int8')
  224. def _get_mc_luts():
  225. """ Kind of lazy obtaining of the luts.
  226. """
  227. if not hasattr(mcluts, 'THE_LUTS'):
  228. mcluts.THE_LUTS = _marching_cubes_lewiner_cy.LutProvider(
  229. EDGETORELATIVEPOSX, EDGETORELATIVEPOSY, EDGETORELATIVEPOSZ,
  230. _to_array(mcluts.CASESCLASSIC), _to_array(mcluts.CASES),
  231. _to_array(mcluts.TILING1), _to_array(mcluts.TILING2), _to_array(mcluts.TILING3_1), _to_array(mcluts.TILING3_2),
  232. _to_array(mcluts.TILING4_1), _to_array(mcluts.TILING4_2), _to_array(mcluts.TILING5), _to_array(mcluts.TILING6_1_1),
  233. _to_array(mcluts.TILING6_1_2), _to_array(mcluts.TILING6_2), _to_array(mcluts.TILING7_1),
  234. _to_array(mcluts.TILING7_2), _to_array(mcluts.TILING7_3), _to_array(mcluts.TILING7_4_1),
  235. _to_array(mcluts.TILING7_4_2), _to_array(mcluts.TILING8), _to_array(mcluts.TILING9),
  236. _to_array(mcluts.TILING10_1_1), _to_array(mcluts.TILING10_1_1_), _to_array(mcluts.TILING10_1_2),
  237. _to_array(mcluts.TILING10_2), _to_array(mcluts.TILING10_2_), _to_array(mcluts.TILING11),
  238. _to_array(mcluts.TILING12_1_1), _to_array(mcluts.TILING12_1_1_), _to_array(mcluts.TILING12_1_2),
  239. _to_array(mcluts.TILING12_2), _to_array(mcluts.TILING12_2_), _to_array(mcluts.TILING13_1),
  240. _to_array(mcluts.TILING13_1_), _to_array(mcluts.TILING13_2), _to_array(mcluts.TILING13_2_),
  241. _to_array(mcluts.TILING13_3), _to_array(mcluts.TILING13_3_), _to_array(mcluts.TILING13_4),
  242. _to_array(mcluts.TILING13_5_1), _to_array(mcluts.TILING13_5_2), _to_array(mcluts.TILING14),
  243. _to_array(mcluts.TEST3), _to_array(mcluts.TEST4), _to_array(mcluts.TEST6),
  244. _to_array(mcluts.TEST7), _to_array(mcluts.TEST10), _to_array(mcluts.TEST12),
  245. _to_array(mcluts.TEST13), _to_array(mcluts.SUBCONFIG13),
  246. )
  247. return mcluts.THE_LUTS