-
Notifications
You must be signed in to change notification settings - Fork 4
/
craniometrics.py
300 lines (238 loc) · 11 KB
/
craniometrics.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
"""
Created on Mon Aug 2, 2021
Last update on December 12, 2022
@author: TAbdelAlim
"""
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pyvista as pv
import json
class CranioMetrics:
"""
Basic Cranial Measurements class
:param file_name: String representing the filename
:param slice_d: Horizontal distance between two consequtive slides
"""
def __init__(self, file_path, slice_d=1):
# file_path = Path(file_path)
self.file_name = file_path.stem
self.file_ext = file_path.suffix
self.pvmesh = pv.read(file_path)
d = np.zeros_like(self.pvmesh.points)
self.array_name = 'coordinates'
self.pvmesh[self.array_name] = d[:, 1]
self.pvmesh.points += d
self.x_bounds = [
int(np.ceil(self.pvmesh.bounds[0])),
int(np.ceil(self.pvmesh.bounds[1]))
]
self.y_bounds = [
int(np.ceil(self.pvmesh.bounds[2])),
int(np.ceil(self.pvmesh.bounds[3]))
]
self.z_bounds = [
int(np.ceil(self.pvmesh.bounds[4])),
int(np.ceil(self.pvmesh.bounds[5]))
]
self.slice_mesh(slice_d)
def slice_mesh(self, slice_d):
"""
generate axial slices throughout the mesh and extract measures from
slices
:param slice_d: Horizontal distance between two consequtive slides
:return: Height and index of the slice where max depth is found and
breadth <180mm to correct for ears.
"""
# empty_dataframe for slice bounds
self.slice_df = pd.DataFrame(columns=[
'depth',
'breadth',
'x_min',
'x_max',
'y',
'z_min',
'z_max',
])
# create slices and calculate bounds/optima for every slice
for i in range(0, self.y_bounds[1], slice_d):
self.slice_d = slice_d
self.mesh_s = self.pvmesh.slice(normal=[0, 1, 0], origin=[0, i, 0])
mb = self.mesh_s.bounds
self.slice_df = self.slice_df.append({
'depth': np.round(mb[5] - mb[4], 2),
'breadth': np.round(mb[1] - mb[0], 2),
'x_min': mb[0], # left
'x_max': mb[1], # right
'y': mb[2], # slice number (height of slice = 1 so mb[2] = mb[3] = slice height
'z_min': mb[4], # rear
'z_max': mb[5] # front
}, ignore_index=True)
# index and z-height at which max depth is found
self.slice_index = np.where(self.slice_df['depth']
== self.slice_df.depth.max())[0][0]
# check if the ears are not in the slice (excessive breadth > 180mm)
# else go to next slice (max 100 slice searches)
count_b = 0
while self.slice_df.breadth.iloc[self.slice_index] >= 180 and count_b <= 100:
count_b += 1
self.slice_index += self.slice_d
self.slice_df.breadth.iloc[self.slice_index]
self.slice_height = self.slice_df.iloc[self.slice_index].y
self.breadth = self.slice_df.iloc[self.slice_index].breadth
def show_slices(self, plotter, axis='y'):
# create slices and calculate bounds/optima for every slice
if axis == 'x':
for i in range(self.x_bounds[0], self.x_bounds[1], self.slice_d):
self.mesh_sx = self.pvmesh.slice(normal=[1, 0, 0], origin=[i, 0, 0])
plotter.add_mesh(self.mesh_sx, color='white')
if axis == 'y':
for i in range(self.y_bounds[0], self.y_bounds[1], self.slice_d):
self.mesh_sy = self.pvmesh.slice(normal=[0, 1, 0], origin=[0, i, 0])
plotter.add_mesh(self.mesh_sy, color='white')
if axis == 'z':
for i in range(self.z_bounds[0], self.z_bounds[1], self.slice_d):
self.mesh_s = self.pvmesh.slice(normal=[0, 0, 1], origin=[0, 0, i])
plotter.add_mesh(self.mesh_s, color='white')
def extract_dimensions(self, slice_height):
"""
extract_dimensions(self.slice_height) extracts the basic measures from
the mesh (depth, breadth, CI, HC).
:param slice_height: Y-value of the slice at which max depth is found
(self.slice_height) and at which the measures are extracted
:return: Cranial depth, breadth, CI, HC, xyz coordinates of bounds
"""
def cart2pol(x, y): # cartesian to polar (radians)
rho = np.sqrt(x ** 2 + y ** 2)
phi = np.arctan2(y, x)
return (rho, phi)
def dist_polar( # phi in rad
rho1,
phi1,
rho2,
phi2,
):
dist = np.sqrt(rho1 ** 2 + rho2 ** 2 - 2 * rho1 * rho2
* np.cos(phi1 - phi2))
return dist
HC_slice = self.pvmesh.slice(normal=[0, 1, 0], origin=[0, slice_height, 0])
HCP = HC_slice.points
polar = []
for i in range(len(HCP)):
polar.append(cart2pol(HCP[i][0], HCP[i][2]))
self.polar_df = pd.DataFrame(polar, columns=['rho', 'phi'
]).sort_values('phi').reset_index(drop=True)
HC_estimate = 0
for i in range(len(HCP) - 1):
p = self.polar_df.iloc[i] # point
n_p = self.polar_df.iloc[i + 1] # next_point
HC_estimate = HC_estimate + dist_polar(p.rho, p.phi,
n_p.rho, n_p.phi)
self.HC = np.round(HC_estimate / 10, 1)
if self.HC <= 60:
try:
self.slice_index = np.where(self.slice_df['y']
== slice_height)[0][0]
except IndexError:
print('Orientation problem; unable to detect slice')
else:
slice_height += self.slice_d
self.extract_dimensions(slice_height)
self.HC_s = self.pvmesh.slice(normal=[0, 1, 0], origin=[0, self.slice_height, 0])
# self.HC_s = self.pvmesh.slice(normal=[0, 0, 1], origin=[0, 0,
# self.slice_height])
hb = self.HC_s.bounds
self.depth = np.round(hb[5] - hb[4], 2)
self.breadth = np.round(hb[1] - hb[0], 2)
self.CI = np.round(100 * (self.breadth / self.depth), 1)
lh_opt_index = np.where(self.HC_s.points[:, 0] == hb[0])
self.lh_opt = self.HC_s.points[lh_opt_index][0]
rh_opt_index = np.where(self.HC_s.points[:, 0] == hb[1])
self.rh_opt = self.HC_s.points[rh_opt_index][0]
occ_opt_index = np.where(self.HC_s.points[:, 2] == hb[4])
self.occ_opt = self.HC_s.points[occ_opt_index][0]
front_opt_index = np.where(self.HC_s.points[:, 2] == hb[5])
self.front_opt = self.HC_s.points[front_opt_index][0]
self.optima_df = pd.DataFrame(columns=['front_opt', 'occ_opt',
'rh_opt', 'lh_opt'])
self.optima_df = self.optima_df.append({
'front_opt': self.front_opt,
'occ_opt': self.occ_opt,
'rh_opt': self.rh_opt,
'lh_opt': self.lh_opt,
}, ignore_index=True)
def plot_craniometrics(self, plotter, n_axes=1, slice_only=True):
"""
plotting of the extracted extracted craniometrics
:param opacity: Mesh opacity
:return: pv.BackgroundPlotter containing the extracted measures in text,
the original mesh and in red: HC line and the four optima used to
calculated the CI.
"""
plotter.add_mesh(self.HC_s, color='red', line_width=12)
if slice_only:
plotter.view_xz(True)
if n_axes == 3: # visualize the 3 orthogonal axes instead of just the OFD slice
temp1 = self.pvmesh.slice(normal=[0, 0, 1], origin=[0, 0, 0])
temp2 = self.pvmesh.slice(normal=[1, 0, 0], origin=[0, 0, 0])
plotter.add_mesh(temp1, color='red', line_width=12)
plotter.add_mesh(temp2, color='red', line_width=12)
plotter.add_points(np.array([self.front_opt, self.occ_opt,
self.lh_opt, self.rh_opt]),
render_points_as_spheres=True,
point_size=20, color='k')
plotter.add_points(np.array([self.HC_s.center_of_mass()[0], self.slice_height, self.HC_s.center_of_mass()[2]]),
render_points_as_spheres=True, color='r', point_size=15)
plotter.add_text('''file = {}.stl
OFD (depth) = {} mm
BPD (breadth) = {} mm
Cephalic Index = {}
Circumference = {} cm
Mesh volume = {} cc '''.format(
self.file_name,
round(np.float64(self.depth), 2),
round(np.float64(self.breadth), 2),
self.CI,
self.HC,
round((self.pvmesh.volume / 1000), 2),
), font_size=10, color='white')
# ICV correlation based on CT: round((((self.pvmesh.volume / 1000) + 46.4349) / 1.4566), 2)
def plot_HC_slice(self):
self.extract_dimensions(self.slice_height)
fig = plt.figure()
ax = fig.add_subplot(111, projection='polar')
plt.polar(self.polar_df["phi"], self.polar_df["rho"], color='r') # plot polar HC
def callback(self, mesh, pid, **dargs):
point = self.pvmesh.points[pid]
label = ['Index: {}\n{}: {}'.format(pid,
self.array_name,
mesh.points[pid])]
self.coord = mesh.points[pid]
def picking(self, plotter, target=None):
plotter.enable_point_picking(callback=self.callback, show_message=False,
color='red', point_size=20,
use_mesh=True, show_point=True, render_points_as_spheres=True)
self.coord = plotter.picked_point
if target == 'nose':
self.nose_coord = plotter.picked_point
plotter.add_points(self.nose_coord,
render_points_as_spheres=True,
point_size=20, color='green')
plotter.add_text('nasion: {}'.format(str(self.nose_coord)), 'upper_right', font_size=10)
return self.nose_coord
elif target == 'left':
self.left_coord = plotter.picked_point
plotter.add_points(self.left_coord,
render_points_as_spheres=True,
point_size=20, color='green')
plotter.add_text('\nLH tragus: {}'.format(str(self.left_coord)), 'upper_right', font_size=10)
return self.left_coord
elif target == 'right':
self.right_coord = plotter.picked_point
plotter.add_points(self.right_coord,
render_points_as_spheres=True,
point_size=20, color='green')
plotter.add_text('\n\nRH tragus: {}'.format(str(self.right_coord)), 'upper_right', font_size=10)
return self.right_coord
else:
pass