leminhhung0101 commited on
Commit
bc52876
·
verified ·
1 Parent(s): 08f875f

Create SegmentationTest.py

Browse files
Files changed (1) hide show
  1. SegmentationTest.py +377 -0
SegmentationTest.py ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Script doc lap de test model phan doan (segmentation) khoi u nao
3
+ (DeepLabV3+ ResNet101V2) da train (.keras).
4
+ Khong can toan bo pipeline training - chi can model + 1 file de test.
5
+
6
+ Input: file .h5 co dataset 'image' (va 'mask' neu muon so sanh voi ground truth).
7
+
8
+ Cach dung:
9
+ # Chi du doan, luu anh overlay ra file
10
+ python test_segmentation.py --model best_model.keras --input slice.h5 --output result.png
11
+
12
+ # Du doan + tinh metric neu file h5 co san mask ground truth
13
+ python test_segmentation.py --model best_model.keras --input slice.h5 --output result.png
14
+ """
15
+
16
+ import argparse
17
+ import numpy as np
18
+ import cv2
19
+ import h5py
20
+ import tensorflow as tf
21
+ import matplotlib.pyplot as plt
22
+ from scipy.ndimage import label, binary_closing, binary_dilation
23
+
24
+ IMG_SIZE = (256, 256)
25
+ NUM_SLICES = 1
26
+ PIXEL_THRESHOLD = 0.01
27
+
28
+
29
+ # ============================================================
30
+ # LOSS / METRIC FUNCTIONS - BAT BUOC PHAI CO DE load_model() HOAT DONG
31
+ # (copy y nguyen tu script training goc)
32
+ # ============================================================
33
+ @tf.function
34
+ def dice_coef(y_true, y_pred, smooth=1e-6):
35
+ y_true = tf.cast(y_true, tf.float32)
36
+ y_pred = tf.cast(y_pred, tf.float32)
37
+ if len(y_true.shape) == 3:
38
+ y_true = tf.expand_dims(y_true, axis=-1)
39
+ if len(y_pred.shape) == 3:
40
+ y_pred = tf.expand_dims(y_pred, axis=-1)
41
+ y_true_f = tf.reshape(y_true, [-1])
42
+ y_pred_f = tf.reshape(y_pred, [-1])
43
+ intersection = tf.reduce_sum(y_true_f * y_pred_f)
44
+ union = tf.reduce_sum(y_true_f) + tf.reduce_sum(y_pred_f)
45
+ return (2.0 * intersection + smooth) / (union + smooth)
46
+
47
+
48
+ @tf.function
49
+ def generalized_dice_coef(y_true, y_pred, smooth=1e-6):
50
+ y_true = tf.cast(y_true, tf.float32)
51
+ y_pred = tf.cast(y_pred, tf.float32)
52
+ if len(y_true.shape) == 3:
53
+ y_true = tf.expand_dims(y_true, axis=-1)
54
+ if len(y_pred.shape) == 3:
55
+ y_pred = tf.expand_dims(y_pred, axis=-1)
56
+ w_fg = 1.0 / (tf.reduce_sum(y_true) ** 2 + smooth)
57
+ w_bg = 1.0 / (tf.reduce_sum(1.0 - y_true) ** 2 + smooth)
58
+ intersection_fg = tf.reduce_sum(y_true * y_pred)
59
+ union_fg = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred)
60
+ intersection_bg = tf.reduce_sum((1.0 - y_true) * (1.0 - y_pred))
61
+ union_bg = tf.reduce_sum(1.0 - y_true) + tf.reduce_sum(1.0 - y_pred)
62
+ numerator = w_fg * intersection_fg + w_bg * intersection_bg
63
+ denominator = w_fg * union_fg + w_bg * union_bg
64
+ return 2.0 * (numerator + smooth) / (denominator + smooth)
65
+
66
+
67
+ @tf.function
68
+ def weighted_dice_coef(y_true, y_pred, weight_fg=0.75, weight_bg=0.25, smooth=1e-6):
69
+ y_true = tf.cast(y_true, tf.float32)
70
+ y_pred = tf.cast(y_pred, tf.float32)
71
+ if len(y_true.shape) == 3:
72
+ y_true = tf.expand_dims(y_true, axis=-1)
73
+ if len(y_pred.shape) == 3:
74
+ y_pred = tf.expand_dims(y_pred, axis=-1)
75
+ intersection_fg = tf.reduce_sum(y_true * y_pred)
76
+ union_fg = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred)
77
+ dice_fg = (2.0 * intersection_fg + smooth) / (union_fg + smooth)
78
+ intersection_bg = tf.reduce_sum((1.0 - y_true) * (1.0 - y_pred))
79
+ union_bg = tf.reduce_sum(1.0 - y_true) + tf.reduce_sum(1.0 - y_pred)
80
+ dice_bg = (2.0 * intersection_bg + smooth) / (union_bg + smooth)
81
+ return weight_fg * dice_fg + weight_bg * dice_bg
82
+
83
+
84
+ @tf.function
85
+ def iou(y_true, y_pred, smooth=1e-6):
86
+ y_true = tf.cast(y_true, tf.float32)
87
+ y_pred = tf.cast(y_pred, tf.float32)
88
+ if len(y_true.shape) == 3:
89
+ y_true = tf.expand_dims(y_true, axis=-1)
90
+ if len(y_pred.shape) == 3:
91
+ y_pred = tf.expand_dims(y_pred, axis=-1)
92
+ y_true_f = tf.reshape(y_true, [-1])
93
+ y_pred_f = tf.reshape(y_pred, [-1])
94
+ intersection = tf.reduce_sum(y_true_f * y_pred_f)
95
+ union = tf.reduce_sum(y_true_f) + tf.reduce_sum(y_pred_f) - intersection
96
+ return (intersection + smooth) / (union + smooth)
97
+
98
+
99
+ @tf.function
100
+ def boundary_iou(y_true, y_pred, smooth=1e-6):
101
+ y_true = tf.cast(y_true, tf.float32)
102
+ y_pred = tf.cast(y_pred, tf.float32)
103
+ if len(y_true.shape) == 3:
104
+ y_true = tf.expand_dims(y_true, axis=-1)
105
+ if len(y_pred.shape) == 3:
106
+ y_pred = tf.expand_dims(y_pred, axis=-1)
107
+
108
+ def erosion(x):
109
+ return -tf.nn.max_pool2d(-x, ksize=3, strides=1, padding='SAME')
110
+
111
+ y_true_eroded = erosion(y_true)
112
+ y_pred_eroded = erosion(y_pred)
113
+ y_true_boundary = tf.abs(y_true - y_true_eroded)
114
+ y_pred_boundary = tf.abs(y_pred - y_pred_eroded)
115
+ intersection = tf.reduce_sum(y_true_boundary * y_pred_boundary)
116
+ union = tf.reduce_sum(y_true_boundary) + tf.reduce_sum(y_pred_boundary) - intersection
117
+ return (intersection + smooth) / (union + smooth)
118
+
119
+
120
+ @tf.function
121
+ def sensitivity(y_true, y_pred, smooth=1e-6):
122
+ y_true = tf.cast(y_true, tf.float32)
123
+ y_pred = tf.cast(y_pred > 0.5, tf.float32)
124
+ true_pos = tf.reduce_sum(y_true * y_pred)
125
+ false_neg = tf.reduce_sum(y_true * (1.0 - y_pred))
126
+ return (true_pos + smooth) / (true_pos + false_neg + smooth)
127
+
128
+
129
+ @tf.function
130
+ def specificity(y_true, y_pred, smooth=1e-6):
131
+ y_true = tf.cast(y_true, tf.float32)
132
+ y_pred = tf.cast(y_pred > 0.5, tf.float32)
133
+ true_neg = tf.reduce_sum((1.0 - y_true) * (1.0 - y_pred))
134
+ false_pos = tf.reduce_sum((1.0 - y_true) * y_pred)
135
+ return (true_neg + smooth) / (true_neg + false_pos + smooth)
136
+
137
+
138
+ @tf.function
139
+ def focal_loss(y_true, y_pred, alpha=0.75, gamma=2.0):
140
+ y_true = tf.cast(y_true, tf.float32)
141
+ y_pred = tf.cast(y_pred, tf.float32)
142
+ y_pred = tf.clip_by_value(y_pred, 1e-7, 1.0 - 1e-7)
143
+ pt_1 = tf.where(tf.equal(y_true, 1), y_pred, tf.ones_like(y_pred))
144
+ focal_pos = -alpha * tf.pow(1.0 - pt_1, gamma) * tf.math.log(pt_1)
145
+ pt_0 = tf.where(tf.equal(y_true, 0), y_pred, tf.zeros_like(y_pred))
146
+ focal_neg = -(1 - alpha) * tf.pow(pt_0, gamma) * tf.math.log(1.0 - pt_0)
147
+ return tf.reduce_mean(focal_pos + focal_neg)
148
+
149
+
150
+ @tf.function
151
+ def tversky_loss(y_true, y_pred, alpha=0.8, beta=0.2, smooth=1e-6):
152
+ y_true = tf.cast(y_true, tf.float32)
153
+ y_pred = tf.cast(y_pred, tf.float32)
154
+ if len(y_true.shape) == 3:
155
+ y_true = tf.expand_dims(y_true, axis=-1)
156
+ if len(y_pred.shape) == 3:
157
+ y_pred = tf.expand_dims(y_pred, axis=-1)
158
+ y_true_f = tf.reshape(y_true, [-1])
159
+ y_pred_f = tf.reshape(y_pred, [-1])
160
+ true_pos = tf.reduce_sum(y_true_f * y_pred_f)
161
+ false_neg = tf.reduce_sum(y_true_f * (1 - y_pred_f))
162
+ false_pos = tf.reduce_sum((1 - y_true_f) * y_pred_f)
163
+ tversky_index = (true_pos + smooth) / (true_pos + alpha * false_neg + beta * false_pos + smooth)
164
+ return 1.0 - tversky_index
165
+
166
+
167
+ @tf.function
168
+ def focal_tversky_loss(y_true, y_pred, alpha=0.8, beta=0.2, gamma=0.75, smooth=1e-6):
169
+ tversky = tversky_loss(y_true, y_pred, alpha, beta, smooth)
170
+ return tf.pow(tversky, gamma)
171
+
172
+
173
+ @tf.function
174
+ def generalized_dice_loss(y_true, y_pred, smooth=1e-6):
175
+ return 1.0 - generalized_dice_coef(y_true, y_pred, smooth)
176
+
177
+
178
+ @tf.function
179
+ def boundary_loss(y_true, y_pred, smooth=1e-6):
180
+ y_true = tf.cast(y_true, tf.float32)
181
+ y_pred = tf.cast(y_pred, tf.float32)
182
+ if len(y_true.shape) == 3:
183
+ y_true = tf.expand_dims(y_true, axis=-1)
184
+ if len(y_pred.shape) == 3:
185
+ y_pred = tf.expand_dims(y_pred, axis=-1)
186
+ sobel_x = tf.reshape(tf.constant([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], dtype=tf.float32), [3, 3, 1, 1])
187
+ sobel_y = tf.reshape(tf.constant([[-1, -2, -1], [0, 0, 0], [1, 2, 1]], dtype=tf.float32), [3, 3, 1, 1])
188
+ edges_true_x = tf.nn.conv2d(y_true, sobel_x, strides=[1, 1, 1, 1], padding='SAME')
189
+ edges_true_y = tf.nn.conv2d(y_true, sobel_y, strides=[1, 1, 1, 1], padding='SAME')
190
+ edges_true = tf.sqrt(edges_true_x ** 2 + edges_true_y ** 2 + smooth)
191
+ edges_pred_x = tf.nn.conv2d(y_pred, sobel_x, strides=[1, 1, 1, 1], padding='SAME')
192
+ edges_pred_y = tf.nn.conv2d(y_pred, sobel_y, strides=[1, 1, 1, 1], padding='SAME')
193
+ edges_pred = tf.sqrt(edges_pred_x ** 2 + edges_pred_y ** 2 + smooth)
194
+ return tf.reduce_mean(tf.square(edges_true - edges_pred))
195
+
196
+
197
+ @tf.function
198
+ def hybrid_loss_optimized(y_true, y_pred, w_ft=0.5, w_dice=0.35, w_boundary=0.1, w_focal=0.05):
199
+ ft_loss = focal_tversky_loss(y_true, y_pred, alpha=0.8, beta=0.2, gamma=0.75)
200
+ d_loss = generalized_dice_loss(y_true, y_pred)
201
+ b_loss = boundary_loss(y_true, y_pred)
202
+ f_loss = focal_loss(y_true, y_pred, alpha=0.75, gamma=2.0)
203
+ return w_ft * ft_loss + w_dice * d_loss + w_boundary * b_loss + w_focal * f_loss
204
+
205
+
206
+ CUSTOM_OBJECTS = {
207
+ 'dice_coef': dice_coef,
208
+ 'generalized_dice_coef': generalized_dice_coef,
209
+ 'weighted_dice_coef': weighted_dice_coef,
210
+ 'iou': iou,
211
+ 'boundary_iou': boundary_iou,
212
+ 'sensitivity': sensitivity,
213
+ 'specificity': specificity,
214
+ 'focal_loss': focal_loss,
215
+ 'tversky_loss': tversky_loss,
216
+ 'focal_tversky_loss': focal_tversky_loss,
217
+ 'generalized_dice_loss': generalized_dice_loss,
218
+ 'boundary_loss': boundary_loss,
219
+ 'hybrid_loss_optimized': hybrid_loss_optimized,
220
+ }
221
+
222
+
223
+ # ============================================================
224
+ # TIEN XU LY - GIONG HET LOGIC TRONG ImprovedNiftiGenerator BAN GOC
225
+ # ============================================================
226
+ def load_image_and_mask_from_h5(path):
227
+ """Doc anh (va mask neu co) tu file .h5."""
228
+ with h5py.File(path, 'r') as f:
229
+ if 'image' not in f:
230
+ raise ValueError(f"File h5 khong co dataset 'image': {path}")
231
+ img = f['image'][:].astype(np.float32)
232
+ if img.ndim == 3:
233
+ img = img[..., 0]
234
+
235
+ mask = None
236
+ if 'mask' in f:
237
+ mask = f['mask'][:].astype(np.float32)
238
+ if mask.ndim == 3:
239
+ mask = mask[..., 0]
240
+
241
+ return img, mask
242
+
243
+
244
+ def preprocess_image(img, mask=None):
245
+ """Resize + normalize percentile (2, 98) - dung y nhu _load_slice va
246
+ _normalize_batch trong ImprovedNiftiGenerator ban goc."""
247
+ if img.shape != IMG_SIZE:
248
+ img = cv2.resize(img, IMG_SIZE, interpolation=cv2.INTER_LINEAR)
249
+ if mask is not None and mask.shape != IMG_SIZE:
250
+ mask = cv2.resize(mask, IMG_SIZE, interpolation=cv2.INTER_NEAREST)
251
+ if mask is not None:
252
+ mask = (mask > 0).astype(np.float32)
253
+
254
+ p2, p98 = np.percentile(img, (2, 98))
255
+ img_norm = np.clip(img, p2, p98)
256
+ img_norm = (img_norm - p2) / (p98 - p2 + 1e-8)
257
+
258
+ X = img_norm[np.newaxis, ..., np.newaxis].astype(np.float32) # (1, 256, 256, 1)
259
+ return X, img, mask
260
+
261
+
262
+ def advanced_post_process(pred, threshold=0.25, min_size=100):
263
+ """Hau xu ly du doan de loai bo noise va lam min (copy tu ban goc)."""
264
+ binary_pred = (pred > threshold).astype(np.uint8)
265
+
266
+ kernel_close = np.ones((3, 3), np.uint8)
267
+ binary_pred = binary_closing(binary_pred, structure=kernel_close).astype(np.uint8)
268
+
269
+ labeled, num_features = label(binary_pred)
270
+ if num_features > 0:
271
+ sizes = np.bincount(labeled.flat)[1:]
272
+ for i, size in enumerate(sizes, 1):
273
+ if size < min_size:
274
+ binary_pred[labeled == i] = 0
275
+
276
+ kernel_dilate = np.ones((2, 2), np.uint8)
277
+ binary_pred = binary_dilation(binary_pred, structure=kernel_dilate).astype(np.uint8)
278
+
279
+ return binary_pred
280
+
281
+
282
+ # ============================================================
283
+ # CHAY INFERENCE
284
+ # ============================================================
285
+ def run_inference(model_path, input_path, output_path=None, threshold=0.25, min_size=100):
286
+ print(f"Dang load model: {model_path}")
287
+ model = tf.keras.models.load_model(model_path, custom_objects=CUSTOM_OBJECTS)
288
+
289
+ print(f"Dang doc va tien xu ly file: {input_path}")
290
+ raw_img, raw_mask = load_image_and_mask_from_h5(input_path)
291
+ X, img_resized, mask_resized = preprocess_image(raw_img, raw_mask)
292
+
293
+ print("Dang du doan...")
294
+ pred_raw = model.predict(X, verbose=0)[0, ..., 0]
295
+ pred_processed = advanced_post_process(pred_raw, threshold=threshold, min_size=min_size)
296
+
297
+ tumor_pixels = int(pred_processed.sum())
298
+ total_pixels = pred_processed.size
299
+ print("\n" + "=" * 50)
300
+ print("KET QUA DU DOAN (SEGMENTATION)")
301
+ print("=" * 50)
302
+ print(f"So pixel duoc du doan la tumor: {tumor_pixels} / {total_pixels} "
303
+ f"({100 * tumor_pixels / total_pixels:.2f}%)")
304
+ print(f"Xac suat trung binh (raw) vung tumor: {pred_raw.mean():.4f}")
305
+ print(f"Xac suat max (raw): {pred_raw.max():.4f}")
306
+
307
+ # Neu file h5 co san ground truth mask -> tinh metric so sanh
308
+ if mask_resized is not None:
309
+ y_true = tf.constant(mask_resized[..., np.newaxis], dtype=tf.float32)
310
+ y_pred = tf.constant(pred_processed[..., np.newaxis].astype(np.float32), dtype=tf.float32)
311
+
312
+ dice = dice_coef(y_true, y_pred).numpy()
313
+ iou_score = iou(y_true, y_pred).numpy()
314
+ sens = sensitivity(y_true, y_pred).numpy()
315
+ spec = specificity(y_true, y_pred).numpy()
316
+
317
+ true_pos = np.sum((mask_resized == 1) & (pred_processed == 1))
318
+ false_pos = np.sum((mask_resized == 0) & (pred_processed == 1))
319
+ precision = true_pos / (true_pos + false_pos + 1e-7)
320
+ f1 = 2 * precision * sens / (precision + sens + 1e-7)
321
+
322
+ print("\nSo sanh voi ground truth mask co san trong file h5:")
323
+ print(f" Dice coefficient : {dice:.4f}")
324
+ print(f" IoU : {iou_score:.4f}")
325
+ print(f" Sensitivity : {sens:.4f}")
326
+ print(f" Specificity : {spec:.4f}")
327
+ print(f" Precision : {precision:.4f}")
328
+ print(f" F1 Score : {f1:.4f}")
329
+ else:
330
+ print("\n(File h5 khong co dataset 'mask' nen khong tinh duoc metric so sanh)")
331
+
332
+ print("=" * 50)
333
+
334
+ # Xuat anh minh hoa
335
+ if output_path:
336
+ n_panels = 4 if mask_resized is not None else 3
337
+ fig, axes = plt.subplots(1, n_panels, figsize=(4 * n_panels, 4))
338
+
339
+ axes[0].imshow(img_resized, cmap='gray')
340
+ axes[0].set_title('Anh dau vao')
341
+ axes[0].axis('off')
342
+
343
+ idx = 1
344
+ if mask_resized is not None:
345
+ axes[idx].imshow(mask_resized, cmap='jet', alpha=0.8)
346
+ axes[idx].set_title('Ground Truth')
347
+ axes[idx].axis('off')
348
+ idx += 1
349
+
350
+ axes[idx].imshow(pred_processed, cmap='jet', alpha=0.8)
351
+ axes[idx].set_title('Du doan')
352
+ axes[idx].axis('off')
353
+ idx += 1
354
+
355
+ axes[idx].imshow(img_resized, cmap='gray')
356
+ axes[idx].imshow(pred_processed, cmap='jet', alpha=0.5)
357
+ axes[idx].set_title('Overlay')
358
+ axes[idx].axis('off')
359
+
360
+ plt.tight_layout()
361
+ plt.savefig(output_path, dpi=150, bbox_inches='tight')
362
+ plt.close()
363
+ print(f"\nDa luu anh minh hoa tai: {output_path}")
364
+
365
+ return pred_raw, pred_processed
366
+
367
+
368
+ if __name__ == "__main__":
369
+ parser = argparse.ArgumentParser(description="Test model segmentation khoi u nao voi 1 file .h5")
370
+ parser.add_argument("--model", required=True, help="Duong dan file model .keras")
371
+ parser.add_argument("--input", required=True, help="Duong dan file .h5 can test (co dataset 'image', 'mask' neu co)")
372
+ parser.add_argument("--output", default=None, help="Duong dan file .png de luu anh minh hoa (tuy chon)")
373
+ parser.add_argument("--threshold", type=float, default=0.25, help="Nguong nhi phan hoa du doan (mac dinh 0.25)")
374
+ parser.add_argument("--min_size", type=int, default=100, help="Kich thuoc vung nho nhat giu lai, tinh bang pixel (mac dinh 100)")
375
+ args = parser.parse_args()
376
+
377
+ run_inference(args.model, args.input, args.output, args.threshold, args.min_size)