-
Notifications
You must be signed in to change notification settings - Fork 1
/
visualization.py
473 lines (373 loc) · 14.6 KB
/
visualization.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
# -*- coding: utf-8 -*-
"""Visualization.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1g1ON_LDVx0PvXht7nDRTpi0JFKqqpADf
#Connecting Google Drive
"""
from google.colab import drive
import os
drive.mount('/content/drive/',force_remount=True)
cd /content
"""## Installing required Libraries"""
!pip install SimpleITK
#@title Default title text
import SimpleITK as sitk
from tqdm import tqdm
import numpy as np
import os
import tables
import numpy as np
import nibabel as nib
from tqdm import tqdm
from glob import glob
"""# Reading the Brain Volume
* Use the following code line to read the Flair Sequence
```
# modalities_dir = [ flair[0] ]
```
* Use the following code line to read the T1 Sequence
```
# modalities_dir = [ t1[0] ]
```
* Use the following code line to read the T1ce Sequence
```
# modalities_dir = [ t1ce[0] ]
```
* Use the following code line to read the T2 Sequence
```
# modalities_dir = [ t2[0] ]
```
"""
import os
import numpy as np
import nibabel as nib
from glob import glob
from tensorflow.keras.models import load_model
def read_brain(brain_dir):
brain_dir = os.path.normpath(brain_dir)
flair = glob( os.path.join(brain_dir, '*_flair*.nii.gz'))
t1 = glob( os.path.join(brain_dir, '*_t1*.nii.gz'))
t1ce = glob( os.path.join(brain_dir, '*_ce*.nii.gz'))
t2 = glob( os.path.join(brain_dir, '*_t2*.nii.gz'))
#gt = glob( os.path.join(brain_dir, '*_seg*.nii.gz'))
modalities_dir = [t2[0]]
all_modalities = []
for modality in modalities_dir:
print(modality)
nifti_file = nib.load(modality)
brain_numpy = np.asarray(nifti_file.dataobj)
all_modalities.append(brain_numpy)
# all modalities have the same affine, so we take one of them (the last one in this case),
# affine is just saved for preparing the predicted nii.gz file in the future.
all_modalities = np.array(all_modalities)
all_modalities = np.rint(all_modalities).astype(np.int16)
# to fit keras channel last model
all_modalities = np.transpose(all_modalities)
return all_modalities
if __name__ == '__main__':
val_data_dir = '/content/drive/MyDrive/Visualize/*'
view = 'axial'
all_brains_dir = glob(val_data_dir)
all_brains_dir.sort()
if view == 'axial':
view_axes = (0, 1, 2, 3)
elif view == 'sagittal':
view_axes = (2, 1, 0, 3)
elif view == 'coronal':
view_axes = (1, 2, 0, 3)
for brain_dir in all_brains_dir:
if os.path.isdir(brain_dir):
print("Volume ID: ", os.path.basename(brain_dir))
all_modalities = read_brain(brain_dir)
all_modalities = all_modalities.transpose(view_axes)
"""# Reading the Ground Truth and Prediction
* Use the following code line to read the ground truth annotation
```
# modalities_dir = [ gt[0] ]
```
* Use the following code line to read the Prediction
```
# modalities_dir = [ pred[0] ]
```
"""
import os
import numpy as np
import nibabel as nib
from glob import glob
from tensorflow.keras.models import load_model
def read_brain_pred(brain_dir):
brain_dir = os.path.normpath(brain_dir)
gt = glob( os.path.join(brain_dir, '*_seg*.nii.gz'))
pred = glob( os.path.join(brain_dir, '*_pred*.nii.gz'))
#modalities_dir = [flair[0], t1[0], t1ce[0], t2[0], gt[0]]
#modalities_dir = [pred[0]]
modalities_dir = [gt[0]]
prediction = []
for i in modalities_dir:
print(i)
nifti_file = nib.load(i)
brain = np.asarray(nifti_file.dataobj)
prediction.append(brain)
# all modalities have the same affine, so we take one of them (the last one in this case),
# affine is just saved for preparing the predicted nii.gz file in the future.
prediction = np.array(prediction)
prediction = np.rint(prediction).astype(np.int16)
prediction = np.transpose(prediction)
return prediction
if __name__ == '__main__':
val_data_dir = '/content/drive/MyDrive/Visualize/*'
view = 'axial'
all_brains_dir = glob(val_data_dir)
all_brains_dir.sort()
if view == 'axial':
view_axes = (0, 1, 2, 3)
elif view == 'sagittal':
view_axes = (0, 2, 1, 3)
elif view == 'coronal':
view_axes = (1, 0, 2, 3)
else:
ValueError('unknown input view => {}'.format(view))
for brain_dir in all_brains_dir:
if os.path.isdir(brain_dir):
print("Volume ID: ", os.path.basename(brain_dir))
prediction = read_brain_pred(brain_dir)
prediction = prediction.transpose(view_axes)
"""# Returning the overlapped region and 3D Brain MRI
* Use the following code line for overlapping the segmented region on to the brain MRI
```
# return img_masked
```
* Use the following code line to output 3d brain MRI
```
# return img_color
```
"""
from skimage import color, io, img_as_float
import numpy as np
import matplotlib.pyplot as plt
import numpy as np
alpha = 1.0
def show_segmented_image(brainMRI,Predicted):
img = img_as_float(brainMRI)
img_mask = Predicted
#img_mask = GroundTruth
img = img / np.max(img)
rows, cols = img.shape
# Construct a colour image to superimpose
sliced_image = np.zeros((rows, cols, 3))
ones = np.argwhere(img_mask == 1.0)
twos = np.argwhere(img_mask == 2.0)
fours = np.argwhere(img_mask == 4.0)
for i in range(len(ones)):
sliced_image[ones[i][0], ones[i][1]] = [1, 0, 0]
for i in range(len(twos)):
sliced_image[twos[i][0], twos[i][1]] = [0, 1, 0]
for i in range(len(fours)):
sliced_image[fours[i][0], fours[i][1]] = [0, 0, 1]
# Construct RGB version of grey-level image
img_color = np.dstack((img, img, img))
# Convert the input image and color mask to Hue Saturation Value (HSV)
# colorspace
img_hsv = color.rgb2hsv(img_color)
color_mask_hsv = color.rgb2hsv(sliced_image)
# Replace the hue and saturation of the original image
# with that of the color mask
img_hsv[..., 0] = color_mask_hsv[..., 0]
img_hsv[..., 1] = color_mask_hsv[..., 1] * alpha
img_masked = color.hsv2rgb(img_hsv)
return img_color
# io.imshow(img_masked)
#plt.show()
"""# Saving the Visualizations of Coronal overlapped segmented regions
* Use the following code line for saving the overlapped ground truth region on the Coronal brain MRI Sequence
```
# brainMRI = all_modalitiesall_modalities[:, i, :, 0]
```
* Use the following code line for saving the overlapped predicted region on the Coronal brain MRI Sequence
```
# brainMRI = all_modalitiesall_modalities[:, i, :, 0]
# Predicted = predictionall_modalities[:, i, :, 0]
```
"""
root_path = '/content/drive/MyDrive/Training_115_Segmentation/T2/Coronal/'
#path = os.path.join(os.path.join(root_path), 'Ground_Truth_Overlap')
path = os.path.join(os.path.join(root_path), 'Brain_MRI')
#path = os.path.join(os.path.join(root_path), 'Prediction_Overlap')
for i in range(240):
brainMRI = all_modalities[:, i, :, 0]
#GroundTruth = gt[:,:,i,0]
Predicted = prediction[:,i,:,0]
print(brainMRI.shape)
print(Predicted.shape)
visualization=show_segmented_image(brainMRI,Predicted)
i=str(i)
j = "brain_name" + i + ".jpg"
path1 = os.path.join(os.path.join(path), j)
#io.imshow(visualization)
io.imshow(visualization,cmap="gray")
fig1 = plt.gcf()
plt.show()
plt.draw()
plt.axis('off')
fig1.savefig(path1, bbox_inches='tight', pad_inches = 0)
"""# Saving the Visualizations of Sagittal overlapped segmented regions
* Use the following code line for saving the overlapped ground truth region on the Sagittal brain MRI Sequence
```
# brainMRI = all_modalitiesall_modalities[:, :, i, 0]
# GroundTruth = gtall_modalities[:, :, i, 0]
```
* Use the following code line for saving the overlapped predicted region on the Sagittal brain MRI Sequence
```
# brainMRI = all_modalitiesall_modalities[:, :, i, 0]
# Predicted = predictionall_modalities[:, :, i, 0]
```
"""
root_path = '/content/drive/MyDrive/Training_115_Segmentation/T2/Sagittal/'
#path = os.path.join(os.path.join(root_path), 'Ground_Truth_Overlap')
path = os.path.join(os.path.join(root_path), 'Brain_MRI')
#path = os.path.join(os.path.join(root_path), 'Prediction_Overlap')
for i in range(240):
brainMRI = all_modalities[:, :, i, 0]
#GroundTruth = gt[:,:,i,0]
Predicted = prediction[:,:,i,0]
print(brainMRI.shape)
print(Predicted.shape)
visualization=show_segmented_image(brainMRI,Predicted)
i=str(i)
j = "brain_name" + i + ".jpg"
path1 = os.path.join(os.path.join(path), j)
#io.imshow(visualization)
#For visualizing Segmented regions use below line of code
io.imshow(visualization,cmap="gray")
fig1 = plt.gcf()
plt.show()
plt.draw()
plt.axis('off')
fig1.savefig(path1, bbox_inches='tight', pad_inches = 0)
"""# Saving the Visualizations of Axial overlapped segmented regions
* Use the following code line for saving the overlapped ground truth region on the Axial brain MRI Sequence
```
# brainMRI = all_modalities[i, :, :, 0]
# GroundTruth = gt[i,:,:,0]
```
* Use the following code line for saving the overlapped predicted region on the Axial brain MRI Sequence
```
# brainMRI = all_modalities[i, :, :, 0]
# Predicted = prediction[i,:,:,0]
```
"""
root_path = '/content/drive/MyDrive/Training_115_Segmentation/T2/Axial/'
path = os.path.join(os.path.join(root_path), 'Brain_MRI')
#path = os.path.join(os.path.join(root_path), 'Prediction_Overlap')
for i in range(155):
brainMRI = all_modalities[i, :, :, 0]
#GroundTruth = gt[:,:,i,0]
Predicted = prediction[i,:,:,0]
print(brainMRI.shape)
print(Predicted.shape)
visualization=show_segmented_image(brainMRI,Predicted)
i=str(i)
j = "brain_name" + i + ".jpg"
path1 = os.path.join(os.path.join(path), j)
#io.imshow(visualization)
io.imshow(visualization,cmap="gray")
fig1 = plt.gcf()
plt.show()
plt.draw()
plt.axis('off')
#plt.colorbar('off')
fig1.savefig(path1, bbox_inches='tight', pad_inches = 0)
"""# Gifs Creation """
!pip install pillow
import glob
from PIL import Image
# filepaths
fp_in = "/content/drive/MyDrive/Axial_GIF/Flair/*.jpg"
fp_out = "/content/drive/MyDrive/Axial_GIF/Flair_Brain.gif"
# https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#gif
img, *imgs = [Image.open(f) for f in sorted(glob.glob(fp_in), key=lambda x: int(x.split('brain_name', 1)[1].split('.jpg')[0]))]
img.save(fp=fp_out, format='GIF', append_images=imgs,
save_all=True, duration=500, loop=0)
import glob
from PIL import Image
# filepaths
fp_in = "/content/drive/MyDrive/Axial_GIF/Prediction/*.png"
fp_out = "/content/drive/MyDrive/Axial_GIF/Flair_Overlap.gif"
# https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#gif
img, *imgs = [Image.open(f) for f in sorted(glob.glob(fp_in), key=lambda x: int(x.split('brain_name', 1)[1].split('.png')[0]))]
img.save(fp=fp_out, format='GIF', append_images=imgs,
save_all=True, duration=500, loop=0)
import glob
from PIL import Image
# filepaths
fp_in = "/content/drive/MyDrive/Axial_GIF/T1/*.jpg"
fp_out = "/content/drive/MyDrive/Axial_GIF/T1_Brain.gif"
# https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#gif
img, *imgs = [Image.open(f) for f in sorted(glob.glob(fp_in), key=lambda x: int(x.split('brain_name', 1)[1].split('.jpg')[0]))]
img.save(fp=fp_out, format='GIF', append_images=imgs,
save_all=True, duration=500, loop=0)
import glob
from PIL import Image
# filepaths
fp_in = "/content/drive/MyDrive/Axial_GIF/T1ce/*.jpg"
fp_out = "/content/drive/MyDrive/Axial_GIF/T1ce_Brain.gif"
# https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#gif
img, *imgs = [Image.open(f) for f in sorted(glob.glob(fp_in), key=lambda x: int(x.split('brain_name', 1)[1].split('.jpg')[0]))]
img.save(fp=fp_out, format='GIF', append_images=imgs,
save_all=True, duration=500, loop=0)
import glob
from PIL import Image
# filepaths
fp_in = "/content/drive/MyDrive/Axial_GIF/T2/*.jpg"
fp_out = "/content/drive/MyDrive/Axial_GIF/T2_Brain.gif"
# https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#gif
img, *imgs = [Image.open(f) for f in sorted(glob.glob(fp_in), key=lambda x: int(x.split('brain_name', 1)[1].split('.jpg')[0]))]
img.save(fp=fp_out, format='GIF', append_images=imgs,
save_all=True, duration=500, loop=0)
import glob
from PIL import Image
# filepaths
fp_in = "/content/drive/MyDrive/Gif/T2/Sagittal/Brain_MRI/*.png"
fp_out = "/content/drive/MyDrive/Gif/T2/Sagittal/T2_Sagittal_Brain.gif"
# https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#gif
img, *imgs = [Image.open(f) for f in sorted(glob.glob(fp_in), key=lambda x: int(x.split('brain_name', 1)[1].split('.png')[0]))]
img.save(fp=fp_out, format='GIF', append_images=imgs,
save_all=True, duration=500, loop=0)
import glob
from PIL import Image
# filepaths
fp_in = "/content/drive/MyDrive/Gif/T1ce/Coronal/Brain_MRI/*.png"
fp_out = "/content/drive/MyDrive/Gif/T1ce/Coronal/T1_Coronal_Brain.gif"
# https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#gif
img, *imgs = [Image.open(f) for f in sorted(glob.glob(fp_in), key=lambda x: int(x.split('brain_name', 1)[1].split('.png')[0]))]
img.save(fp=fp_out, format='GIF', append_images=imgs,
save_all=True, duration=500, loop=0)
import glob
from PIL import Image
# filepaths
fp_in = "/content/drive/MyDrive/Gif/T2/Coronal/Brain_MRI/*.png"
fp_out = "/content/drive/MyDrive/Gif/T2/Coronal/T2_Coronal_Brain.gif"
# https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#gif
img, *imgs = [Image.open(f) for f in sorted(glob.glob(fp_in), key=lambda x: int(x.split('brain_name', 1)[1].split('.png')[0]))]
img.save(fp=fp_out, format='GIF', append_images=imgs,
save_all=True, duration=500, loop=0)
fp_in = "/content/drive/MyDrive/Gif/Flair/Axial/Brain_MRI/*.jpg"
from PIL import Image
import glob
# Create the frames
frames = []
imgs = glob.glob("/content/drive/MyDrive/Gif/Flair/Axial/Brain_MRI/*.jpg")
for i in imgs:
new_frame = Image.open(i)
frames.append(new_frame)
# Save into a GIF file that loops forever
frames[0].save('png_to_gif.gif', format='GIF',
append_images=frames[1:],
save_all=True,
duration=300, loop=0)
x ="brain_name7"
x.split('brain_name', 1)[1]
sorted(glob.glob(fp_in), key=lambda x: int(x.split('brain_name', 1)[1].split('.jpg')[0]))
glob.glob("/content/drive/MyDrive/Gif/Flair/Sagittal/Brain_MRI/*.png")