|
a |
|
b/Segmentation/infrence.py |
|
|
1 |
import os |
|
|
2 |
import cv2 |
|
|
3 |
import numpy as np |
|
|
4 |
import matplotlib.pyplot as plt |
|
|
5 |
|
|
|
6 |
os.environ["SM_FRAMEWORK"] = "tf.keras" |
|
|
7 |
import segmentation_models as sm |
|
|
8 |
|
|
|
9 |
sm.framework() |
|
|
10 |
|
|
|
11 |
my_model = "efficientnetb1" |
|
|
12 |
model = sm.Unet(my_model, encoder_weights="imagenet", input_shape=(256, 256, 3), classes=3, activation='sigmoid') |
|
|
13 |
model.load_weights("Submission_segmentation/weights/unet_model_weights.h5") |
|
|
14 |
|
|
|
15 |
# Define the directory to save the images |
|
|
16 |
output_dir = "result/Test-Dataset2" |
|
|
17 |
|
|
|
18 |
# Create the output directory if it doesn't exist |
|
|
19 |
if not os.path.exists(output_dir): |
|
|
20 |
os.makedirs(output_dir) |
|
|
21 |
|
|
|
22 |
def save_single_image_prediction(model, image_path, output_dir): |
|
|
23 |
# Load the image |
|
|
24 |
original_img = cv2.imread(image_path) |
|
|
25 |
resized_img = cv2.resize(original_img, (256, 256)) |
|
|
26 |
|
|
|
27 |
# Predict the mask |
|
|
28 |
X = np.expand_dims(resized_img, 0) |
|
|
29 |
y_pred = model.predict(X) |
|
|
30 |
_, y_pred_thr = cv2.threshold(y_pred[0, :, :, 0] * 255, 127, 255, cv2.THRESH_BINARY) |
|
|
31 |
y_pred = (y_pred_thr / 255).astype(int) |
|
|
32 |
|
|
|
33 |
# Resize the predicted mask back to the original size |
|
|
34 |
y_pred_original = cv2.resize(y_pred.astype(float), (original_img.shape[1], original_img.shape[0]), interpolation=cv2.INTER_LINEAR) |
|
|
35 |
|
|
|
36 |
# Save the original image and predicted mask |
|
|
37 |
output_image_path = os.path.join(output_dir, os.path.basename(image_path)) |
|
|
38 |
# cv2.imwrite(output_image_path, cv2.cvtColor(original_img, cv2.COLOR_BGR2RGB)) |
|
|
39 |
cv2.imwrite(os.path.join(output_dir, f"predicted_mask_{os.path.basename(image_path)}"), y_pred_original * 255) |
|
|
40 |
|
|
|
41 |
|
|
|
42 |
# for i in os.listdir("Submission_segmentation/data/Auto-WCEBleedGen Challenge Test Dataset/Test Dataset 2"): |
|
|
43 |
# model_path = "Submission_segmentation/data/Auto-WCEBleedGen Challenge Test Dataset/Test Dataset 2/"+i |
|
|
44 |
# save_single_image_prediction(model,model_path,output_dir) |
|
|
45 |
# print(i) |