-
Notifications
You must be signed in to change notification settings - Fork 5
/
mask2surface.py
executable file
·88 lines (69 loc) · 2.54 KB
/
mask2surface.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/usr/bin/env python
import vtk
import sys
import os
import json
import pandas as pd
from matplotlib import cm
index=[]
inputdir="tractseg_output/bundle_segmentations"
files = os.listdir(inputdir)
for file in files:
if file[0] == ".":
continue
tokens = file.split(".")
surf_name=tokens[0]
vtk_filename=surf_name+".vtk"
#r=100
#g=100
#b=0
#color=list(cm.nipy_spectral(len(index)))[0:3]
color=list(cm.hsv(len(index)/len(files)))[0:3]
#index.append({'filename':vtk_filename, 'name': surf_name, 'color': {'r':r, 'g':g, 'b':b}})
index.append({'filename':vtk_filename, 'name': surf_name, 'color': color})
img_path = inputdir+"/"+file
# import the binary nifti image
print("loading %s" % img_path)
reader = vtk.vtkNIFTIImageReader()
reader.SetFileName(img_path)
reader.Update()
print(reader.GetQFormMatrix())
print(reader.GetSFormMatrix())
# do marching cubes to create a surface
surface = vtk.vtkDiscreteMarchingCubes()
surface.SetInputConnection(reader.GetOutputPort())
# GenerateValues(number of surfaces, label range start, label range end)
surface.GenerateValues(1, 1, 1)
surface.Update()
smoother = vtk.vtkWindowedSincPolyDataFilter()
smoother.SetInputConnection(surface.GetOutputPort())
smoother.SetNumberOfIterations(10)
smoother.NonManifoldSmoothingOn()
smoother.NormalizeCoordinatesOn()
smoother.Update()
connectivityFilter = vtk.vtkPolyDataConnectivityFilter()
connectivityFilter.SetInputConnection(smoother.GetOutputPort())
connectivityFilter.SetExtractionModeToLargestRegion()
connectivityFilter.Update()
untransform = vtk.vtkTransform()
#untransform.SetMatrix(reader.GetQFormMatrix())
untransform.SetMatrix(reader.GetSFormMatrix())
untransformFilter=vtk.vtkTransformPolyDataFilter()
untransformFilter.SetTransform(untransform)
untransformFilter.SetInputConnection(connectivityFilter.GetOutputPort())
untransformFilter.Update()
cleaned = vtk.vtkCleanPolyData()
cleaned.SetInputConnection(untransformFilter.GetOutputPort())
cleaned.Update()
deci = vtk.vtkDecimatePro()
deci.SetInputConnection(cleaned.GetOutputPort())
deci.SetTargetReduction(0.5)
deci.PreserveTopologyOn()
writer = vtk.vtkPolyDataWriter()
writer.SetInputConnection(deci.GetOutputPort())
writer.SetFileName("wmc/surfaces/"+vtk_filename)
writer.Write()
print("writing surfaces/index.json")
with open("wmc/surfaces/index.json", "w") as outfile:
json.dump(index, outfile)
print("all done")