-
Notifications
You must be signed in to change notification settings - Fork 0
/
pyfabric.py
447 lines (361 loc) · 13.5 KB
/
pyfabric.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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Compute fabric tensor by the 3D Auto Correlation Function (ACF) of images.
For more information, call this script with the help option:
pyfabric.py -h
"""
__author__ = ['Gianluca Iori']
__date_created__ = '2021-10-22'
__date__ = '2024-04-27'
__copyright__ = 'Copyright (c) 2024, ORMIR'
__docformat__ = 'restructuredtext en'
__license__ = "GPL"
__version__ = "1.4"
__maintainer__ = 'Gianluca Iori'
__email__ = "gianthk.iori@gmail.com"
import numpy as np
import numexpr as ne
import ellipsoid_fit as ef
from tqdm import tqdm
from scipy import ndimage
import matplotlib.pyplot as plt
import importlib
#################################################################################
def ACF(I):
"""Calculate 3D Auto Correlation Function (ACF) of given image.
Taking advantage of the Wiener–Khintchine theorem (https://mathworld.wolfram.com/Wiener-KhinchinTheorem.html)
the ACF is computed in the Fourier domain as:
ACF = |ffti(fft(I) conj (fft(I)))|
with fft() and ffti() being the discrete Fourier and discrete inverse Fourier transforms of the image I, respectively [1].
[1] P. Varga et al., “Investigation of the three-dimensional orientation of mineralized collagen fibrils in human lamellar bone using synchrotron X-ray phase nano-tomography,” Acta Biomaterialia, vol. 9, no. 9, pp. 8118–8127, Sep. 2013, doi: 10.1016/j.actbio.2013.05.015.
Parameters
----------
I
3D image.
Returns
-------
ACF
3D Auto Correlation Function.
"""
Ev = np.fft.fftshift(np.fft.fftn(I))
return np.abs(np.fft.ifftshift(np.fft.ifftn(Ev * np.conj(Ev))))
def zoom_center(ACF, size=None, zoom_factor=None):
"""Crop and zoom center of the ACF.
Parameters
----------
ACF : ndarray
ACF data.
size : int
Size of the zoomed center.
zoom_factor
Zoom factor for imresize.
Returns
-------
ACF_center: ndarray
Zoomed center of the ACF.
"""
if zoom_factor is None:
zoom_factor = 2
center = ACF.shape
if size is None:
size = min(center)/2
size = round(size/2)
center = [int(center[0]/2), int(center[1]/2), int(center[2]/2)]
# resize the 3D data using spline interpolation of order 2
return ndimage.zoom(ACF[center[0]-size:center[0]+size, center[1]-size:center[1]+size, center[2]-size:center[2]+size], zoom_factor, output=None, order=2)
def envelope(bw, method='marching_cubes'):
"""Envelope of Trues from binary image.
Parameters
----------
bw : ndarray
Binary image.
method : str
'pymcubes': Requires PyMCubes module.
'marching_cubes': scikit-image's marching cube algorithm.
Returns
-------
vertices: ndarray
Coordinates [X, Y, Z] of the ACF envelope.
"""
# if importlib.util.find_spec("mcubes") is not None:
# import mcubes
# else:
#
if method == 'pymcubes' and importlib.util.find_spec("mcubes") is None:
import warnings
warnings.warn("mcubes module not found. Switching to skimage method marching_cubes")
method = 'marching_cubes'
if method == 'pymcubes':
import mcubes
# (the 0-levelset of the output of mcubes.smooth is the smoothed version of the 0.5-levelset of the binary array.
smoothed_L = mcubes.smooth(bw)
# Extract the 0-levelset
vertices, triangles = mcubes.marching_cubes(np.transpose(smoothed_L, [2, 1, 0]), 0)
# vertices, triangles = mcubes.marching_cubes(smoothed_L, 0)
elif method == 'marching_cubes':
from skimage.measure import marching_cubes
vertices, triangles, tmp, tmp2 = marching_cubes(np.transpose(bw, [2, 1, 0]), level=None, step_size=1)
# vertices, triangles, tmp, tmp2 = marching_cubes(bw, level=None, step_size=1)
else:
raise IOError('{0} method unknown.', format(method))
return vertices
def set_axes_equal(ax):
'''Make axes of 3D plot have equal scale so that spheres appear as spheres,
cubes as cubes, etc.. This is one possible solution to Matplotlib's
ax.set_aspect('equal') and ax.axis('equal') not working for 3D.
Source
https://stackoverflow.com/questions/13685386/matplotlib-equal-unit-length-with-equal-aspect-ratio-z-axis-is-not-equal-to
Input
ax: a matplotlib axis, e.g., as output from plt.gca().
'''
x_limits = ax.get_xlim3d()
y_limits = ax.get_ylim3d()
z_limits = ax.get_zlim3d()
x_range = abs(x_limits[1] - x_limits[0])
x_middle = np.mean(x_limits)
y_range = abs(y_limits[1] - y_limits[0])
y_middle = np.mean(y_limits)
z_range = abs(z_limits[1] - z_limits[0])
z_middle = np.mean(z_limits)
# The plot bounding box is a sphere in the sense of the infinity
# norm, hence I call half the max range the plot radius.
plot_radius = 0.5*max([x_range, y_range, z_range])
ax.set_xlim3d([x_middle - plot_radius, x_middle + plot_radius])
ax.set_ylim3d([y_middle - plot_radius, y_middle + plot_radius])
ax.set_zlim3d([z_middle - plot_radius, z_middle + plot_radius])
def scatter_plot(coors):
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(coors[:,0], coors[:,1], coors[:,2], zdir='z', s=20, c='b',rasterized=True)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
set_axes_equal(ax)
# plt.show()
return ax
def to01(I):
"""Normalize data to 0-1 range.
Parameters
----------
I
Input data.
Returns
-------
I : float32
Normalized data.
"""
I = I.astype(np.float32, copy=False)
data_min = np.nanmin(I)
data_max = np.nanmax(I)
df = np.float32(data_max - data_min)
mn = np.float32(data_min)
scl = ne.evaluate('(I-mn)/df', truediv=True)
return scl.astype(np.float32)
def to01andbinary(I, t):
"""Normalize data to 0-1 range and segment with given threshold.
Parameters
----------
I
Input data.
t : float
Threshold in the 0-1 range.
Returns
-------
I_binary : bool
Data after normalization and thresholding.
"""
I = I.astype(np.float32, copy=False)
data_min = np.nanmin(I)
data_max = np.nanmax(I)
df = np.float32(data_max - data_min)
mn = np.float32(data_min)
scl = ne.evaluate('(I-mn)/df > t', truediv=True)
return scl.astype(np.bool)
def fabric_pointset(I, pointset, ROIsize, ACF_threshold=0.5, ROIzoom=False, zoom_size=None, zoom_factor=None):
"""Compute fabric tensor of an image at given set of points.
Parameters
----------
I
3D image data.
pointset
(Nx3) Points coordinates [x, y, z].
ROIsize
Size of the Region Of Interest for the analysis.
ACF_threshold : int
ACF threshold value (0-1 range).
ROIzoom : bool
Zoom center of ACF before ellipsoid fit.
zoom_size : int
Size of the zoomed center.
zoom_factor
Zoom factor for imresize.
Returns
-------
evecs : float
(Nx3x3) Fabric tensor eigenvectors as the columns of a 3x3 matrix for each point in pointset.
radii : float
(Nx3) Ellipsoid radii.
evals : float
(Nx3) Ellipsoid eigenvalues.
fabric_comp : float
(Nx6) Ellipsoid tensor components with order: XX, YY, ZZ, XY, YZ, XZ
DA : float
Degree of Anisotropy (ratio between major and minor fabric ellipsoid axes)
"""
# parameters
n_points = pointset.shape[0]
halfROIsize = ROIsize/2
I_size = [I.shape[0]-1, I.shape[1]-1, I.shape[2]-1]
point_count = 0
# initialize output variables
evecs = np.zeros([n_points, 3, 3])
radii = np.zeros([n_points, 3])
fabric_tens = np.ndarray(evecs.shape)
fabric_comp = np.ndarray([evecs.shape[0], 6])
if ROIzoom:
# loop all points in the set
for p in tqdm(pointset):
# ROI extreemes
x0 = round(p[0] - halfROIsize)
y0 = round(p[1] - halfROIsize)
z0 = round(p[2] - halfROIsize)
x1 = x0 + ROIsize
y1 = y0 + ROIsize
z1 = z0 + ROIsize
# check if ROI exceeds image limits
if x0 < 0:
x0 = 0
if y0 < 0:
y0 = 0
if z0 < 0:
z0 = 0
if x1 > I_size[2]:
x1 = I_size[2]
if y1 > I_size[1]:
y1 = I_size[1]
if z1 > I_size[0]:
z1 = I_size[0]
# extract ROI around point p
ROI = I[z0:z1, y0:y1, x0:x1]
# calculate ACF
ROIACF = ACF(ROI)
# zoom ACF center
ROIACF = zoom_center(ROIACF, size=zoom_size, zoom_factor=zoom_factor) # check if size of the zoom can be reduced
# envelope of normalized ACF center
# env_points = envelope(to01(ROIACF)>ACF_threshold)
env_points = envelope(to01andbinary(ROIACF, ACF_threshold))
# ellipsoid fit
center, evecs[point_count, :, :], radii[point_count, :], v = ef.ellipsoid_fit(env_points)
# center, evecs[point_count, :, :], radii[point_count, :], v = ef.ellipsoid_fit(env_points*[1,-1,1])
point_count = point_count + 1
else:
# loop all points in the set
for p in tqdm(pointset):
# ROI extreemes
x0 = round(p[0] - halfROIsize)
y0 = round(p[1] - halfROIsize)
z0 = round(p[2] - halfROIsize)
x1 = x0 + ROIsize
y1 = y0 + ROIsize
z1 = z0 + ROIsize
# check if ROI exceeds image limits
if x0 < 0:
x0 = 0
if y0 < 0:
y0 = 0
if z0 < 0:
z0 = 0
if x1 > I_size[2]:
x1 = I_size[2]
if y1 > I_size[1]:
y1 = I_size[1]
if z1 > I_size[0]:
z1 = I_size[0]
# extract ROI around point p
ROI = I[z0:z1, y0:y1, x0:x1]
# calculate ACF
ROIACF = ACF(ROI)
# envelope of normalized ACF
# the ACF intensity is normalized to the 0-1 range
# env_points = envelope(to01(ROIACF) > ACF_threshold)
env_points = envelope(to01andbinary(ROIACF, ACF_threshold))
# ellipsoid fit
# the ellipsoid envelope coordinates are scaled to 0-1
center, evecs[point_count, :, :], radii[point_count, :], v = ef.ellipsoid_fit(env_points/ROIsize)
# center, evecs[point_count, :, :], radii[point_count, :], v = ef.ellipsoid_fit((env_points*[1,-1,1])/ROIsize)
point_count = point_count + 1
# take abs value of the radii vector
radii = np.abs(radii)
# compute Degree of Anisotropy
DA = np.max(radii, 1) / np.min(radii, 1)
# Remove potential outliers based on the ellipsoid radii:
# any ellipsoid with a radius > ROIsize/2 is removed
idx = np.any(radii > ROIsize * zoom_factor / 2, axis=1)
radii[idx, :] = np.nan
DA[idx] = np.nan
# ellipsoid radii < 1 voxel are meaningless
idx = np.any(radii < 1, axis=1)
radii[idx, :] = np.nan
DA[idx] = np.nan
# Ellipsoid eigenvalues
evals = 1 / (radii ** 2)
# Symmetric ellipsoid tensor components
for cell in range(0, evecs.shape[0]):
fabric_tens[cell, :, :] = np.matmul(evecs[cell, :, :], np.matmul((evals[cell, :] * np.identity(3)), np.transpose(evecs[cell, :, :])))
fabric_comp[cell, :] = fabric_tens[cell, [0, 1, 2, 0, 1, 0], [0, 1, 2, 1, 2, 2]]
# fabric_comp[cell, :] = fabric_tens[cell, [2, 1, 0, 1, 0, 0], [2, 1, 0, 2, 1, 2]]
# evecs[cell, :, :] = np.flipud(evecs[cell, :, :])
return evecs, radii, evals, fabric_comp, DA
# return evecs, np.flipud(radii), np.flipud(evals), fabric_comp, DA
def fabric(I, ACF_threshold=0.5, zoom=False, zoom_size=None, zoom_factor=None, ACFplot=None):
"""Compute fabric tensor of a given image.
Parameters
----------
I
3D image data.
ACF_threshold : int
ACF threshold value (0-1 range).
zoom : bool
Zoom center of ACF before ellipsoid fit.
zoom_size : int
Size of the zoomed center.
zoom_factor
Zoom factor for imresize.
ACFplot
PLot of ACF.
Returns
-------
evecs : float
(3x3) Fabric tensor eigenvectors as the columns of a 3x3 matrix.
radii : float
Ellipsoid radii.
evals : float
Ellipsoid eigenvalues.
fabric_comp : float
Ellipsoid tensor components with order: XX, YY, ZZ, XY, YZ, XZ
DA : float
Degree of Anisotropy (ratio between major and minor fabric ellipsoid axes)
"""
# calculate ACF
ACF_I = ACF(I)
if zoom:
# zoom ACF center
ACF_I = zoom_center(ACF_I, size=zoom_size, zoom_factor=zoom_factor) # check if size of the zoom can be reduced
if ACFplot:
fig, (ax1, ax2, ax3) = plt.subplots(1, 3)
ax1.imshow(ACF_I[int(ACF_I.shape[0] / 2), :, :])
ax2.imshow(ACF_I[:, int(ACF_I.shape[1] / 2), :])
ax3.imshow(ACF_I[:, :, int(ACF_I.shape[2] / 2)])
# envelope of normalized ACF center
env_points = envelope(to01andbinary(ACF_I, ACF_threshold))
# ellipsoid fit
center, evecs, radii, v = ef.ellipsoid_fit(env_points)
# compute Degree of Anisotropy
DA = np.max(radii) / np.min(radii)
# Ellipsoid eigenvalues
evals = 1 / (radii ** 2)
# Symmetric ellipsoid tensor components
fabric_tens = np.matmul(evecs, np.matmul((evals * np.identity(3)), np.transpose(evecs)))
fabric_comp = fabric_tens[[0, 1, 2, 0, 1, 0], [0, 1, 2, 1, 2, 2]]
return evecs, radii, evals, fabric_comp, DA