-
Notifications
You must be signed in to change notification settings - Fork 5
/
freesurfer2vtks.py
executable file
·95 lines (75 loc) · 2.66 KB
/
freesurfer2vtks.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
88
89
90
91
92
93
94
95
#!/usr/bin/env python
import vtk
import sys
import os
import json
import pandas as pd
if not os.path.exists("classification/surfaces"):
os.makedirs("classification/surfaces")
#lut = pd.read_csv('FreeSurferColorLUT.csv')
with open("labels.json") as f:
labels = json.load(f)
img_path = 'aparc.a2009s+aseg.nii.gz'
# import the binary nifti image
print("loading %s" % img_path)
reader = vtk.vtkNIFTIImageReader()
reader.SetFileName(img_path)
reader.Update()
print("list unique values (super slow!)")
out = reader.GetOutput()
vtk_data=out.GetPointData().GetScalars()
unique = set()
for i in range(0, vtk_data.GetSize()):
v = vtk_data.GetValue(i)
unique.add(v)
index=[]
for label in labels:
label_id=int(label["label"])
#only handle some surfaces
#if label_id < 1000 or label_id > 2036:
# continue
if not label_id in unique:
continue
surf_name=label['label']+'.'+label['name']+'.vtk'
label["filename"] = surf_name
print(surf_name)
#label["label"] = label_id
index.append(label)
# 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, label_id, label_id)
surface.Update()
#print(surface)
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())
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("classification/surfaces/"+surf_name)
writer.Write()
print("writing surfaces/index.json")
with open("classification/surfaces/index.json", "w") as outfile:
json.dump(index, outfile)
print("all done")