Coverage for trimesh/voxel/base.py: 89%

171 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-11-22 02:08 +0000

1""" 

2voxel.py 

3----------- 

4 

5Convert meshes to a simple voxel data structure and back again. 

6""" 

7 

8from hashlib import sha256 

9 

10import numpy as np 

11 

12from .. import bounds as bounds_module 

13from .. import caching, util 

14from .. import transformations as tr 

15from ..constants import log 

16from ..exchange.binvox import export_binvox 

17from ..parent import Geometry 

18from ..typed import ShapeLike 

19from . import morphology, ops, transforms 

20from .encoding import DenseEncoding, Encoding 

21 

22 

23class VoxelGrid(Geometry): 

24 """ 

25 Store 3D voxels. 

26 """ 

27 

28 def __init__(self, encoding, transform=None, metadata=None): 

29 if transform is None: 

30 transform = np.eye(4) 

31 if isinstance(encoding, np.ndarray): 

32 encoding = DenseEncoding(encoding.astype(bool)) 

33 if encoding.dtype != bool: 

34 raise ValueError("encoding must have dtype bool") 

35 self._data = caching.DataStore() 

36 self.encoding = encoding 

37 self._transform = transforms.Transform(transform, datastore=self._data) 

38 self._cache = caching.Cache(id_function=self._data.__hash__) 

39 

40 self.metadata = {} 

41 # update the mesh metadata with passed metadata 

42 if isinstance(metadata, dict): 

43 self.metadata.update(metadata) 

44 elif metadata is not None: 

45 raise ValueError(f"metadata should be a dict or None, got {metadata!s}") 

46 

47 def __hash__(self): 

48 """ 

49 Get the hash of the current transformation matrix. 

50 

51 Returns 

52 ------------ 

53 hash : str 

54 Hash of transformation matrix 

55 """ 

56 return self._data.__hash__() 

57 

58 @property 

59 def identifier_hash(self) -> str: 

60 return sha256(hash(self).to_bytes()).hexdigest() 

61 

62 @property 

63 def encoding(self): 

64 """ 

65 `Encoding` object providing the occupancy grid. 

66 

67 See `trimesh.voxel.encoding` for implementations. 

68 """ 

69 return self._data["encoding"] 

70 

71 @encoding.setter 

72 def encoding(self, encoding): 

73 if isinstance(encoding, np.ndarray): 

74 encoding = DenseEncoding(encoding) 

75 elif not isinstance(encoding, Encoding): 

76 raise ValueError(f"encoding must be an Encoding, got {encoding!s}") 

77 if len(encoding.shape) != 3: 

78 raise ValueError(f"encoding must be rank 3, got shape {encoding.shape!s}") 

79 if encoding.dtype != bool: 

80 raise ValueError(f"encoding must be binary, got {encoding.dtype}") 

81 self._data["encoding"] = encoding 

82 

83 @property 

84 def transform(self): 

85 """4x4 homogeneous transformation matrix.""" 

86 return self._transform.matrix 

87 

88 @transform.setter 

89 def transform(self, matrix): 

90 """4x4 homogeneous transformation matrix.""" 

91 self._transform.matrix = matrix 

92 

93 @property 

94 def translation(self): 

95 """Location of voxel at [0, 0, 0].""" 

96 return self._transform.translation 

97 

98 @property 

99 def scale(self): 

100 """ 

101 3-element float representing per-axis scale. 

102 

103 Raises a `RuntimeError` if `self.transform` has rotation or 

104 shear components. 

105 """ 

106 return self._transform.scale 

107 

108 @property 

109 def pitch(self): 

110 """ 

111 Uniform scaling factor representing the side length of 

112 each voxel. 

113 

114 Returns 

115 ----------- 

116 pitch : float 

117 Pitch of the voxels. 

118 

119 Raises 

120 ------------ 

121 `RuntimeError` 

122 If `self.transformation` has rotation or shear 

123 components of has non-uniform scaling. 

124 """ 

125 return self._transform.pitch 

126 

127 @property 

128 def element_volume(self): 

129 return self._transform.unit_volume 

130 

131 def apply_transform(self, matrix): 

132 self._transform.apply_transform(matrix) 

133 return self 

134 

135 def strip(self): 

136 """ 

137 Mutate self by stripping leading/trailing planes of zeros. 

138 

139 Returns 

140 -------- 

141 self after mutation occurs in-place 

142 """ 

143 encoding, padding = self.encoding.stripped 

144 self.encoding = encoding 

145 self._transform.matrix[:3, 3] = self.indices_to_points(padding[:, 0]) 

