|
a |
|
b/predict.py |
|
|
1 |
import os |
|
|
2 |
import cv2 |
|
|
3 |
import numpy as np |
|
|
4 |
import pandas as pd |
|
|
5 |
from glob import glob |
|
|
6 |
from tqdm import tqdm |
|
|
7 |
import pydicom as dicom |
|
|
8 |
|
|
|
9 |
import tensorflow as tf |
|
|
10 |
from tensorflow.keras.utils import CustomObjectScope |
|
|
11 |
from sklearn.metrics import ( |
|
|
12 |
accuracy_score, |
|
|
13 |
f1_score, |
|
|
14 |
jaccard_score, |
|
|
15 |
precision_score, |
|
|
16 |
recall_score, |
|
|
17 |
) |
|
|
18 |
from metrics import dice_loss, dice_coef, iou |
|
|
19 |
|
|
|
20 |
""" Creating a directory """ |
|
|
21 |
|
|
|
22 |
|
|
|
23 |
def create_dir(path): |
|
|
24 |
if not os.path.exists(path): |
|
|
25 |
os.makedirs(path) |
|
|
26 |
|
|
|
27 |
|
|
|
28 |
if __name__ == "__main__": |
|
|
29 |
"""Seeding""" |
|
|
30 |
SEEDS = 42 |
|
|
31 |
np.random.seed(SEEDS) |
|
|
32 |
tf.random.set_seed(SEEDS) |
|
|
33 |
|
|
|
34 |
""" Directory for storing files """ |
|
|
35 |
create_dir("test") |
|
|
36 |
|
|
|
37 |
""" Loading model """ |
|
|
38 |
with CustomObjectScope( |
|
|
39 |
{"iou": iou, "dice_coef": dice_coef, "dice_loss": dice_loss} |
|
|
40 |
): |
|
|
41 |
model = tf.keras.models.load_model("files/model.h5") |
|
|
42 |
|
|
|
43 |
""" Load the dataset """ |
|
|
44 |
test_x = glob("data/test/*/*/*.dcm") |
|
|
45 |
print(f"Test: {len(test_x)}") |
|
|
46 |
|
|
|
47 |
""" Loop over the data """ |
|
|
48 |
for x in tqdm(test_x): |
|
|
49 |
"""Extract the Names""" |
|
|
50 |
dir_name = x.split("/")[-3] |
|
|
51 |
name = dir_name + "_" + x.split("/")[-1].split(".")[0] |
|
|
52 |
|
|
|
53 |
""" Read the Image """ |
|
|
54 |
image = dicom.dcmread(x).pixel_array |
|
|
55 |
image = np.expand_dims(image, axis=-1) |
|
|
56 |
image = image / np.max(image) * 255.0 |
|
|
57 |
x = image / 255.0 |
|
|
58 |
x = np.concatenate([x, x, x], axis=-1) |
|
|
59 |
x = np.expand_dims(x, axis=0) |
|
|
60 |
|
|
|
61 |
""" Prediction """ |
|
|
62 |
mask = model.predict(x)[0] |
|
|
63 |
mask = mask > 0.5 |
|
|
64 |
mask = mask.astype(np.int32) |
|
|
65 |
mask = mask * 255 |
|
|
66 |
|
|
|
67 |
cat_images = np.concatenate([image, mask], axis=1) |
|
|
68 |
cv2.imwrite(f"test/{name}.png", cat_images) |