-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path7_2dunet_deployonoriginalvolumes.py
143 lines (90 loc) · 3.47 KB
/
7_2dunet_deployonoriginalvolumes.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
# -*- coding: utf-8 -*-
"""7 - 2DUnet_DeployOnOriginalVolumes.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1RJVme__Z8ij9zfkM7StPfMi5oeXfCCcd
"""
!pip install tensorflow==2.16.0rc0
!PYTHONHASHSEED=0
!pip install patchify
# Import other modules
from matplotlib import pyplot as plt
import zipfile
from shutil import copyfile
from time import time
import numpy as np
import pandas as pd
import random as python_random
import os
import shutil
import glob
from patchify import patchify, unpatchify
import random
# Import TensorFlow/Keras
import tensorflow as tf
import keras
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Conv3D, Conv3DTranspose, MaxPooling3D, concatenate, Dropout, Activation, BatchNormalization, GroupNormalization
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
import tensorflow.keras.backend as K
from google.colab import drive
drive.mount('/content/drive')
import tensorflow.keras.backend as K
def DiceCoefficient(y_true, y_pred, smooth = 1e-6):
y_pred = tf.keras.activations.softmax(y_pred, axis = -1)
# Cast to float32 datatype
y_true = K.cast(y_true, 'float32')
y_pred = K.cast(y_pred, 'float32')
# Flatten label and prediction tensors
inputs = K.flatten(y_pred)
targets = K.flatten(y_true)
intersection = K.sum(inputs * targets)
dice = (2 * intersection + smooth) / (K.sum(targets) + K.sum(inputs) + smooth)
return dice
model = keras.saving.load_model('/content/drive/MyDrive/DL_PROJECT/2D_FINAL/64_Base.keras', compile = True , custom_objects={'DiceCoefficient' : DiceCoefficient})
model.summary()
vol = np.load('/content/drive/MyDrive/DL_PROJECT/Data/image_006.npy')
mask = np.load('/content/drive/MyDrive/DL_PROJECT/Data/mask_006.npy')
def extract_images(volume):
images = []
for j in range(volume.shape[2]):
images.append(volume[:, :, j, :]) # Append each slice to the images list
images = np.array(images)
return images
def patches_to_minibatch(patch):
minibatch = []
for x in range(patch.shape[0]):
for y in range(patch.shape[1]):
minibatch.append(patch[x , y, 0, :, :, :])
return np.array(minibatch)
def reco_from_minibatch(minibatch):
pre_unpatch = np.zeros(shape = (2, 2, 1, 128, 128, 4))
pre_unpatch[0, 0, 0, :, :, :] = minibatch[0, :, :, :]
pre_unpatch[0, 1, 0, :, :, :] = minibatch[1, :, :, :]
pre_unpatch[1, 0, 0, :, :, :] = minibatch[2, :, :, :]
pre_unpatch[1, 1, 0, :, :, :] = minibatch[3, :, :, :]
return pre_unpatch
def make_prediction_vol(images):
vol_pred = []
for slice in range(images.shape[0]):
patches = patchify(images[slice, :, :, :], (128, 128, 4), step = 128)
batch = patches_to_minibatch(patches)
pred_batch = model.predict(batch, verbose = 0)
pre_unpatch = reco_from_minibatch(pred_batch)
reco_img = unpatchify(pre_unpatch, (256, 256, 4))
img_pred = list(reco_img.argmax(axis = 2))
vol_pred.append(img_pred)
return np.array(vol_pred)
images = extract_images(vol)
masks = extract_images(mask)
masks.shape
prediction = make_prediction_vol(images)
prediction.shape
true_vol = masks.argmax(axis = 3)
true_vol.shape
n_slice = random.randint(0, true_vol.shape[0])
fig, axs = plt.subplots(1, 2, figsize=(10, 10))
axs[0].imshow(prediction[n_slice, :, :], cmap = 'inferno')
axs[0].set_title('Predicted Segmentation')
axs[1].imshow(true_vol[n_slice, :, :], cmap = 'inferno')
axs[1].set_title('Original Segmentation')