146 return self 

147 

148 @caching.cache_decorator 

149 def bounds(self): 

150 indices = self.sparse_indices 

151 # get all 8 corners of the AABB 

152 corners = bounds_module.corners( 

153 [indices.min(axis=0) - 0.5, indices.max(axis=0) + 0.5] 

154 ) 

155 # transform these corners to a new frame 

156 corners = self._transform.transform_points(corners) 

157 # get the AABB of corners in-frame 

158 bounds = np.array([corners.min(axis=0), corners.max(axis=0)]) 

159 bounds.flags.writeable = False 

160 return bounds 

161 

162 @caching.cache_decorator 

163 def extents(self): 

164 bounds = self.bounds 

165 extents = bounds[1] - bounds[0] 

166 extents.flags.writeable = False 

167 return extents 

168 

169 @caching.cache_decorator 

170 def is_empty(self): 

171 return self.encoding.is_empty 

172 

173 @property 

174 def shape(self): 

175 """3-tuple of ints denoting shape of occupancy grid.""" 

176 return self.encoding.shape 

177 

178 @caching.cache_decorator 

179 def filled_count(self): 

180 """int, number of occupied voxels in the grid.""" 

181 return self.encoding.sum.item() 

182 

183 def is_filled(self, point): 

184 """ 

185 Query points to see if the voxel cells they lie in are 

186 filled or not. 

187 

188 Parameters 

189 ---------- 

190 point : (n, 3) float 

191 Points in space 

192 

193 Returns 

194 --------- 

195 is_filled : (n,) bool 

196 Is cell occupied or not for each point 

197 """ 

198 point = np.asanyarray(point) 

199 indices = self.points_to_indices(point) 

200 in_range = np.logical_and( 

201 np.all(indices < np.array(self.shape), axis=-1), np.all(indices >= 0, axis=-1) 

202 ) 

203 

204 is_filled = np.zeros_like(in_range) 

205 is_filled[in_range] = self.encoding.gather_nd(indices[in_range]) 

206 return is_filled 

207 

208 def fill(self, method: str = "holes", **kwargs): 

209 """ 

210 Mutates self by filling in the encoding according 

211 to `morphology.fill`. 

212 

213 Parameters 

214 ---------- 

215 method : str 

216 Implementation key, one of 

217 `trimesh.voxel.morphology.fill.fillers` keys 

218 **kwargs : dict 

219 Additional kwargs passed through to 

220 the keyed implementation. 

221 

222 Returns 

223 ---------- 

224 self : VoxelGrid 

225 After replacing encoding with a filled version. 

226 """ 

227 self.encoding = morphology.fill(self.encoding, method=method, **kwargs) 

228 return self 

229 

230 def hollow(self): 

231 """ 

232 Mutates self by removing internal voxels 

233 leaving only surface elements. 

234 

235 Surviving elements are those in encoding that are 

236 adjacent to an empty voxel where adjacency is 

237 controlled by `structure`. 

238 

239 Returns 

240 ---------- 

241 self : VoxelGrid 

242 After replacing encoding with a surface version. 

243 """ 

244 self.encoding = morphology.surface(self.encoding) 

245 return self 

246 

247 @caching.cache_decorator 

248 def marching_cubes(self): 

249 """ 

250 A marching cubes Trimesh representation of the voxels. 

251 

252 No effort was made to clean or smooth the result in any way; 

253 it is merely the result of applying the scikit-image 

254 measure.marching_cubes function to self.encoding.dense. 

255 

256 Returns 

257 --------- 

258 meshed : trimesh.Trimesh 

259 Representing the current voxel 

260 object as returned by marching cubes algorithm. 

261 """ 

262 return ops.matrix_to_marching_cubes(matrix=self.matrix) 

263 

264 @property 

265 def matrix(self): 

266 """ 

267 Return a DENSE matrix of the current voxel encoding. 

268 

269 Returns 

270 ------------- 

271 dense : (a, b, c) bool 

272 Numpy array of dense matrix 

273 Shortcut to voxel.encoding.dense 

274 """ 

275 return self.encoding.dense 

276 

277 @caching.cache_decorator 

278 def volume(self): 

279 """ 

280 What is the volume of the filled cells in the current 

281 voxel object. 

282 

283 Returns 

284 --------- 

285 volume : float 

286 Volume of filled cells. 

287 """ 

288 return self.filled_count * self.element_volume 

289 

290 @caching.cache_decorator 

291 def points(self): 

292 """ 

293 The center of each filled cell as a list of points. 

294 

295 Returns 

296 ---------- 

297 points : (self.filled, 3) float 

298 Points in space. 

299 """ 

