-
Notifications
You must be signed in to change notification settings - Fork 0
/
Final.py
293 lines (215 loc) · 10.9 KB
/
Final.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
# -*- coding: utf-8 -*-
"""DMGS_DIP_35270_Final.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1StBrRnuUnuyL9ZqqKct5Iyg_7RroqMch
"""
!pip install SimpleITK
pip install nibabel scikit-image
"""------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------"""
import os
import numpy as np
import nibabel as nib
import matplotlib.pyplot as plt
from skimage.transform import resize
from keras.models import Model
from keras.layers import Input, Conv2D, MaxPooling2D, Dropout, UpSampling2D, concatenate
# Load and preprocessing the data in batches
def load_data(file_path, target_shape):
# Load NIfTI file using nibabel
img = nib.load(file_path)
data = img.get_fdata()
# Resize the data to the target shape
resized_data = resize(data, target_shape)
return resized_data
def load_and_preprocess_data(file_paths, target_shape=(256, 256, 1)):
data_list = []
for file_path in file_paths:
data = load_data(file_path, target_shape)
data_list.append(data)
data_array = np.stack(data_list, axis=0)
return data_array
# Batch size for loading and preprocessing
batch_size = 2
# Defining target shape
target_shape = (256, 256, 1)
# Dataset paths
input_folder = '/content/drive/MyDrive/Dataset/Liver_tumor Part2'
input_files = [os.path.join(input_folder, f'volume-{i}.nii') for i in range(51, 56)]
segmentation_folder = '/content/drive/MyDrive/Dataset/Liver Part 1/segmentations'
segmentation_files = [os.path.join(segmentation_folder, f'segmentation-{i}.nii') for i in [0, 1, 10, 11, 12]]
# Displaying input and segmentation file names with directory names
def display_file_names(input_files, segmentation_files):
print("Input Files:")
for file_path in input_files:
directory_name, file_name = os.path.split(file_path)
print(f"Directory: {directory_name}, File: {file_name}")
print("\nSegmentation Files:")
for file_path in segmentation_files:
directory_name, file_name = os.path.split(file_path)
print(f"Directory: {directory_name}, File: {file_name}")
# Example usage:
display_file_names(input_files, segmentation_files)
# Loading and preprocessing segmentation data in batches
segmentation_data = []
for i in range(0, len(segmentation_files), batch_size):
batch_files = segmentation_files[i:i + batch_size]
batch_data = load_and_preprocess_data(batch_files, target_shape)
batch_data[batch_data > 0] = 1
segmentation_data.append(batch_data)
segmentation_data = np.vstack(segmentation_data)
# Loading and preprocessing input data in batches
input_data = []
for i in range(0, len(input_files), batch_size):
batch_files = input_files[i:i + batch_size]
batch_data = load_and_preprocess_data(batch_files, target_shape)
batch_data = (batch_data - np.min(batch_data)) / (np.max(batch_data) - np.min(batch_data))
input_data.append(batch_data)
input_data = np.vstack(input_data)
# UNet model architecture
def unet_model(input_size):
inputs = Input(input_size)
# Encoder
conv1 = Conv2D(64, 3, activation='relu', padding='same')(inputs)
conv1 = Conv2D(64, 3, activation='relu', padding='same')(conv1)
pool1 = MaxPooling2D(pool_size=(2, 2), padding='same')(conv1)
conv2 = Conv2D(128, 3, activation='relu', padding='same')(pool1)
conv2 = Conv2D(128, 3, activation='relu', padding='same')(conv2)
pool2 = MaxPooling2D(pool_size=(2, 2), padding='same')(conv2)
conv3 = Conv2D(256, 3, activation='relu', padding='same')(pool2)
conv3 = Conv2D(256, 3, activation='relu', padding='same')(conv3)
pool3 = MaxPooling2D(pool_size=(2, 2), padding='same')(conv3)
conv4 = Conv2D(512, 3, activation='relu', padding='same')(pool3)
conv4 = Conv2D(512, 3, activation='relu', padding='same')(conv4)
drop4 = Dropout(0.5)(conv4)
pool4 = MaxPooling2D(pool_size=(2, 2), padding='same')(drop4)
# Middle
conv5 = Conv2D(1024, 3, activation='relu', padding='same')(pool4)
conv5 = Conv2D(1024, 3, activation='relu', padding='same')(conv5)
drop5 = Dropout(0.5)(conv5)
# Decoder
up6 = UpSampling2D(size=(2, 2))(drop5)
up6 = concatenate([up6, drop4], axis=3)
conv6 = Conv2D(512, 3, activation='relu', padding='same')(up6)
conv6 = Conv2D(512, 3, activation='relu', padding='same')(conv6)
up7 = UpSampling2D(size=(2, 2))(conv6)
up7 = concatenate([up7, conv3], axis=3)
conv7 = Conv2D(256, 3, activation='relu', padding='same')(up7)
conv7 = Conv2D(256, 3, activation='relu', padding='same')(conv7)
up8 = UpSampling2D(size=(2, 2))(conv7)
up8 = concatenate([up8, conv2], axis=3)
conv8 = Conv2D(128, 3, activation='relu', padding='same')(up8)
conv8 = Conv2D(128, 3, activation='relu', padding='same')(conv8)
up9 = UpSampling2D(size=(2, 2))(conv8)
up9 = concatenate([up9, conv1], axis=3)
conv9 = Conv2D(64, 3, activation='relu', padding='same')(up9)
conv9 = Conv2D(64, 3, activation='relu', padding='same')(conv9)
# Output layer
output = Conv2D(1, 1, activation='sigmoid')(conv9)
model = Model(inputs=inputs, outputs=output)
return model
# Training the model
model = unet_model((256, 256, 1))
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
history=model.fit(input_data, segmentation_data, epochs=5, batch_size=1, validation_split=0.2)
from google.colab import drive
drive.mount('/content/drive')
def apply_window(image, center, width):
windowed_image = np.clip((image - (center - 0.5 * width)) / width, 0, 1)
return windowed_image
# Function to generate and display windowed images
def generate_and_display_windowed_images(input_files, center, width):
for file_path in input_files:
input_data = load_data(file_path, target_shape=(256, 256, 1))
# Apply windowing to the input data
windowed_image = apply_window(input_data, center, width)
# Display original and windowed images side by side
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.title("Original Image")
plt.imshow(np.squeeze(input_data), cmap="gray")
plt.subplot(1, 2, 2)
plt.title("Windowed Image")
plt.imshow(np.squeeze(windowed_image), cmap="gray")
plt.show()
window_center = 100
window_width = 200
generate_and_display_windowed_images(input_files, window_center, window_width)
model.summary()
print(input_data.shape)
import matplotlib.pyplot as plt
# Generating predicted images
def generate_and_show_maxpool_images(model, input_files, threshold=0.5):
for file_path in input_files:
input_data = load_data(file_path, target_shape=(256, 256, 1))
# Normalize the input_data
input_data_min = np.min(input_data)
input_data_max = np.max(input_data)
input_data = (input_data - input_data_min) / (input_data_max - input_data_min)
input_data = np.expand_dims(input_data, axis=0) # Add batch dimension
# Predicting segmentation mask
predicted_mask = model.predict(input_data)
# Apply threshold to the predicted mask
binary_mask = (predicted_mask > threshold).astype(np.uint8)
# Creating overlay image
overlay_image = input_data.copy()
overlay_image[binary_mask == 1] = 1.0 # Set pixels in the tumor region to a different intensity (e.g., white)
# Displaying input, predicted mask, and overlay images
plt.figure(figsize=(15, 5))
plt.subplot(1, 3, 1)
plt.title("Input Image")
plt.imshow(np.squeeze(input_data), cmap="gray")
plt.subplot(1, 3, 2)
plt.title("Predicted Mask")
plt.imshow(np.squeeze(predicted_mask), cmap="pink")
plt.subplot(1, 3, 3)
plt.title("Overlay Image")
plt.imshow(np.squeeze(overlay_image), cmap="gray")
plt.show()
# Example usage:
generate_and_show_maxpool_images(model, input_files)
test_input_files = ['/content/drive/MyDrive/Dataset/Liver Part 1/segmentations/segmentation-0.nii'
,'/content/drive/MyDrive/Dataset/Liver Part 1/segmentations/segmentation-1.nii'
,'/content/drive/MyDrive/Dataset/Liver Part 1/segmentations/segmentation-11.nii'
,'/content/drive/MyDrive/Dataset/Liver Part 1/segmentations/segmentation-11.nii'
,'/content/drive/MyDrive/Dataset/Liver Part 1/segmentations/segmentation-12.nii']
# List of file paths for test input data
test_segmentation_files = ['/content/drive/MyDrive/Dataset/Liver Part 1/segmentations/segmentation-0.nii'
,'/content/drive/MyDrive/Dataset/Liver Part 1/segmentations/segmentation-0.nii'
,'/content/drive/MyDrive/Dataset/Liver Part 1/segmentations/segmentation-10.nii'
,'/content/drive/MyDrive/Dataset/Liver Part 1/segmentations/segmentation-11.nii'
,'/content/drive/MyDrive/Dataset/Liver Part 1/segmentations/segmentation-12.nii'] # List of file paths for test segmentation data
# Loading and preprocessing test data
test_input_data = load_and_preprocess_data(test_input_files, target_shape)
test_segmentation_data = load_and_preprocess_data(test_segmentation_files, target_shape)
test_segmentation_data[test_segmentation_data > 0] = 1 # Applying threshold
# Evaluate on the test set
test_loss, test_accuracy = model.evaluate(test_input_data, test_segmentation_data)
# Make predictions on the test set
y_pred = model.predict(test_input_data)
y_pred_classes = (y_pred > 0.5).astype(np.uint8)
# Convert one-hot encoded labels to integers
y_true_classes = test_segmentation_data.astype(np.uint8)
# Print classification report
print("Classification Report:\n", classification_report(y_true_classes.flatten(), y_pred_classes.flatten()))
# Print accuracy
print("Test Accuracy:", test_accuracy)
# Assuming you have a training history object named 'history' obtained from model.fit()
# Plot training accuracy and validation accuracy
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.plot(history.history['accuracy'], label='Train')
plt.plot(history.history['val_accuracy'], label='Validation')
plt.title('Model accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend(loc='upper left')
# Plot training loss and validation loss
plt.subplot(1, 2, 2)
plt.plot(history.history['loss'], label='Train')
plt.plot(history.history['val_loss'], label='Validation')
plt.title('Model loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend(loc='upper left')
plt.show()