-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate_mesh_object_from_nifti.py
39 lines (29 loc) · 1.12 KB
/
create_mesh_object_from_nifti.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from pathlib import Path
from skimage.measure import marching_cubes
import nibabel as nib
import time
def convert_nii_to_mesh():
source = Path(r'./path/to/mask.nii.gz')
dest = Path(r'./path/to/mesh.obj')
img = nib.load(source)
spacing = img.header.get_zooms()
arr = img.get_fdata()
verts, faces, normals, values = marching_cubes(arr)
# voxel grid coordinates to world coordinates: verts * voxel_size + origin
verts = verts * spacing + img.affine[0:3, -1]
# without spacing
# verts = verts + img.affine[0:3, -1]
faces = faces + 1
for idx, normal in enumerate(normals):
normal = [-n for n in normal]
normals[idx] = normal
with open(dest, 'w') as out_file:
for item in verts:
out_file.write("v {0} {1} {2}\n".format(item[0], item[1], item[2]))
for item in normals:
out_file.write("vn {0} {1} {2}\n".format(item[0], item[1], item[2]))
for item in faces:
out_file.write("f {0}//{0} {1}//{1} {2}//{2}\n".format(item[0], item[1], item[2]))
out_file.close()
if __name__ == '__main__':
convert_nii_to_mesh()