-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEM.py
1437 lines (1104 loc) · 61.3 KB
/
EM.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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# =============================================================================
# FILE: EM.py
# DESCRIPTION: A Python file containing classes for image segmentation and
# evaluation using Expectation-Maximization Algorithm.
# AUTHOR: [Abdelrahman Usama Habib]
# DATE: [11/19/2023]
# =============================================================================
# -----------------------------------------------------------------------------
# TABLE OF CONTENTS
# -----------------------------------------------------------------------------
# 1. Import Statements
# 2. FileManager Class
# 3. NiftiManager Class
# 4. Evaluate Class
# 5. ElastixTransformix Class
# 6. BrainAtlasManager Class
# 7. Plot Class
# 8. EM Class
# -----------------------------------------------------------------------------
# 1. Import Statements
import nibabel as nib
import matplotlib.pyplot as plt
import os
import numpy as np
from sklearn.cluster import KMeans
from scipy.stats import multivariate_normal
from tqdm import tqdm
import subprocess
from glob import glob
import math
from tqdm import tqdm
import pprint
import pandas as pd
from loguru import logger
import pandas as pd
# 2. FileManager Class
class FileManager:
'''
A class for managing file-related operations, such as checking file existence, creating directories,
pretty-printing objects, and replacing text in files.
Methods:
- __init__(self) -> None: Initialize a PrettyPrinter for clear object printing.
- check_file_existence(self, file, description): Check if a file exists; raise a ValueError if not.
- create_directory_if_not_exists(self, path): Create a directory if it does not exist.
- pprint_objects(self, *arg): Print large and indented objects clearly.
- replace_text_in_file(self, file_path, search_text, replacement_text): Replace text in a text file.
Attributes:
- pp (pprint.PrettyPrinter): PrettyPrinter object for clear object printing.
'''
def __init__(self) -> None:
# Initialize a PrettyPrinter for clear object printing
self.pp = pprint.PrettyPrinter(indent=4)
def check_file_existence(self, file, description):
'''
Check if a file exists; raise a ValueError if not.
Args:
file ('str'): File path.
description ('str'): Description of the file for the error message.
'''
if file is None:
raise ValueError(f"Please check if the {description} file passed exists in the specified directory")
def create_directory_if_not_exists(self, path):
'''
Create a directory if it does not exist.
Args:
path ('str'): Directory path.
'''
if not os.path.exists(path):
os.makedirs(path)
def pprint_objects(self, *arg):
'''
Print large and indented objects clearly.
Args:
*arg: Variable number of arguments to print.
'''
self.pp.pprint(arg)
def replace_text_in_file(self, file_path, search_text, replacement_text):
'''
Replace text in a text file.
Args:
file_path ('str'): Path to the text file.
search_text ('str'): Text to search for in the file.
replacement_text ('str'): Text to replace the searched text with.
'''
try:
# Read the file
with open(file_path, 'r') as file:
content = file.read()
# Replace the search_text with replacement_text
modified_content = content.replace(search_text, replacement_text)
# Write the modified content back to the file
with open(file_path, 'w') as file:
file.write(modified_content)
# print(f"Text replaced in {file_path} and saved.")
except FileNotFoundError:
print(f"File not found: {file_path}")
# except Exception as e:
# print(f"An error occurred: {e}")
# 3. NiftiManager Class
class NiftiManager:
"""
Manager class for handling NIfTI files, including loading, visualization, and export.
Methods:
- __init__(self) -> None: Initializes the NiftiManager.
- load_nifti(self, file_path) -> Tuple[np.array, nibabel.Nifti1Image]:
Load the NIfTI image and access the image data as a Numpy array.
- show_nifti(self, file_data, title, slice=25) -> None:
Display a single slice from the NIfTI volume.
- show_label_seg_nifti(self, label, seg, subject_id, slice=25) -> None:
Display both segmentation and ground truth labels for a specific slice.
- show_mean_volumes(self, mean_csf, mean_wm, mean_gm, slices=[128], export=False, filename=None) -> None:
Display mean volumes for CSF, WM, and GM for specified slices.
- show_combined_mean_volumes(self, mean_csf, mean_wm, mean_gm, slice_to_display=128, export=False, filename=None) -> None:
Display combined averaged volumes for CSF, WM, and GM at a specific slice.
- min_max_normalization(self, image, max_value) -> np.array:
Perform min-max normalization on an image.
- export_nifti(self, volume, export_path, nii_image=None) -> None:
Export NIfTI volume to a given path.
Attributes:
None
"""
def __init__(self) -> None:
pass
def load_nifti(self, file_path):
'''
Load the NIfTI image and access the image data as a Numpy array.
Args:
file_path ('str'): Path to the NIfTI file.
Returns:
data_array ('np.array'): Numpy array representing the image data.
nii_image: Loaded NIfTI image object.
'''
nii_image = nib.load(file_path)
data_array = nii_image.get_fdata()
return data_array, nii_image
def show_nifti(self, file_data, title, slice=25):
'''
Display a single slice from the NIfTI volume.
Args:
file_data ('np.array'): Numpy array representing the image data.
title ('str'): Title for the plot.
slice ('int'): Slice index to display.
'''
plt.imshow(file_data[:, :, slice], cmap='gray')
plt.title(title)
# plt.colorbar()
plt.axis('off')
plt.show()
def show_label_seg_nifti(self, label, seg, subject_id, slice=25):
'''
Display both segmentation and ground truth labels for a specific slice.
Args:
label ('np.array'): Ground truth label image.
seg ('np.array'): Segmentation label image.
subject_id ('str'): Identifier for the subject or image.
slice ('int'): Slice index to display.
Returns:
None
'''
plt.figure(figsize=(20, 7))
plt.subplot(1, 2, 1)
plt.imshow(label[:, :, slice], cmap='gray')
plt.title(f'Label Image (Subject ID={subject_id})')
# plt.colorbar()
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(seg[:, :, slice], cmap='gray')
plt.title(f'Segmentation Image (Subject ID={subject_id})')
# plt.colorbar()
plt.axis('off')
plt.show()
def show_mean_volumes(self, mean_csf, mean_wm, mean_gm, slices=[128], export=False, filename=None):
'''
Display mean volumes for CSF, WM, and GM for specified slices.
Args:
mean_csf ('np.array'): Mean volume for CSF.
mean_wm ('np.array'): Mean volume for WM.
mean_gm ('np.array'): Mean volume for GM.
slices ('list'): List of slice indices to display.
export ('bool'): Whether to export the plot to a file.
filename ('str'): Filename for the exported plot.
Returns:
None
'''
num_slices = len(slices)
plt.figure(figsize=(20, 7 * num_slices))
for i, slice in enumerate(slices):
plt.subplot(num_slices, 3, i * 3 + 1)
plt.imshow(mean_csf[:, :, slice], cmap='gray')
plt.title(f'Average CSF Volume - Slice {slice}')
# plt.colorbar()
plt.axis('off')
plt.subplot(num_slices, 3, i * 3 + 2)
plt.imshow(mean_wm[:, :, slice], cmap='gray')
plt.title(f'Average WM Volume - Slice {slice}')
# plt.colorbar()
plt.axis('off')
plt.subplot(num_slices, 3, i * 3 + 3)
plt.imshow(mean_gm[:, :, slice], cmap='gray')
plt.title(f'Average GM Volume - Slice {slice}')
# plt.colorbar()
plt.axis('off')
if export and filename:
plt.savefig(filename)
plt.show()
def show_combined_mean_volumes(self, mean_csf, mean_wm, mean_gm, slice_to_display=128, export=False, filename=None):
'''
Display combined averaged volumes for CSF, WM, and GM at a specific slice.
Args:
mean_csf ('np.array'): Mean volume for CSF.
mean_wm ('np.array'): Mean volume for WM.
mean_gm ('np.array'): Mean volume for GM.
slice_to_display ('int'): Slice index to display.
export ('bool'): Whether to export the plot to a file.
filename ('str'): Filename for the exported plot.
Returns:
None
'''
# Stack the mean volumes along the fourth axis to create a single 4D array
combined_mean_volumes = np.stack((mean_csf, mean_wm, mean_gm), axis=3)
# Choose the channel you want to display (0 for CSF, 1 for WM, 2 for GM)
# channel_to_display = 0 # Adjust as needed
# Display the selected channel
plt.imshow(combined_mean_volumes[:, :, :, :][:, :, slice_to_display]) # [:, :, :, channel_to_display]
plt.axis('off') # Turn off axis labels
plt.title(f'Combined Averaged Volumes at Slice {slice_to_display}') # Add a title
if export and filename:
plt.savefig(filename)
plt.show()
def min_max_normalization(self, image, max_value):
'''
Perform min-max normalization on an image.
Args:
image ('np.array'): Input image to normalize.
max_value ('float'): Maximum value for normalization.
Returns:
normalized_image ('np.array'): Min-max normalized image.
'''
# Ensure the image is a NumPy array for efficient calculations
image = np.array(image)
# Calculate the minimum and maximum pixel values
min_value = np.min(image)
max_actual = np.max(image)
# Perform min-max normalization
normalized_image = (image - min_value) / (max_actual - min_value) * max_value
return normalized_image
def export_nifti(self, volume, export_path, nii_image=None):
'''
Export NIfTI volume to a given path.
Args:
volume ('np.array'): Numpy array representing the volume.
export_path ('str'): Path to export the NIfTI file.
nii_image ('nibabel'): Loaded NIfTI image object.
Returns:
None
'''
# Create a NIfTI image from the NumPy array
# np.eye(4): Identity affine transformation matrix, it essentially assumes that the images are in the same orientation and position
# as the original images
affine = nii_image.affine if nii_image else np.eye(4)
img = nib.Nifti1Image(volume, affine)
# Save the NIfTI image
nib.save(img, str(export_path))
# 4. Evaluate Class
class Evaluate:
"""
Class for evaluating segmentation performance using Dice coefficients.
Methods:
- __init__(self) -> None: Initializes the Evaluate class.
- calc_dice_coefficient(self, mask1, mask2) -> float:
Calculate the Dice coefficient between two binary masks.
- evaluate_dice_volumes(self, volume1, volume2, labels=None) -> dict:
Evaluate Dice coefficients for different tissue types.
Attributes:
None
"""
def __init__(self) -> None:
pass
def calc_dice_coefficient(self, mask1, mask2):
'''
Calculate the Dice coefficient between two binary masks.
Args:
mask1 ('np.array'): Binary mask.
mask2 ('np.array'): Binary mask.
Returns:
dice ('float'): Dice coefficient.
'''
# Ensure the masks have the same shape
if mask1.shape != mask2.shape:
raise ValueError("Input masks must have the same shape.")
# Compute the intersection and union of the masks
intersection = np.sum(mask1 * mask2)
union = np.sum(mask1) + np.sum(mask2)
# Calculate the Dice coefficient
dice = (2.0 * intersection) / (union + 1e-8) # Add a small epsilon to avoid division by zero
return dice
def evaluate_dice_volumes(self, volume1, volume2, labels=None):
'''
Evaluate Dice coefficients for different tissue types.
Args:
volume1 ('np.array'): Segmentation volume.
volume2 ('np.array'): Ground truth segmentation volume.
labels ('dict'): Dictionary mapping tissue types to labels.
Returns:
dice_coefficients ('dict'): Dictionary of Dice coefficients for each tissue type.
'''
if labels is None or not isinstance(labels, dict):
raise ValueError("The 'labels' parameter must be a dictionary mapping tissue types to labels.")
# Ensure the masks have the same shape
if volume1.shape != volume2.shape:
raise ValueError("Input masks must have the same shape.")
if labels is None:
raise ValueError("Missing labels argument.")
dice_coefficients = {}
for tissue_label in ['WM', 'GM', 'CSF']:
mask1 = volume1 == labels[tissue_label]
mask2 = volume2 == labels[tissue_label]
dice_coefficient = self.calc_dice_coefficient(mask1, mask2)
dice_coefficients[tissue_label] = round(dice_coefficient, 6)
# print(f"{tissue_label} DICE: {dice_coefficient}")
return dice_coefficients
# 5. ElastixTransformix Class
class ElastixTransformix:
"""
Class for performing image registration using elastix and label propagation using transformix.
Methods:
- __init__(self) -> None: Initializes the ElastixTransformix class.
- execute_cmd(self, command) -> str:
Execute a command and check for success.
- register_elastix(self, fixed_path, moving_path, reg_params, create_dir_callback, execute_cmd_callback, fMask=None) -> None:
Perform image registration using elastix.
- label_propagation_transformix(self, fixed_path, moving_path, input_label, transform_path, replace_text_in_file_callback, create_dir_callback, execute_cmd_callback) -> None:
Apply label propagation using transformix.
Attributes:
None
"""
def __init__(self) -> None:
pass
def excute_cmd(self, command):
'''
Execute a command and check for success.
Args:
command ('str'): Command to execute.
Returns:
result ('str'): Output of the command if successful.
'''
# excute the command
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True)
# Check the return code to see if the command was successful
if result.returncode == 0:
# print("Command executed successfully.")
# print("Output:")
return result.stdout
else:
print(f"Command failed with an error: {command}")
print(result.stderr)
return result.stderr
# Perform registration and label propagation
def register_elastix(self,
fixed_path,
moving_path,
reg_params,
create_dir_callback,
excute_cmd_callback,
fMask = None):
'''
Perform image registration using elastix.
Args:
fixed_path ('str'): Path to the fixed image.
moving_path ('str'): Path to the moving image.
reg_params ('str'): Registration parameters for elastix.
create_dir_callback ('function'): Callback function to create directories.
excute_cmd_callback ('function'): Callback function to execute commands.
fMask ('str'): Optional path to a mask file.
Returns:
None
'''
# Get the names of the fixed and moving images for the output directory, names without the file extensions
reg_fixed_name = fixed_path.replace("\\", "/").split("/")[-1].split(".")[0] # \\
reg_moving_name = moving_path.replace("\\", "/").split("/")[-1].split(".")[0]
# create output dir
output_dir = f'output/images/output_{reg_fixed_name}/{reg_moving_name}'
create_dir_callback(output_dir)
# create elastix command line
command_line = f'elastix -f "{fixed_path}" -m "{moving_path}" {reg_params} -out "{output_dir}"' if not fMask else \
f'elastix -f "{fixed_path}" -m "{moving_path}" -fMask {fMask} {reg_params} -out "{output_dir}"'
# print(command_line)
# call elastix command
excute_cmd_callback(command_line)
def label_propagation_transformix(
self,
fixed_path,
moving_path,
input_label,
transform_path,
replace_text_in_file_callback,
create_dir_callback,
excute_cmd_callback):
'''
Apply label propagation using transformix.
Args:
fixed_path ('str'): Path to the fixed image.
moving_path ('str'): Path to the moving image.
input_label ('str'): Path to the input label image.
transform_path ('str'): Path to the transformation parameters.
replace_text_in_file_callback ('function'): Callback function to replace text in a file.
create_dir_callback ('function'): Callback function to create directories.
excute_cmd_callback ('function'): Callback function to execute commands.
Returns:
None
'''
replace_text_in_file_callback(
transform_path,
search_text = '(FinalBSplineInterpolationOrder 3)',
replacement_text = '(FinalBSplineInterpolationOrder 0)')
# Get the names of the fixed and moving images for the output directory, names without the file extensions
reg_fixed_name = fixed_path.replace("\\", "/").split("/")[-1].split(".")[0]
# reg_moving_name = os.path.join(moving_path.replace("\\", "/").split("/")[0], moving_path.replace("\\", "/").split("/")[-1].split(".")[0])
# issue here with the files dir -> creates two dirs (output/labels/output_IBSR_11/..\IBSR_01_seg)
reg_moving_name = os.path.join(moving_path.replace("\\", "/").split("/")[-1].split(".")[0])
# create an output directory for the labels
output_dir = f'output/labels/output_{reg_fixed_name}/{reg_moving_name}' # rem _float64
# creates the output directory
create_dir_callback(output_dir)
# create transformix command line
command_line = f'transformix -in "{input_label}" -tp "{transform_path}" -out "{output_dir}"'
# print(command_line)
# run transformix on all combinations
excute_cmd_callback(command_line)
# 6. BrainAtlasManager Class
class BrainAtlasManager:
"""
Class for managing brain atlases and performing segmentation using tissue models and label propagation.
Methods:
- __init__(self) -> None: Initializes the BrainAtlasManager class.
- segment_using_tissue_models(self, image, label, tissue_map_csv) -> Tuple[np.array, np.array]:
Segmentation using intensity information and tissue models.
- segment_using_tissue_atlas(self, image, label, *atlases) -> Tuple[np.array, np.array]:
Segmentation using position information and atlases.
- segment_using_tissue_models_and_atlas(self, image, label, tissue_map_csv, *atlases) -> Tuple[np.array, np.array]:
Segmentation using both intensity and position information.
Attributes:
None
"""
def __init__(self) -> None:
pass
def segment_using_tissue_models(self, image, label, tissue_map_csv):
'''
Task (1.1) Tissue models: segmentation using just intensity information.
Args:
image ('np.array'):
A normalized [0, 255] and skull stripped intensity volume for the brain in the form of a numpy array.
This is the required volume to be segmented.
label ('np.array'):
A nifti volume for the intensity image. Pixels labeled as 0 will be treated as background.
tissue_map_csv ('Path'):
A csf file path that contains the tissue maps probabilities. The file should contain three columns,
first column for CSF, then WM, then GM.
Returns:
The segmented volume in the same shape of the passed intensity volume. The output is given in labels for
the segmentation, where label 0 is for background, 1 for CSF, 2 for WM, and 3 for GM. Those labels changes
based on the tissue map columns orders. The final atlas probability has a shape of (N, K), where N is the
number of samples, and K is the number of clusters.
segmentation_result ('np.array'):
The segmentation label image in the form of numpy array.
tissue_map_array ('np.array'):
An array that represents the final atlas probabilities.
'''
# read the tissues moodels
tissue_map_df = pd.read_csv(tissue_map_csv, header=None)
tissue_map_array = tissue_map_df.values
# binary mask
binary_mask = np.where(label == 0, 0, 1)
# map background pixels above a threshold to WM (label 2)
threshold = 100
bg_mask = np.arange(len(tissue_map_array)) > threshold
tissue_map_array[bg_mask, 1] = 2
# flatten the image and select only tissues within the mask
registered_volume_test = image[binary_mask == 1].flatten()
# using registered_volume_test as an index to extract specific rows from tissue_map_array
tissue_map_array = tissue_map_array[registered_volume_test, :]
# obtain the argmax to know to which cluster each row (histogram bin - 0:255) falls into
tissue_map_array_argmax = np.argmax(tissue_map_array, axis=1) + 1
# Reshape the atlases_argmax array to match the shape of the original image
reshaped_atlases_argmax = tissue_map_array_argmax.reshape(image[binary_mask == 1].shape)
# Create an empty segmentation result with the same shape as the original image
segmentation_result = np.zeros_like(image)
# Set the background (ignored) pixels to label 0
segmentation_result[binary_mask == 0] = 0
# set the segmented values where indexes falls to be true
segmentation_result[binary_mask == 1] = reshaped_atlases_argmax
return segmentation_result, tissue_map_array
def segment_using_tissue_atlas(self, image, label, *atlases):
'''
Task (1.2) Label propagation: segmentation using just position information using atlases
Args:
image ('np.array'):
A normalized [0, 255] and skull stripped intensity volume for the brain in the form of a numpy array.
This is the required volume to be segmented.
label ('np.array'):
A nifti volume for the intensity image. Pixels labeled as 0 will be treated as background.
atlases ('np.arrays'):
atlases nifti data files for CSF, WM, and GM as in order.
Returns:
The segmented volume in the same shape of the passed intensity volume. The output is given in labels for
the segmentation, where label 0 is for background, 1 for CSF, 2 for WM, and 3 for GM. Those labels changes
based on the tissue map columns orders. The final atlas probability has a shape of (N, K), where N is the
number of samples, and K is the number of clusters.
segmentation_result ('np.array'):
The segmentation label image in the form of numpy array.
concatenated_atlas ('np.array'):
An array that represents the final atlas probabilities.
'''
# binary mask
binary_mask = np.where(label == 0, 0, 1)
# get the atlases
atlas_csf = atlases[0][binary_mask == 1].flatten()
atlas_wm = atlases[1][binary_mask == 1].flatten()
atlas_gm = atlases[2][binary_mask == 1].flatten()
# concatenate the flatenned atlases to form a NxK shaped array of arrays
concatenated_atlas = np.column_stack((atlas_csf, atlas_wm, atlas_gm))
# get the argmax for each row to find which cluster does each sample refers to
atlases_argmax = np.argmax(concatenated_atlas, axis=1) + 1
# Create an empty segmentation result with the same shape as the original image
segmented_image = np.zeros_like(image)
# Reshape the atlases_argmax array to match the shape of the original image
reshaped_atlases_argmax = atlases_argmax.reshape(image[binary_mask == 1].shape)
# Set the background (ignored) pixels to label 0
segmented_image[binary_mask == 0] = 0
# set the segmented values where indexes falls to be true
segmented_image[binary_mask == 1] = reshaped_atlases_argmax
return segmented_image, concatenated_atlas
def segment_using_tissue_models_and_atlas(self, image, label, tissue_map_csv, *atlases):
'''(1.3) Tissue models & label propagation: multiplying both results: segmentation using intensity & position information
Args:
image ('np.array'):
A normalized [0, 255] and skull stripped intensity volume for the brain in the form of a numpy array.
This is the required volume to be segmented.
label ('np.array'):
A nifti volume for the intensity image. Pixels labeled as 0 will be treated as background.
tissue_map_csv ('Path'):
A csf file path that contains the tissue maps probabilities. The file should contain three columns,
first column for CSF, then WM, then GM.
atlases ('np.arrays'):
atlases nifti data files for CSF, WM, and GM as in order.
Returns:
The segmented volume in the same shape of the passed intensity volume. The output is given in labels for
the segmentation, where label 0 is for background, 1 for CSF, 2 for WM, and 3 for GM. Those labels changes
based on the tissue map columns orders. The final atlas probability has a shape of (N, K), where N is the
number of samples, and K is the number of clusters.
segmentation_result ('np.array'):
The segmentation label image in the form of numpy array.
posteriors ('np.array'):
An array that represents the final atlas probabilities.
'''
# read the tissues moodels
tissue_map_df = pd.read_csv(tissue_map_csv, header=None)
tissue_map_array = tissue_map_df.values
# map background pixels above a threshold to WM (label 2)
threshold = 100
bg_mask = np.arange(len(tissue_map_array)) > threshold
tissue_map_array[bg_mask, 1] = 2
# binary mask
binary_mask = np.where(label == 0, 0, 1)
# get the atlases
atlas_csf = atlases[0][binary_mask == 1].flatten()
atlas_wm = atlases[1][binary_mask == 1].flatten()
atlas_gm = atlases[2][binary_mask == 1].flatten()
# concatenate the flatenned atlases to form a NxK shaped array of arrays
concatenated_atlas = np.column_stack((atlas_csf, atlas_wm, atlas_gm))
# Perform Bayesian segmentation
registered_volume_test = image[binary_mask == 1].flatten()
# using registered_volume_test as an index to extract specific rows from tissue_map_array
tissue_map_array = tissue_map_array[registered_volume_test, :]
# multiply the probabilities
posteriors = tissue_map_array * concatenated_atlas
# ger the argmax for each sample to know for which cluster does it belongs, +1 to avoid 0 value
posteriors_argmax = np.argmax(posteriors, axis=1) + 1
# Create an empty segmentation result with the same shape as the original image
segmented_image = np.zeros_like(image)
# Reshape the atlases_argmax array to match the shape of the original image
reshaped_atlases_argmax = posteriors_argmax.reshape(image[binary_mask == 1].shape)
# Set the background (ignored) pixels to label 0
segmented_image[binary_mask == 0] = 0
# set the segmented values where indexes falls to be true
segmented_image[binary_mask == 1] = reshaped_atlases_argmax
return segmented_image, posteriors
# 7. Plot Class
class Plot:
"""
Class for generating and displaying box plots.
Methods:
- __init__(self) -> None: Initializes the Plot class.
- plot_boxplot_per_tissue(self, WM_values, GM_values, CSF_values, config) -> None:
Plots a box plot for each tissue type based on the provided data.
- plot_boxplot_per_patient(self, values, subjects, config) -> None:
Plots a box plot for each subject separately.
Attributes:
None
"""
def __init__(self) -> None:
pass
def plot_boxplot_per_tissue(self, WM_values, GM_values, CSF_values, config):
"""
Plots a box plot for each tissue type based on the provided data.
Args:
WM_values ('list'): List of white matter values for each patient.
GM_values ('list'): List of gray matter values for each patient.
CSF_values ('list'): List of cerebrospinal fluid values for each patient.
config ('str'): Configuration information to include in the plot title.
Returns:
None. The function generates and displays the box plot.
"""
# Calculate quartiles and IQR for each tissue type
WM_q1, WM_q2, WM_q3 = np.percentile(WM_values, [25, 50, 75])
WM_iqr = WM_q3 - WM_q1
GM_q1, GM_q2, GM_q3 = np.percentile(GM_values, [25, 50, 75])
GM_iqr = GM_q3 - GM_q1
CSF_q1, CSF_q2, CSF_q3 = np.percentile(CSF_values, [25, 50, 75])
CSF_iqr = CSF_q3 - CSF_q1
# Combine the data for plotting
data = [WM_values, GM_values, CSF_values]
# Create a box plot
fig, ax = plt.subplots()
ax.boxplot(data, labels=['WM', 'GM', 'CSF'])
# Set labels and title
ax.set_ylabel('Values')
ax.set_title(f'({config}) configurations')
# Show the plot
plt.show()
def plot_boxplot_per_patient(self, values, subjects, config):
'''
Plots a boxplot for each subject separately.
Args:
values ('list'): A 1D list Contains the values to be plotted.
subjects ('list'): A 1D list, same length as 'values' for the x-axis of the plot.
Returns:
None. The function generates and displays the box plot.
'''
# Convert WM_values to a list of lists
data = [[value] for value in values]
# Plot box plots for each patient
fig, axs = plt.subplots(1, 1, figsize=(10, 12), sharex=True)
axs.boxplot(data, labels=subjects)
axs.set_title('WM Values ')
axs.set_ylabel('WM Values')
axs.set_title(f'Box Plot for Each Patient using ({config}) Configurations')
plt.xlabel('Patient ID')
plt.show()
# 8. EM Class
class EM:
"""
Implementation of the Expectation-Maximization (EM) algorithm for image segmentation.
Methods:
- __init__(K=3, params_init_type='random', modality='multi', verbose=True): Initializes the EM algorithm.
- initialize_for_fit(labels_gt_file, t1_path, t2_path, tissue_model_csv_dir, include_atlas, *atlases): Initializes variables for fitting.
- skull_stripping(image, label): Performs skull stripping and returns the volume with labeled tissues only.
- get_tissue_data(labels_gt_file, t1_path, t2_path): Removes black background from skull-stripped volume.
- initialize_parameters(data, tissue_model_csv_dir, *atlases): Initializes model parameters.
- multivariate_gaussian_probability(x, mean_k, cov_k, regularization=1e-4): Computes multivariate Gaussian probability.
- expectation(): Expectation step of the EM algorithm.
- maximization(w_ik, tissue_data): Maximization step of the EM algorithm.
- log_likelihood(alpha, clusters_means, clusters_covar, multivariate_gaussian_probability_callback): Computes log-likelihood.
- generate_segmentation(posteriors, gt_binary): Generates segmentation based on posterior probabilities.
- correct_pred_labels(segmentation_result, gt_binary): Corrects predicted labels based on prior knowledge.
- fit(n_iterations, labels_gt_file, t1_path, t2_path=None, correct_labels=True, tissue_model_csv_dir=None, atlas_csf=None, atlas_wm=None, atlas_gm=None, include_atlas=False): Fits the EM algorithm and segments the volume.
Attributes:
- K ('int'): Number of clusters/components.
- params_init_type ('str'): Type of initialization for parameters ('kmeans', 'random', 'tissue_models', 'atlas', 'tissue_models_atlas').
- modality ('str'): Modality of the input data ('multi' or 'single').
- verbose ('bool'): Whether to print verbose output.
- labels_gt_file ('str'): Ground truth labels file path.
- t1_path ('str'): Path to the T1-weighted image.
- t2_path ('str'): Path to the T2-weighted image.
- sum_tolerance ('float'): Tolerance for sum conditions.
- convergence_tolerance ('int'): Tolerance for convergence check.
- seed ('int'): Seed for random initialization.
- NM ('NiftiManager'): Nifti file manager class.
- FM ('FileManager'): File manager class.
- BrainAtlas ('BrainAtlasManager'): Brain atlas manager.
- tissue_data ('np.array'): 2D array of voxel intensities for selected tissues.
- gt_binary ('np.array'): Binary mask indicating selected tissues.
- img_shape ('tuple'): Shape of the T1-weighted image volume.
- n_samples ('int'): Number of samples.
- n_features ('int'): Number of features.
- clusters_means ('np.array'): Cluster means.
- clusters_covar ('np.array'): Cluster covariance matrices.
- alpha_k ('np.array'): Prior probabilities.
- posteriors ('np.array'): Normalized posterior probabilities.
- pred_labels ('np.array'): Predicted labels.
- loglikelihood ('list'): List to store log-likelihood values.
- atlas_prob ('np.array'): Atlas probabilities.
- include_atlas ('bool'): Whether to include atlas information in the initialization.
"""
def __init__(self, K=3, params_init_type='random', modality='multi', verbose=True):
'''
Initialize the Expectation-Maximization (EM) algorithm for image segmentation.
Args:
K ('int'): Number of clusters/components.
params_init_type ('str'): Type of initialization for parameters ('kmeans', 'random', 'tissue_models', 'atlas', 'tissue_models_atlas').
modality ('str'): Modality of the input data ('multi' or 'single').
verbose (bool): Whether to print verbose output.
Returns:
None
'''
self.K = K
self.params_init_type = params_init_type
self.modality = modality
self.verbose = verbose
self.labels_gt_file, self.t1_path, self.t2_path = None, None, None
self.labels_nifti, self.t1_volume = None, None
self.sum_tolerance = 0.15
self.convergence_tolerance = 200
self.seed = 42
# Setting a seed
np.random.seed(self.seed)
# Helper classes
self.NM = NiftiManager()
self.FM = FileManager()
self.BrainAtlas = BrainAtlasManager()
self.tissue_data, self.gt_binary, self.img_shape = None, None, None # (N, d) for tissue data
self.n_samples = None # N samples
self.n_features = None # d = number of features (dimension),
# based on the number of modalities we pass
# create parameters objects
self.clusters_means = None # (K, d)
self.clusters_covar = None # (K, d, d)
self.alpha_k = None # prior probabilities, (K,)
self.posteriors = None # (N, K)
self.pred_labels = None # (N,)
self.loglikelihood = [-np.inf]
# atlas parameters
self.atlas_prob = None # (N, K)
self.include_atlas = None
def initialize_for_fit(self, labels_gt_file, t1_path, t2_path, tissue_model_csv_dir, include_atlas, *atlases):
'''
Initialize variables only when fitting the algorithm.
Args:
labels_gt_file ('path'): Ground truth labels file path.
t1_path ('str'): Path to the T1-weighted image.
t2_path ('str'): Path to the T2-weighted image.
tissue_model_csv_dir ('str'): Directory containing tissue model CSV files.
include_atlas ('bool'): Whether to include atlas information in the initialization.
*atlases: Variable number of atlas objects.
Returns:
None
'''
# get the atlases
atlas_csf = atlases[0]
atlas_wm = atlases[1]
atlas_gm = atlases[2]
# initializing skull stripping variables
self.labels_gt_file, self.t1_path, self.t2_path \
= labels_gt_file, t1_path, t2_path
# Removing the background for the data
self.tissue_data, self.gt_binary, self.img_shape \
= self.get_tissue_data(
self.labels_gt_file,
t1_path=self.t1_path,
t2_path=self.t2_path
) # (N, d) for tissue data
self.n_samples = self.tissue_data.shape[0] # N samples
self.n_features = self.tissue_data.shape[1] # number of features 2 or 1 (dimension), based on the number of modalities we pass
self.clusters_means = np.zeros((self.K, self.n_features)) # (K, d)
self.clusters_covar = np.zeros(((self.K, self.n_features, self.n_features))) # (K, d, d)
self.alpha_k = np.ones(self.K) # prior probabilities, (K,)
self.posteriors = np.zeros((self.n_samples, self.K), dtype=np.float64) # (N, K)
self.pred_labels = np.zeros((self.n_samples,)) # (N,)
self.atlas_prob = np.zeros((self.n_samples, self.K), dtype=np.float64) # atlas probabilities, (N, K)
self.include_atlas = include_atlas
if self.modality not in ['single', 'multi']:
raise ValueError('Wronge modality type passed. Only supports "single" or "multi" options.')
if tissue_model_csv_dir is None and self.params_init_type == 'tissue_models':
raise ValueError('Missing tissue_model_csv_dir argument.')
if (atlas_csf is None or atlas_wm is None or atlas_gm is None) and self.params_init_type == 'atlas':
raise ValueError('Missing atlases argument.')
if ((atlas_csf is None or atlas_wm is None or atlas_gm is None) or (tissue_model_csv_dir is None)) and self.params_init_type == 'tissue_models_atlas':