Spaces:
Sleeping
Sleeping
tobotobitobo commited on
Commit ·
c81183f
1
Parent(s): 6b7b8af
working
Browse files- overlays/ISIC_0000001.png +0 -0
- overlays/ISIC_0000003.png +0 -0
- overlays/ISIC_0000008.png +0 -0
- requirements.txt +1 -0
- src/__pycache__/overlay_mask.cpython-311.pyc +0 -0
- src/__pycache__/shownpz.cpython-311.pyc +0 -0
- src/datasets/__pycache__/dataset_isic.cpython-311.pyc +0 -0
- src/datasets/dataset_isic.py +7 -1
- src/organize_test_files.py +29 -0
- src/overlay_mask.py +96 -0
- src/shownpz.py +44 -0
- src/streamlit_app.py +1 -1
- src/test_isic.py +65 -32
- test_log/test_log_ISIC/test_best_model.pth.txt +22 -22
overlays/ISIC_0000001.png
ADDED
|
overlays/ISIC_0000003.png
ADDED
|
overlays/ISIC_0000008.png
ADDED
|
requirements.txt
CHANGED
|
@@ -14,3 +14,4 @@ numpy
|
|
| 14 |
scikit-image
|
| 15 |
scipy
|
| 16 |
tqdm
|
|
|
|
|
|
| 14 |
scikit-image
|
| 15 |
scipy
|
| 16 |
tqdm
|
| 17 |
+
yacs
|
src/__pycache__/overlay_mask.cpython-311.pyc
ADDED
|
Binary file (5.22 kB). View file
|
|
|
src/__pycache__/shownpz.cpython-311.pyc
ADDED
|
Binary file (2.26 kB). View file
|
|
|
src/datasets/__pycache__/dataset_isic.cpython-311.pyc
CHANGED
|
Binary files a/src/datasets/__pycache__/dataset_isic.cpython-311.pyc and b/src/datasets/__pycache__/dataset_isic.cpython-311.pyc differ
|
|
|
src/datasets/dataset_isic.py
CHANGED
|
@@ -55,7 +55,11 @@ class ISIC_dataset(Dataset):
|
|
| 55 |
def __init__(self, base_dir, list_dir, split, transform=None):
|
| 56 |
self.transform = transform
|
| 57 |
self.split = split
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
self.data_dir = base_dir
|
| 60 |
|
| 61 |
def __len__(self):
|
|
@@ -64,6 +68,8 @@ class ISIC_dataset(Dataset):
|
|
| 64 |
def __getitem__(self, idx):
|
| 65 |
slice_name = self.sample_list[idx].strip('\n')
|
| 66 |
data_path = os.path.join(self.data_dir, slice_name + '.npz')
|
|
|
|
|
|
|
| 67 |
data = np.load(data_path)
|
| 68 |
image, label = data['image'], data['label']
|
| 69 |
|
|
|
|
| 55 |
def __init__(self, base_dir, list_dir, split, transform=None):
|
| 56 |
self.transform = transform
|
| 57 |
self.split = split
|
| 58 |
+
list_path = os.path.join(list_dir, f"{self.split}.txt")
|
| 59 |
+
print(f"Looking for list file at: {list_path}") # Debug print
|
| 60 |
+
if not os.path.exists(list_path):
|
| 61 |
+
raise FileNotFoundError(f"List file not found: {list_path}")
|
| 62 |
+
self.sample_list = open(list_path).readlines()
|
| 63 |
self.data_dir = base_dir
|
| 64 |
|
| 65 |
def __len__(self):
|
|
|
|
| 68 |
def __getitem__(self, idx):
|
| 69 |
slice_name = self.sample_list[idx].strip('\n')
|
| 70 |
data_path = os.path.join(self.data_dir, slice_name + '.npz')
|
| 71 |
+
if not os.path.exists(data_path):
|
| 72 |
+
raise FileNotFoundError(f"Data file not found: {data_path}")
|
| 73 |
data = np.load(data_path)
|
| 74 |
image, label = data['image'], data['label']
|
| 75 |
|
src/organize_test_files.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import shutil
|
| 3 |
+
|
| 4 |
+
def organize_test_files():
|
| 5 |
+
# Create test_npz directory if it doesn't exist
|
| 6 |
+
test_dir = os.path.join('datasets', 'test_npz')
|
| 7 |
+
if os.path.exists(test_dir):
|
| 8 |
+
shutil.rmtree(test_dir)
|
| 9 |
+
os.makedirs(test_dir)
|
| 10 |
+
|
| 11 |
+
# Read test.txt to get list of files
|
| 12 |
+
test_list_path = os.path.join('lists', 'ISIC', 'test.txt')
|
| 13 |
+
with open(test_list_path, 'r') as f:
|
| 14 |
+
test_files = [line.strip() for line in f.readlines()]
|
| 15 |
+
|
| 16 |
+
# Source directory containing all npz files
|
| 17 |
+
source_dir = os.path.join('datasets', 'train_npz')
|
| 18 |
+
|
| 19 |
+
# Copy each file to test_npz directory
|
| 20 |
+
for file_name in test_files:
|
| 21 |
+
source_file = os.path.join(source_dir, file_name + '.npz')
|
| 22 |
+
if os.path.exists(source_file):
|
| 23 |
+
shutil.copy2(source_file, os.path.join(test_dir, file_name + '.npz'))
|
| 24 |
+
print(f"Copied {file_name}.npz")
|
| 25 |
+
else:
|
| 26 |
+
print(f"Warning: {file_name}.npz not found in source directory")
|
| 27 |
+
|
| 28 |
+
if __name__ == "__main__":
|
| 29 |
+
organize_test_files()
|
src/overlay_mask.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import matplotlib.pyplot as plt
|
| 3 |
+
import os
|
| 4 |
+
import argparse
|
| 5 |
+
from PIL import Image
|
| 6 |
+
|
| 7 |
+
def save_image(image, save_path):
|
| 8 |
+
"""
|
| 9 |
+
Save image as PNG
|
| 10 |
+
Args:
|
| 11 |
+
image: Image array
|
| 12 |
+
save_path: Path to save the image
|
| 13 |
+
"""
|
| 14 |
+
plt.figure(figsize=(10, 10))
|
| 15 |
+
plt.imshow(image)
|
| 16 |
+
plt.axis('off')
|
| 17 |
+
plt.savefig(save_path, bbox_inches='tight', pad_inches=0)
|
| 18 |
+
plt.close()
|
| 19 |
+
|
| 20 |
+
def overlay_mask(image, mask, save_path, alpha=0.5):
|
| 21 |
+
"""
|
| 22 |
+
Overlay mask on original image
|
| 23 |
+
Args:
|
| 24 |
+
image: Original image (numpy array)
|
| 25 |
+
mask: Mask (numpy array)
|
| 26 |
+
save_path: Path to save the visualization
|
| 27 |
+
alpha: Transparency of the mask overlay (0-1)
|
| 28 |
+
"""
|
| 29 |
+
plt.figure(figsize=(10, 10))
|
| 30 |
+
|
| 31 |
+
# Normalize image to 0-1 range if needed
|
| 32 |
+
if image.max() > 1:
|
| 33 |
+
image = image / 255.0
|
| 34 |
+
|
| 35 |
+
# Show original image
|
| 36 |
+
plt.imshow(image)
|
| 37 |
+
|
| 38 |
+
# Remove extra dimension from mask if present
|
| 39 |
+
if len(mask.shape) == 3:
|
| 40 |
+
mask = mask.squeeze()
|
| 41 |
+
|
| 42 |
+
# Overlay mask with transparency
|
| 43 |
+
plt.imshow(mask, alpha=alpha, cmap='gray')
|
| 44 |
+
|
| 45 |
+
plt.axis('off')
|
| 46 |
+
plt.savefig(save_path, bbox_inches='tight', pad_inches=0)
|
| 47 |
+
plt.close()
|
| 48 |
+
|
| 49 |
+
def main():
|
| 50 |
+
parser = argparse.ArgumentParser()
|
| 51 |
+
parser.add_argument('--image_npz', type=str, required=True, help='path to npz file containing the image')
|
| 52 |
+
parser.add_argument('--mask_npy', type=str, required=True, help='path to npy file containing the mask')
|
| 53 |
+
parser.add_argument('--output_dir', type=str, default='overlays', help='output directory for overlays')
|
| 54 |
+
parser.add_argument('--alpha', type=float, default=0.1, help='transparency of mask overlay (0-1)')
|
| 55 |
+
args = parser.parse_args()
|
| 56 |
+
|
| 57 |
+
# Create output directory if it doesn't exist
|
| 58 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 59 |
+
|
| 60 |
+
# Load image from NPZ file
|
| 61 |
+
image_data = np.load(args.image_npz)
|
| 62 |
+
image = image_data['image']
|
| 63 |
+
|
| 64 |
+
# Load mask from NPY file
|
| 65 |
+
mask = np.load(args.mask_npy)
|
| 66 |
+
|
| 67 |
+
# Handle image shape and resize
|
| 68 |
+
if len(image.shape) == 3:
|
| 69 |
+
if image.shape[0] == 1: # If first dimension is 1
|
| 70 |
+
image = image.squeeze(0) # Remove it
|
| 71 |
+
if image.shape[0] == 3: # If channels first
|
| 72 |
+
image = np.transpose(image, (1, 2, 0)) # Change to channels last
|
| 73 |
+
|
| 74 |
+
# Convert to PIL Image and resize
|
| 75 |
+
image = (image * 255).astype(np.uint8)
|
| 76 |
+
if len(image.shape) == 2: # If grayscale
|
| 77 |
+
image = np.stack([image] * 3, axis=-1) # Convert to RGB
|
| 78 |
+
image = Image.fromarray(image)
|
| 79 |
+
image = image.resize((224, 224), Image.Resampling.LANCZOS)
|
| 80 |
+
image = np.array(image) / 255.0
|
| 81 |
+
|
| 82 |
+
# Create output filenames
|
| 83 |
+
base_name = os.path.splitext(os.path.basename(args.image_npz))[0]
|
| 84 |
+
original_save_path = os.path.join(args.output_dir, f'{base_name}_original.png')
|
| 85 |
+
overlay_save_path = os.path.join(args.output_dir, f'{base_name}_overlay.png')
|
| 86 |
+
|
| 87 |
+
# Save original image
|
| 88 |
+
save_image(image, original_save_path)
|
| 89 |
+
print(f'Saved original image to {original_save_path}')
|
| 90 |
+
|
| 91 |
+
# Create and save overlay
|
| 92 |
+
overlay_mask(image, mask, overlay_save_path, args.alpha)
|
| 93 |
+
print(f'Saved overlay to {overlay_save_path}')
|
| 94 |
+
|
| 95 |
+
if __name__ == '__main__':
|
| 96 |
+
main()
|
src/shownpz.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cv2
|
| 2 |
+
import numpy as np
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
def draw_mask(image, mask_generated):
|
| 7 |
+
# Ensure image is in the right format (H, W, C)
|
| 8 |
+
if len(image.shape) == 3 and image.shape[0] == 3: # If channels first
|
| 9 |
+
image = np.transpose(image, (1, 2, 0)) # Change to channels last
|
| 10 |
+
|
| 11 |
+
# Remove any extra dimensions
|
| 12 |
+
image = image.squeeze()
|
| 13 |
+
mask_generated = mask_generated.squeeze()
|
| 14 |
+
|
| 15 |
+
# Ensure image is 2D or 3D
|
| 16 |
+
if len(image.shape) == 1:
|
| 17 |
+
raise ValueError(f"Unexpected image shape: {image.shape}")
|
| 18 |
+
|
| 19 |
+
# If image is 2D, convert to 3D (grayscale to RGB)
|
| 20 |
+
if len(image.shape) == 2:
|
| 21 |
+
image = np.stack([image] * 3, axis=-1)
|
| 22 |
+
|
| 23 |
+
# Normalize image to 0-255 range if needed
|
| 24 |
+
if image.max() <= 1:
|
| 25 |
+
image = (image * 255).astype(np.uint8)
|
| 26 |
+
|
| 27 |
+
# Create colored mask
|
| 28 |
+
colored_mask = np.zeros_like(image)
|
| 29 |
+
colored_mask[mask_generated.astype(bool)] = [0, 255, 0] # BGR (nie RGB!)
|
| 30 |
+
|
| 31 |
+
# Blend the image and mask
|
| 32 |
+
blended = cv2.addWeighted(image, 0.9, colored_mask, 0.1, 0)
|
| 33 |
+
|
| 34 |
+
return Image.fromarray(blended.astype(np.uint8))
|
| 35 |
+
|
| 36 |
+
def make_overlay(image, mask, save_path):
|
| 37 |
+
# Ensure the directory exists
|
| 38 |
+
os.makedirs(os.path.dirname(save_path), exist_ok=True)
|
| 39 |
+
|
| 40 |
+
# Create overlay
|
| 41 |
+
overlay = draw_mask(image, mask)
|
| 42 |
+
|
| 43 |
+
# Save the result
|
| 44 |
+
overlay.save(save_path)
|
src/streamlit_app.py
CHANGED
|
@@ -31,7 +31,7 @@ if st.button('Test Model'):
|
|
| 31 |
st.code(result.stderr)
|
| 32 |
|
| 33 |
# Optionally, display the latest log file
|
| 34 |
-
log_dir = os.path.join('
|
| 35 |
if os.path.exists(log_dir):
|
| 36 |
log_files = sorted([f for f in os.listdir(log_dir) if f.endswith('.txt')], reverse=True)
|
| 37 |
if log_files:
|
|
|
|
| 31 |
st.code(result.stderr)
|
| 32 |
|
| 33 |
# Optionally, display the latest log file
|
| 34 |
+
log_dir = os.path.join('test_log', 'test_log_ISIC')
|
| 35 |
if os.path.exists(log_dir):
|
| 36 |
log_files = sorted([f for f in os.listdir(log_dir) if f.endswith('.txt')], reverse=True)
|
| 37 |
if log_files:
|
src/test_isic.py
CHANGED
|
@@ -3,6 +3,7 @@ import logging
|
|
| 3 |
import os
|
| 4 |
import random
|
| 5 |
import sys
|
|
|
|
| 6 |
|
| 7 |
import numpy as np
|
| 8 |
import torch
|
|
@@ -16,9 +17,12 @@ from datasets.dataset_isic import ISIC_dataset, RandomGenerator
|
|
| 16 |
from networks.vision_transformer import SwinUnet as ViT_seg
|
| 17 |
from utils import test_single_volume
|
| 18 |
|
|
|
|
|
|
|
|
|
|
| 19 |
parser = argparse.ArgumentParser()
|
| 20 |
parser.add_argument('--root_path', type=str,
|
| 21 |
-
default='datasets/
|
| 22 |
help='root dir for test data')
|
| 23 |
parser.add_argument('--dataset', type=str,
|
| 24 |
default='ISIC', help='experiment_name')
|
|
@@ -66,7 +70,26 @@ args = parser.parse_args()
|
|
| 66 |
|
| 67 |
config = get_config(args)
|
| 68 |
|
| 69 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
image = image.cuda()
|
| 71 |
label = label.cuda()
|
| 72 |
with torch.no_grad():
|
|
@@ -81,17 +104,18 @@ def test_single_image(image, label, model, classes, patch_size, test_save_path=N
|
|
| 81 |
metric_list = []
|
| 82 |
for i in range(1, classes):
|
| 83 |
metric_list.append(calculate_metric_percase(pred == i, label == i))
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
|
| 89 |
return metric_list
|
| 90 |
|
| 91 |
def calculate_metric_percase(pred, gt):
|
| 92 |
dice = calculate_dice(pred, gt)
|
| 93 |
-
|
| 94 |
-
|
|
|
|
| 95 |
|
| 96 |
def calculate_dice(pred, gt):
|
| 97 |
pred = pred.astype(np.float32)
|
|
@@ -100,10 +124,19 @@ def calculate_dice(pred, gt):
|
|
| 100 |
dice = (2. * intersection) / (np.sum(pred) + np.sum(gt) + 1e-5)
|
| 101 |
return dice
|
| 102 |
|
| 103 |
-
def
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
def inference(args, model, test_save_path=None):
|
| 109 |
# Create transform for resizing images
|
|
@@ -114,23 +147,34 @@ def inference(args, model, test_save_path=None):
|
|
| 114 |
logging.info("{} test iterations per epoch".format(len(testloader)))
|
| 115 |
model.eval()
|
| 116 |
metric_list = 0.0
|
|
|
|
|
|
|
| 117 |
for i_batch, sampled_batch in tqdm(enumerate(testloader)):
|
| 118 |
image, label, case_name = sampled_batch["image"], sampled_batch["label"], sampled_batch['case_name'][0]
|
| 119 |
metric_i = test_single_image(image, label, model, classes=args.num_classes,
|
| 120 |
patch_size=[args.img_size, args.img_size],
|
| 121 |
-
test_save_path=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
metric_list += np.array(metric_i)
|
| 123 |
-
logging.info('idx %d case %s mean_dice %f
|
| 124 |
-
i_batch, case_name, np.mean(metric_i, axis=0)[0], np.mean(metric_i, axis=0)[1]))
|
| 125 |
metric_list = metric_list / len(db_test)
|
| 126 |
for i in range(1, args.num_classes):
|
| 127 |
-
logging.info('Mean class %d mean_dice %f
|
| 128 |
performance = np.mean(metric_list, axis=0)[0]
|
| 129 |
-
|
| 130 |
-
|
|
|
|
| 131 |
return "Testing Finished!"
|
| 132 |
|
| 133 |
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
| 134 |
if not args.deterministic:
|
| 135 |
cudnn.benchmark = True
|
| 136 |
cudnn.deterministic = False
|
|
@@ -146,15 +190,13 @@ if __name__ == "__main__":
|
|
| 146 |
dataset_config = {
|
| 147 |
'ISIC': {
|
| 148 |
'root_path': args.root_path,
|
| 149 |
-
'list_dir':
|
| 150 |
'num_classes': args.n_class,
|
| 151 |
},
|
| 152 |
}
|
| 153 |
args.num_classes = dataset_config[dataset_name]['num_classes']
|
| 154 |
args.root_path = dataset_config[dataset_name]['root_path']
|
| 155 |
-
|
| 156 |
-
if args.list_dir == './lists/lists_ISIC' or args.list_dir == f'./lists/{args.dataset}':
|
| 157 |
-
args.list_dir = dataset_config[dataset_name]['list_dir']
|
| 158 |
args.is_pretrain = True
|
| 159 |
|
| 160 |
net = ViT_seg(config, img_size=args.img_size, num_classes=args.num_classes).cuda()
|
|
@@ -180,13 +222,4 @@ if __name__ == "__main__":
|
|
| 180 |
logging.info(str(args))
|
| 181 |
logging.info(snapshot_name)
|
| 182 |
|
| 183 |
-
|
| 184 |
-
args.test_save_dir = os.path.join(args.output_dir, "predictions")
|
| 185 |
-
test_save_path = args.test_save_dir
|
| 186 |
-
os.makedirs(test_save_path, exist_ok=True)
|
| 187 |
-
else:
|
| 188 |
-
test_save_path = None
|
| 189 |
-
inference(args, net, test_save_path)
|
| 190 |
-
|
| 191 |
-
# Example command to run the test:
|
| 192 |
-
# python test_isic.py --dataset ISIC --cfg configs/swin_tiny_patch4_window7_224_lite.yaml --is_savenii --root_path datasets/train_npz --output_dir outputs --max_epochs 150 --base_lr 0.05 --img_size 224 --batch_size 24
|
|
|
|
| 3 |
import os
|
| 4 |
import random
|
| 5 |
import sys
|
| 6 |
+
import shutil
|
| 7 |
|
| 8 |
import numpy as np
|
| 9 |
import torch
|
|
|
|
| 17 |
from networks.vision_transformer import SwinUnet as ViT_seg
|
| 18 |
from utils import test_single_volume
|
| 19 |
|
| 20 |
+
from overlay_mask import overlay_mask
|
| 21 |
+
from shownpz import make_overlay
|
| 22 |
+
|
| 23 |
parser = argparse.ArgumentParser()
|
| 24 |
parser.add_argument('--root_path', type=str,
|
| 25 |
+
default='datasets/test_npz',
|
| 26 |
help='root dir for test data')
|
| 27 |
parser.add_argument('--dataset', type=str,
|
| 28 |
default='ISIC', help='experiment_name')
|
|
|
|
| 70 |
|
| 71 |
config = get_config(args)
|
| 72 |
|
| 73 |
+
def cleanup_previous_results():
|
| 74 |
+
"""Clean up previous test results"""
|
| 75 |
+
# Clean up outputs directory
|
| 76 |
+
if os.path.exists('outputs'):
|
| 77 |
+
shutil.rmtree('outputs')
|
| 78 |
+
|
| 79 |
+
# Clean up overlays directory
|
| 80 |
+
if os.path.exists('overlays'):
|
| 81 |
+
shutil.rmtree('overlays')
|
| 82 |
+
|
| 83 |
+
# Clean up test_log directory
|
| 84 |
+
if os.path.exists('test_log'):
|
| 85 |
+
shutil.rmtree('test_log')
|
| 86 |
+
|
| 87 |
+
# Create fresh directories
|
| 88 |
+
os.makedirs('outputs', exist_ok=True)
|
| 89 |
+
os.makedirs('overlays', exist_ok=True)
|
| 90 |
+
os.makedirs('test_log', exist_ok=True)
|
| 91 |
+
|
| 92 |
+
def test_single_image(image, label, model, classes, patch_size, test_save_path=None, case=None, overlay_count=None):
|
| 93 |
image = image.cuda()
|
| 94 |
label = label.cuda()
|
| 95 |
with torch.no_grad():
|
|
|
|
| 104 |
metric_list = []
|
| 105 |
for i in range(1, classes):
|
| 106 |
metric_list.append(calculate_metric_percase(pred == i, label == i))
|
| 107 |
+
|
| 108 |
+
# Only save overlay for first 3 images
|
| 109 |
+
if overlay_count is not None and overlay_count < 3:
|
| 110 |
+
make_overlay(image.cpu().numpy().squeeze(0), pred, "overlays/" + case + ".png")
|
| 111 |
|
| 112 |
return metric_list
|
| 113 |
|
| 114 |
def calculate_metric_percase(pred, gt):
|
| 115 |
dice = calculate_dice(pred, gt)
|
| 116 |
+
acc = calculate_accuracy(pred, gt)
|
| 117 |
+
iou = calculate_iou(pred, gt)
|
| 118 |
+
return dice, acc, iou
|
| 119 |
|
| 120 |
def calculate_dice(pred, gt):
|
| 121 |
pred = pred.astype(np.float32)
|
|
|
|
| 124 |
dice = (2. * intersection) / (np.sum(pred) + np.sum(gt) + 1e-5)
|
| 125 |
return dice
|
| 126 |
|
| 127 |
+
def calculate_accuracy(pred, gt):
|
| 128 |
+
pred = pred.astype(np.float32)
|
| 129 |
+
gt = gt.astype(np.float32)
|
| 130 |
+
correct_pixels = np.sum(pred == gt)
|
| 131 |
+
total_pixels = gt.size
|
| 132 |
+
accuracy = correct_pixels / total_pixels
|
| 133 |
+
return accuracy
|
| 134 |
+
|
| 135 |
+
def calculate_iou(pred, gt):
|
| 136 |
+
intersection = np.logical_and(pred, gt).sum()
|
| 137 |
+
union = np.logical_or(pred, gt).sum()
|
| 138 |
+
iou = intersection / union if union != 0 else 0.0
|
| 139 |
+
return iou
|
| 140 |
|
| 141 |
def inference(args, model, test_save_path=None):
|
| 142 |
# Create transform for resizing images
|
|
|
|
| 147 |
logging.info("{} test iterations per epoch".format(len(testloader)))
|
| 148 |
model.eval()
|
| 149 |
metric_list = 0.0
|
| 150 |
+
overlay_count = 0 # Counter for overlays
|
| 151 |
+
|
| 152 |
for i_batch, sampled_batch in tqdm(enumerate(testloader)):
|
| 153 |
image, label, case_name = sampled_batch["image"], sampled_batch["label"], sampled_batch['case_name'][0]
|
| 154 |
metric_i = test_single_image(image, label, model, classes=args.num_classes,
|
| 155 |
patch_size=[args.img_size, args.img_size],
|
| 156 |
+
test_save_path=None, # Don't save masks
|
| 157 |
+
case=case_name,
|
| 158 |
+
overlay_count=overlay_count)
|
| 159 |
+
if overlay_count < 3:
|
| 160 |
+
overlay_count += 1
|
| 161 |
+
|
| 162 |
metric_list += np.array(metric_i)
|
| 163 |
+
logging.info('idx %d case %s mean_dice %f mean_acc %f mean_iou %f' % (
|
| 164 |
+
i_batch, case_name, np.mean(metric_i, axis=0)[0], np.mean(metric_i, axis=0)[1], np.mean(metric_i, axis=0)[2]))
|
| 165 |
metric_list = metric_list / len(db_test)
|
| 166 |
for i in range(1, args.num_classes):
|
| 167 |
+
logging.info('Mean class %d mean_dice %f mean_acc %f mean_iou %f' % (i, metric_list[i - 1][0], metric_list[i - 1][1], np.mean(metric_i, axis=0)[2]))
|
| 168 |
performance = np.mean(metric_list, axis=0)[0]
|
| 169 |
+
mean_acc = np.mean(metric_list, axis=0)[1]
|
| 170 |
+
mean_iou = np.mean(metric_list, axis=0)[2]
|
| 171 |
+
logging.info('Testing performance in best val model: mean_dice : %f mean_acc : %f mean_iou %f' % (performance, mean_acc, mean_iou))
|
| 172 |
return "Testing Finished!"
|
| 173 |
|
| 174 |
if __name__ == "__main__":
|
| 175 |
+
# Clean up previous results before starting new test
|
| 176 |
+
cleanup_previous_results()
|
| 177 |
+
|
| 178 |
if not args.deterministic:
|
| 179 |
cudnn.benchmark = True
|
| 180 |
cudnn.deterministic = False
|
|
|
|
| 190 |
dataset_config = {
|
| 191 |
'ISIC': {
|
| 192 |
'root_path': args.root_path,
|
| 193 |
+
'list_dir': os.path.join('src', 'lists', args.dataset),
|
| 194 |
'num_classes': args.n_class,
|
| 195 |
},
|
| 196 |
}
|
| 197 |
args.num_classes = dataset_config[dataset_name]['num_classes']
|
| 198 |
args.root_path = dataset_config[dataset_name]['root_path']
|
| 199 |
+
args.list_dir = dataset_config[dataset_name]['list_dir']
|
|
|
|
|
|
|
| 200 |
args.is_pretrain = True
|
| 201 |
|
| 202 |
net = ViT_seg(config, img_size=args.img_size, num_classes=args.num_classes).cuda()
|
|
|
|
| 222 |
logging.info(str(args))
|
| 223 |
logging.info(snapshot_name)
|
| 224 |
|
| 225 |
+
inference(args, net)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
test_log/test_log_ISIC/test_best_model.pth.txt
CHANGED
|
@@ -1,22 +1,22 @@
|
|
| 1 |
-
[22:
|
| 2 |
-
[22:
|
| 3 |
-
[22:
|
| 4 |
-
[22:
|
| 5 |
-
[22:
|
| 6 |
-
[22:
|
| 7 |
-
[22:
|
| 8 |
-
[22:
|
| 9 |
-
[22:
|
| 10 |
-
[22:
|
| 11 |
-
[22:
|
| 12 |
-
[22:
|
| 13 |
-
[22:
|
| 14 |
-
[22:
|
| 15 |
-
[22:
|
| 16 |
-
[22:
|
| 17 |
-
[22:
|
| 18 |
-
[22:
|
| 19 |
-
[22:
|
| 20 |
-
[22:
|
| 21 |
-
[22:
|
| 22 |
-
[22:
|
|
|
|
| 1 |
+
[22:50:31.836] Namespace(root_path='src/datasets/test_npz', dataset='ISIC', num_classes=2, list_dir='src\\lists\\ISIC', output_dir='src/outputs', max_iterations=30000, max_epochs=150, batch_size=24, img_size=224, is_savenii=True, test_save_dir='predictions', deterministic=1, base_lr=0.05, seed=1234, cfg='src/configs/swin_tiny_patch4_window7_224_lite.yaml', opts=None, zip=False, cache_mode='part', resume=None, accumulation_steps=None, use_checkpoint=False, amp_opt_level='O1', tag=None, eval=False, throughput=False, n_class=2, split_name='test', is_pretrain=True)
|
| 2 |
+
[22:50:31.836] best_model.pth
|
| 3 |
+
[22:50:31.846] 17 test iterations per epoch
|
| 4 |
+
[22:50:42.989] idx 0 case ISIC_0000001 mean_dice 0.925362 mean_acc 0.988381 mean_iou 0.861091
|
| 5 |
+
[22:50:43.177] idx 1 case ISIC_0000003 mean_dice 0.960937 mean_acc 0.972477 mean_iou 0.924811
|
| 6 |
+
[22:50:43.342] idx 2 case ISIC_0000008 mean_dice 0.974235 mean_acc 0.982163 mean_iou 0.949764
|
| 7 |
+
[22:50:43.495] idx 3 case ISIC_0000011 mean_dice 0.965687 mean_acc 0.987185 mean_iou 0.933650
|
| 8 |
+
[22:50:43.844] idx 4 case ISIC_0000016 mean_dice 0.972417 mean_acc 0.988142 mean_iou 0.946314
|
| 9 |
+
[22:50:44.085] idx 5 case ISIC_0000017 mean_dice 0.960936 mean_acc 0.987285 mean_iou 0.924808
|
| 10 |
+
[22:50:44.405] idx 6 case ISIC_0000025 mean_dice 0.928897 mean_acc 0.969547 mean_iou 0.867234
|
| 11 |
+
[22:50:44.792] idx 7 case ISIC_0000029 mean_dice 0.966497 mean_acc 0.972915 mean_iou 0.935165
|
| 12 |
+
[22:50:45.088] idx 8 case ISIC_0000032 mean_dice 0.968455 mean_acc 0.979532 mean_iou 0.938840
|
| 13 |
+
[22:50:45.431] idx 9 case ISIC_0000036 mean_dice 0.837651 mean_acc 0.848234 mean_iou 0.720653
|
| 14 |
+
[22:50:45.830] idx 10 case ISIC_0000042 mean_dice 0.952283 mean_acc 0.966757 mean_iou 0.908912
|
| 15 |
+
[22:50:46.124] idx 11 case ISIC_0000043 mean_dice 0.934522 mean_acc 0.943638 mean_iou 0.877092
|
| 16 |
+
[22:50:46.445] idx 12 case ISIC_0000051 mean_dice 0.971923 mean_acc 0.983498 mean_iou 0.945379
|
| 17 |
+
[22:50:46.779] idx 13 case ISIC_0000064 mean_dice 0.980977 mean_acc 0.986846 mean_iou 0.962663
|
| 18 |
+
[22:50:47.095] idx 14 case ISIC_0000087 mean_dice 0.972324 mean_acc 0.978675 mean_iou 0.946139
|
| 19 |
+
[22:50:47.399] idx 15 case ISIC_0000095 mean_dice 0.911183 mean_acc 0.985232 mean_iou 0.836856
|
| 20 |
+
[22:50:47.718] idx 16 case ISIC_0000105 mean_dice 0.944544 mean_acc 0.992008 mean_iou 0.894916
|
| 21 |
+
[22:50:49.317] Mean class 1 mean_dice 0.948755 mean_acc 0.971324 mean_iou 0.894916
|
| 22 |
+
[22:50:49.317] Testing performance in best val model: mean_dice : 0.948755 mean_acc : 0.971324 mean_iou 0.904370
|