|
a |
|
b/Segmentation/test.py |
|
|
1 |
import os |
|
|
2 |
import cv2 |
|
|
3 |
import numpy as np |
|
|
4 |
import matplotlib.pyplot as plt |
|
|
5 |
os.environ["SM_FRAMEWORK"] = "tf.keras" |
|
|
6 |
import segmentation_models as sm |
|
|
7 |
sm.framework() |
|
|
8 |
|
|
|
9 |
my_model = "efficientnetb1" |
|
|
10 |
model = sm.Unet(my_model, encoder_weights="imagenet", input_shape=( 256,256, 3), classes=3, activation='sigmoid') |
|
|
11 |
model.load_weights("Submission_segmentation/weights/unet_model_weights.h5") |
|
|
12 |
|
|
|
13 |
#test for single image |
|
|
14 |
def visualize_single_image_prediction(model, image_path): |
|
|
15 |
# Load the image |
|
|
16 |
original_img = cv2.imread(image_path) |
|
|
17 |
resized_img = cv2.resize(original_img, (256, 256)) |
|
|
18 |
|
|
|
19 |
# Predict the mask |
|
|
20 |
X = np.expand_dims(resized_img, 0) |
|
|
21 |
y_pred = model.predict(X) |
|
|
22 |
_, y_pred_thr = cv2.threshold(y_pred[0, :, :, 0] * 255, 127, 255, cv2.THRESH_BINARY) |
|
|
23 |
y_pred = (y_pred_thr / 255).astype(int) |
|
|
24 |
|
|
|
25 |
# Resize the predicted mask back to the original size |
|
|
26 |
y_pred_original = cv2.resize(y_pred.astype(float), (original_img.shape[1], original_img.shape[0]), interpolation=cv2.INTER_LINEAR) |
|
|
27 |
|
|
|
28 |
# Visualize the original image and predicted mask |
|
|
29 |
plt.figure(figsize=(12, 4)) |
|
|
30 |
plt.subplot(131) |
|
|
31 |
plt.title("Original Image") |
|
|
32 |
plt.imshow(cv2.cvtColor(original_img, cv2.COLOR_BGR2RGB)) |
|
|
33 |
plt.axis("off") |
|
|
34 |
|
|
|
35 |
plt.subplot(132) |
|
|
36 |
plt.title("Predicted Mask") |
|
|
37 |
plt.imshow(y_pred_original, cmap="gray") |
|
|
38 |
plt.axis("off") |
|
|
39 |
|
|
|
40 |
plt.show() |
|
|
41 |
|
|
|
42 |
#example |
|
|
43 |
visualize_single_image_prediction(model, "img- (10).png") |
|
|
44 |
print("done") |