Views
No views yet
1# Import necessary classes
2from tensorflow.keras.models import load_model
3from tensorflow.python.keras import layers
4from tensorflow.python.keras.models import Sequential
5
6import random
7import numpy as np
8import matplotlib.pyplot as plt
9from tensorflow.keras.preprocessing.image import ImageDataGenerator
10
11seed=24
12batch_size= 8
13
14# Load images for dataset generators from respective dataset libraries. The images and masks are returned as NumPy arrays
15
16# Images can be further resized by adding target_size=(150, 150) with any size for your network to flow_from_directory parameters
17# Our images are already cropped to 256x256 so traget_size parameter can be ignored
18
19def image_and_mask_generator(image_dir, label_dir):
20 img_data_gen_args = dict(rescale = 1/255.)
21 mask_data_gen_args = dict()
22
23 image_data_generator = ImageDataGenerator(**img_data_gen_args)
24 image_generator = image_data_generator.flow_from_directory(image_dir,
25 seed=seed,
26 batch_size=batch_size,
27 classes = ["."],
28 class_mode=None #Very important to set this otherwise it returns multiple numpy arrays thinking class mode is binary.
29 )
30
31 mask_data_generator = ImageDataGenerator(**mask_data_gen_args)
32 mask_generator = mask_data_generator.flow_from_directory(label_dir,
33 classes = ["."],
34 seed=seed,
35 batch_size=batch_size,
36 color_mode = 'grayscale', #Read masks in grayscale
37 class_mode=None
38 )
39 # print processed image paths for vanity
40 print(image_generator.filenames[0:5])
41 print(mask_generator.filenames[0:5])
42
43 generator = zip(image_generator, mask_generator)
44 return generator
45
46# Method to calculate Intersection over Union Accuracy Coefficient
47def iou_coef(y_true, y_pred, smooth=1e-6):
48 intersection = tensorflow.reduce_sum(y_true * y_pred)
49 union = tensorflow.reduce_sum(y_true) + tensorflow.reduce_sum(y_pred) - intersection
50
51 return (intersection + smooth) / (union + smooth)
52
53# Method to calculate Dice Accuracy Coefficient
54def dice_coef(y_true, y_pred, smooth=1e-6):
55 intersection = tensorflow.reduce_sum(y_true * y_pred)
56 total = tensorflow.reduce_sum(y_true) + tensorflow.reduce_sum(y_pred)
57
58 return (2. * intersection + smooth) / (total + smooth)
59
60# Method to calculate Dice Loss
61def soft_dice_loss(y_true, y_pred):
62 return 1-dice_coef(y_true, y_pred)
63
64# Method to create generator
65def create_generator(zipped):
66 for (img, mask) in zipped:
67 yield (img, mask)
68
69model_path = "path"
70u_net_model = load_model(model_path, custom_objects={'soft_dice_loss': soft_dice_loss, 'dice_coef': dice_coef, "iou_coef": iou_coef})
71
72test_generator = create_generator(image_and_mask_generator(output_test_image_dir,output_test_label_dir))
73
74# Assuming create_generator is defined and provides images for prediction
75images, ground_truth_masks = next(test_generator)
76
77# Make predictions
78predictions = u_net_model.predict(images)
79
80# Apply threshold to predictions
81thresh_val = 0.8
82prediction_threshold = (predictions > thresh_val).astype(np.uint8)
83
84# Visualize results
85num_samples = min(10, len(images)) # Use at most 10 samples or the total number of images available
86f = plt.figure(figsize=(15, 25))
87for i in range(num_samples):
88 ix = random.randint(0, len(images) - 1) # Ensure ix is within range
89
90 f.add_subplot(num_samples, 4, i * 4 + 1)
91 plt.imshow(images[ix])
92 plt.title("Image")
93 plt.axis('off')
94
95 f.add_subplot(num_samples, 4, i * 4 + 2)
96 plt.imshow(np.squeeze(ground_truth_masks[ix]))
97 plt.title("Ground Truth")
98 plt.axis('off')
99
100 f.add_subplot(num_samples, 4, i * 4 + 3)
101 plt.imshow(np.squeeze(predictions[ix]))
102 plt.title("Prediction")
103 plt.axis('off')
104
105 f.add_subplot(num_samples, 4, i * 4 + 4)
106 plt.imshow(np.squeeze(prediction_threshold[ix]))
107 plt.title(f"Thresholded at {thresh_val}")
108 plt.axis('off')
109
110plt.show()
111