300 return self._transform.transform_points(self.sparse_indices.astype(float)) 

301 

302 @property 

303 def sparse_indices(self): 

304 """(n, 3) int array of sparse indices of occupied voxels.""" 

305 return self.encoding.sparse_indices 

306 

307 def as_boxes(self, colors=None, **kwargs): 

308 """ 

309 A rough Trimesh representation of the voxels with a box 

310 for each filled voxel. 

311 

312 Parameters 

313 ---------- 

314 colors : None, (3,) or (4,) float or uint8 

315 (X, Y, Z, 3) or (X, Y, Z, 4) float or uint8 

316 Where matrix.shape == (X, Y, Z) 

317 

318 Returns 

319 --------- 

320 mesh : trimesh.Trimesh 

321 Mesh with one box per filled cell. 

322 """ 

323 

324 if colors is not None: 

325 colors = np.asanyarray(colors) 

326 if colors.ndim == 4: 

327 encoding = self.encoding 

328 if colors.shape[:3] == encoding.shape: 

329 # TODO jackd: more efficient implementation? 

330 # encoding.as_mask? 

331 colors = colors[encoding.dense] 

332 else: 

333 log.warning("colors incorrect shape!") 

334 colors = None 

335 elif colors.shape not in ((3,), (4,)): 

336 log.warning("colors incorrect shape!") 

337 colors = None 

338 

339 mesh = ops.multibox(centers=self.sparse_indices.astype(float), colors=colors) 

340 

341 mesh = mesh.apply_transform(self.transform) 

342 return mesh 

343 

344 def points_to_indices(self, points): 

345 """ 

346 Convert points to indices in the matrix array. 

347 

348 Parameters 

349 ---------- 

350 points: (n, 3) float, point in space 

351 

352 Returns 

353 --------- 

354 indices: (n, 3) int array of indices into self.encoding 

355 """ 

356 points = self._transform.inverse_transform_points(points) 

357 return np.round(points).astype(int) 

358 

359 def indices_to_points(self, indices): 

360 return self._transform.transform_points(indices.astype(float)) 

361 

362 def show(self, *args, **kwargs): 

363 """ 

364 Convert the current set of voxels into a trimesh for visualization 

365 and show that via its built- in preview method. 

366 """ 

367 return self.as_boxes(kwargs.pop("colors", None)).show(*args, **kwargs) 

368 

369 def copy(self): 

370 return VoxelGrid(self.encoding.copy(), self._transform.matrix.copy()) 

371 

372 def export(self, file_obj=None, file_type=None, **kwargs): 

373 """ 

374 Export the current VoxelGrid. 

375 

376 Parameters 

377 ------------ 

378 file_obj : file-like or str 

379 File or file-name to export to. 

380 file_type : None or str 

381 Only 'binvox' currently supported. 

382 

383 Returns 

384 --------- 

385 export : bytes 

386 Value of export. 

387 """ 

388 if isinstance(file_obj, str) and file_type is None: 

389 file_type = util.split_extension(file_obj).lower() 

390 

391 if file_type != "binvox": 

392 raise ValueError("only binvox exports supported!") 

393 

394 exported = export_binvox(self, **kwargs) 

395 if hasattr(file_obj, "write"): 

396 file_obj.write(exported) 

397 elif isinstance(file_obj, str): 

398 with open(file_obj, "wb") as f: 

399 f.write(exported) 

400 return exported 

401 

402 def revoxelized(self, shape: ShapeLike): 

403 """ 

404 Create a new VoxelGrid without rotations, reflections 

405 or shearing. 

406 

407 Parameters 

408 ---------- 

409 shape : (3,) int 

410 The shape of the returned VoxelGrid. 

411 

412 Returns 

413 ---------- 

414 vox : VoxelGrid 

415 Of the given shape with possibly non-uniform 

416 scale and translation transformation matrix. 

417 """ 

418 shape = np.atleast_1d(shape) 

419 if shape.shape != (3,): 

420 raise ValueError(f"shape must be 3D, got {shape}") 

421 scale = self.extents / shape 

422 # the first and last cell centers of a grid spanning `self.bounds` 

423 centers = self.bounds + np.array([scale, -scale]) / 2.0 

424 points = util.grid_linspace(centers, shape).reshape((*shape, 3)) 

425 dense = self.is_filled(points) 

426 return VoxelGrid(dense, transform=tr.scale_and_translate(scale, centers[0])) 

427 

428 def __add__(self, other): 

429 raise NotImplementedError("TODO : implement voxel concatenation")