backup / DiffAtlas /test /evaluate.py
kanydao's picture
Resume DiffAtlas backup after packing large Label directories (part 53)
5471715 verified
Raw
History Blame Contribute Delete
15.9 kB
import os
import io
import blobfile as bf
import torch as th
import sys
parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
sys.path.insert(0, parent_dir)
from ddpm import Unet3D, GaussianDiffusion_Nolatent
from Dataset.TS_Dataset import get_TS_dataloader
from Dataset.MMWHS_Dataset import get_MMWHS_dataloader
import torchio as tio
from omegaconf import DictConfig
import hydra
import numpy as np
import torch
from omegaconf import OmegaConf
import atexit
import torch.nn as nn
import torch.nn.functional as F
import scipy.ndimage as ndimage
from scipy.ndimage import distance_transform_edt
from datetime import datetime
import time
def squeeze_and_expand(img, num_slice=32):
original_shape = img.shape[2:]
original_img = img.clone()
step = img.shape[2] // num_slice
img = img[...,::step, :, :]
img = F.interpolate(img, size=original_shape, mode='trilinear', align_corners=False)
img[...,::step, :, :] = original_img[...,::step, :, :]
return img
def zoom_in_and_out(img, zoom_factor=2):
original_shape = img.shape[2:]
original_img = img.clone()
new_shape = (int(original_shape[0] // zoom_factor),
int(original_shape[1] // zoom_factor),
int(original_shape[2] // zoom_factor))
img = F.interpolate(img, size=new_shape, mode='trilinear', align_corners=False)
img = F.interpolate(img, size=original_shape, mode='trilinear', align_corners=False)
img[..., ::zoom_factor, ::zoom_factor, ::zoom_factor] = original_img[..., ::zoom_factor, ::zoom_factor, ::zoom_factor]
return img
def degrade_img_only(img, degrade_type):
if degrade_type == 'none':
return img
elif degrade_type == 'res32':
return squeeze_and_expand(img, num_slice=32)
elif degrade_type == 'res16':
return squeeze_and_expand(img, num_slice=16)
elif degrade_type == 'res8':
return squeeze_and_expand(img, num_slice=8)
elif degrade_type == 'res4':
return squeeze_and_expand(img, num_slice=4)
elif degrade_type == 'vol32':
return zoom_in_and_out(img, zoom_factor=2)
elif degrade_type == 'vol16':
return zoom_in_and_out(img, zoom_factor=4)
elif degrade_type == 'vol8':
return zoom_in_and_out(img, zoom_factor=8)
elif degrade_type == 'vol4':
return zoom_in_and_out(img, zoom_factor=16)
else:
return img
def get_degrade_mask(degrade_type):
mask = torch.zeros((1, 1, 64, 64, 64), dtype=torch.float32)
if degrade_type == 'none':
mask[...] = 1
elif degrade_type == 'res32':
step = 2
mask[0, 0, ::step, :, :] = 1
elif degrade_type == 'res16':
step = 4
mask[0, 0, ::step, :, :] = 1
elif degrade_type == 'res8':
step = 8
mask[0, 0, ::step, :, :] = 1
elif degrade_type == 'res4':
step = 16
mask[0, 0, ::step, :, :] = 1
elif degrade_type == '2d':
mask[0, 0, 32, :, :] = 1
elif degrade_type == 'mid4':
width = 4
mask[0, 0, 32-width//2:32+width//2, :, :] = 1
mask = 1 - mask
elif degrade_type == 'mid8':
width = 8
mask[0, 0, 32-width//2:32+width//2, :, :] = 1
mask = 1 - mask
elif degrade_type == 'mid16':
width = 16
mask[0, 0, 32-width//2:32+width//2, :, :] = 1
mask = 1 - mask
elif degrade_type == 'mid32':
width = 32
mask[0, 0, 32-width//2:32+width//2, :, :] = 1
mask = 1 - mask
elif degrade_type == 'mid64':
width = 64
mask[0, 0, 32-width//2:32+width//2, :, :] = 1
mask = 1 - mask
elif degrade_type == 'none':
mask[...] = 1
elif degrade_type == 'vol32':
mask[0, 0, ::2, ::2, ::2] = 1
elif degrade_type == 'vol16':
mask[0, 0, ::4, ::4, ::4] = 1
elif degrade_type == 'vol8':
mask[0, 0, ::8, ::8, ::8] = 1
else:
raise ValueError("Invalid degrade type")
return mask
def dev(device):
if device is None:
if th.cuda.is_available():
return th.device(f"cuda")
return th.device("cpu")
return th.device(device)
def load_state_dict(path, backend=None, **kwargs):
with bf.BlobFile(path, "rb") as f:
data = f.read()
return th.load(io.BytesIO(data), **kwargs)
try:
import ctypes
libgcc_s = ctypes.CDLL('libgcc_s.so.1')
except:
pass
def get_dice(preds, labels):
assert preds.shape[0] == labels.shape[0], "predict & target batch size don't match"
predict = preds.reshape(preds.shape[0], -1)
target = labels.reshape(labels.shape[0], -1)
if np.sum(target) == 0 and np.sum(predict) == 0:
return 1.0
else:
num = np.sum(np.multiply(predict, target), axis=1)
den = np.sum(predict, axis=1) + np.sum(target, axis=1)
dice = 2 * num / den
return dice.mean()
def ignore_background(y_pred: torch.Tensor, y: torch.Tensor):
return y_pred[:, 1:], y[:, 1:]
def prepare_spacing(spacing, batch_size, img_dim):
if spacing is None:
spacing = tuple([1.0] * img_dim)
if isinstance(spacing, (int, float)):
spacing = tuple([float(spacing)] * img_dim)
elif isinstance(spacing, (tuple, list)):
if len(spacing) == 1:
spacing = tuple([float(spacing[0])] * img_dim)
elif len(spacing) == img_dim:
spacing = tuple(float(s) for s in spacing)
else:
raise ValueError("spacing should be a number or sequence of numbers matching image dimensions")
return [spacing] * batch_size
def get_edge_surface_distance(pred, gt, distance_metric="euclidean", spacing=None, use_subvoxels=False, symmetric=True, class_index=None):
pred = pred.cpu().numpy().astype(bool)
gt = gt.cpu().numpy().astype(bool)
edges_pred = ndimage.binary_dilation(pred).astype(bool) ^ pred
edges_gt = ndimage.binary_dilation(gt).astype(bool) ^ gt
if distance_metric == "euclidean":
dt_pred = distance_transform_edt(~edges_pred, sampling=spacing)
dt_gt = distance_transform_edt(~edges_gt, sampling=spacing)
else:
raise ValueError(f"Unsupported distance metric: {distance_metric}")
distances_pred_gt = dt_gt[edges_pred]
distances_gt_pred = dt_pred[edges_gt]
areas = None
return (edges_pred, edges_gt), (distances_pred_gt, distances_gt_pred), areas
def compute_surface_dice(y_pred, y, class_thresholds, include_background=False,
distance_metric="euclidean", spacing=None, use_subvoxels=False):
if not include_background:
y_pred, y = ignore_background(y_pred=y_pred, y=y)
if not isinstance(y_pred, torch.Tensor) or not isinstance(y, torch.Tensor):
raise ValueError("y_pred and y must be PyTorch Tensor.")
if y_pred.ndimension() not in (4, 5) or y.ndimension() not in (4, 5):
raise ValueError("y_pred and y should be one-hot encoded: [B,C,H,W] or [B,C,H,W,D].")
if y_pred.shape != y.shape:
raise ValueError(
f"y_pred and y should have same shape, but instead, shapes are {y_pred.shape} (y_pred) and {y.shape} (y)."
)
batch_size, n_class = y_pred.shape[:2]
img_dim = y_pred.ndim - 2
spacing_list = prepare_spacing(spacing=spacing, batch_size=batch_size, img_dim=img_dim)
nsd = torch.empty((batch_size, n_class), device=y_pred.device, dtype=torch.float)
for b, c in np.ndindex(batch_size, n_class):
(edges_pred, edges_gt), (distances_pred_gt, distances_gt_pred), areas = get_edge_surface_distance(
y_pred[b, c],
y[b, c],
distance_metric=distance_metric,
spacing=spacing_list[b],
use_subvoxels=use_subvoxels,
symmetric=True,
class_index=c,
)
boundary_complete = len(distances_pred_gt) + len(distances_gt_pred)
boundary_correct = torch.sum(torch.tensor(distances_pred_gt <= class_thresholds[c])) + \
torch.sum(torch.tensor(distances_gt_pred <= class_thresholds[c]))
if boundary_complete == 0:
nsd[b, c] = torch.tensor(float('nan'))
else:
nsd[b, c] = boundary_correct / boundary_complete
return nsd
class NSDMetric(nn.Module):
def __init__(self, n_classes):
super(NSDMetric, self).__init__()
self.n_classes = n_classes
self.class_thresholds = [1.0] * n_classes
def forward(self, inputs, target, spacing=(1.0, 1.0, 1.0), softmax=False):
if softmax:
inputs = torch.softmax(inputs, dim=1)
inputs = F.one_hot(inputs, num_classes=self.n_classes).permute(0, 4, 1, 2, 3).float()
target = F.one_hot(target, num_classes=self.n_classes).permute(0, 4, 1, 2, 3).float()
nsd_scores = compute_surface_dice(
inputs,
target,
class_thresholds=self.class_thresholds,
include_background=False,
spacing=spacing
)
return nsd_scores[0]
class Tee:
def __init__(self, *files):
self.files = files
def write(self, obj):
for f in self.files:
f.write(obj)
f.flush()
def flush(self):
for f in self.files:
f.flush()
def generate_results(dataloader, diffusion, device, conf):
if conf.degrade_type.endswith('_img'):
conf.degrade_type = conf.degrade_type[:-4]
degrade_mask = get_degrade_mask(conf.degrade_type)
degrade_img = True
elif conf.degrade_type.startswith('vol'):
degrade_mask = get_degrade_mask(conf.degrade_type)
degrade_img = True
else:
degrade_mask = get_degrade_mask(conf.degrade_type)
degrade_img = False
print(f"Degrade type: {conf.degrade_type}, Degrade img: {degrade_img}")
for batch in iter(dataloader):
begin = time.time()
for k in batch.keys():
if isinstance(batch[k], th.Tensor):
batch[k] = batch[k].to(device)
affine = batch['affine'].squeeze(0).cpu()
real_image = batch["img"]
real_mask = batch.get('mask').cpu()
real_mask_sdf = batch.get('mask_sdf').cpu()
gt_name = batch['name']
if degrade_img:
real_image = degrade_img_only(real_image, conf.degrade_type)
# gt_name = gt_name.split('_image')[0]
# gt_name = gt_name.split('-image')[0]
print(f"Generating for {gt_name}")
# sample_fn = diffusion.p_sample_loop
sample_fn = diffusion.p_sample_loop_universal_guidance
result = sample_fn(
shape_image=real_image.size(),
shape_mask=real_mask_sdf.size(),
device=device,
image=real_image,
degrade_mask=degrade_mask,
# delta=conf.delta,
guidance_scale=0.5,
use_ddim=False,
guidance_start_t=150,
guidance_strategy='last_n',
)
gen_image = result[:, 0, :, :, :].cpu()
gen_mask = result[:, 1:(result.size()[1]), :, :, :].cpu()
for b in range(real_image.size(0)):
name = gt_name[b].split('_image')[0]
res = [real_image[b:b+1], real_mask[b:b+1], gen_image[b:b+1], gen_mask[b:b+1], name]
os.makedirs(conf.target_path, exist_ok=True)
torch.save(res, os.path.join(conf.target_path, f"{name}.pt"))
end = time.time()
print(f"exp_dir: {conf.target_path}")
print(f"Time per batch: {end - begin:.2f}s")
# break #### break debug
def evaluate_metrics(results, conf):
dice_total = [0, 0, 0, 0, 0]
nsd_total = [0, 0, 0, 0, 0]
for real_image, real_mask, gen_image, gen_mask, gt_name in results:
dice = []
for i in range(gen_mask.size()[1]):
gen_mask_i = gen_mask[:,i,:,:,:]
gen_mask_i = gen_mask_i.cpu()
# gen_mask_i_de_sdf = torch.where(gen_mask_i < 0.07, torch.tensor(1.0), torch.tensor(0.0))
# gen_mask_i_de_sdf = sdf_to_voxel(gen_mask_i.squeeze(0), level=0.07)
# gen_mask_i_de_sdf = torch.from_numpy(gen_mask_i_de_sdf).unsqueeze(0)
gen_mask_i_de_sdf = torch.where(gen_mask_i < 0.0, torch.tensor(1.0), torch.tensor(0.0))
real_mask_i = real_mask[:,i,:,:,:]
Dice = get_dice(real_mask_i.numpy(), gen_mask_i_de_sdf.numpy())
# print(f" {i+1}_dice:", Dice)
dice.append(Dice)
dice_total[i] += Dice
get_nsd = NSDMetric(n_classes=6)
background_mask = torch.where((gen_mask <= 0.0).sum(dim=1) > 0, torch.tensor(0.0), torch.tensor(1.0))
gen_mask_togather = torch.where(background_mask == 0, torch.argmin(gen_mask, dim=1)+1, torch.tensor(0.0))
background_mask = torch.where((real_mask > 0).sum(dim=1) > 0, torch.tensor(0.0), torch.tensor(1.0))
real_mask_togather = torch.where(background_mask == 0, torch.argmax(real_mask, dim=1)+1, torch.tensor(0.0))
nnsd = get_nsd(inputs=gen_mask_togather.long(), target=real_mask_togather.long())
for i in range(0, 5):
nsd_total[i] += nnsd[i]
print(f" {gt_name}:")
# print(f" Dice: {dice}")
# print(f" NSD: {nnsd}")
print(f" Dice: {sum(dice)/len(dice): .4f}")
print(f" NSD: {sum(nnsd)/len(nnsd): .4f}")
dice_total_avg = [item / len(results) for item in dice_total]
nsd_total_avg = [item / len(results) for item in nsd_total]
print(conf.target_path)
print("Total average:")
print(f" Dice: {dice_total_avg}")
print(f" NSD: {nsd_total_avg}")
@hydra.main(config_path='confs', config_name='infer', version_base=None)
def main(conf: DictConfig):
print(OmegaConf.to_container(conf, resolve=True))
device = dev(conf.get('device'))
model = Unet3D(
dim=conf.diffusion_img_size,
dim_mults=conf.dim_mults,
channels=conf.diffusion_num_channels,
cond_dim=16,
)
diffusion = GaussianDiffusion_Nolatent(
model,
image_size=conf.diffusion_img_size,
num_frames=conf.diffusion_depth_size,
channels=conf.diffusion_num_channels,
timesteps=conf.timesteps,
loss_type=conf.loss_type,
)
diffusion.to(device)
weights_dict = {}
for k, v in (load_state_dict(os.path.expanduser(conf.model_path), map_location="cpu")["model"].items()):
new_k = k.replace('module.', '') if 'module' in k else k
weights_dict[new_k] = v
diffusion.load_state_dict(weights_dict)
model.eval()
BS = 4
if conf.dataset == 'MMWHS':
dataloader = get_MMWHS_dataloader(root_dir=conf.root_dir, mode=conf.mode, data_type=conf.data_type, batch_size=BS)
elif conf.dataset == 'TS':
dataloader = get_TS_dataloader(root_dir=conf.root_dir, mode=conf.mode, batch_size=BS)
else:
raise ValueError("No Such Dataset")
if conf.gen == 1:
# Generate results
tag = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
conf.target_path = os.path.join(conf.target_path, tag)
if not os.path.exists(conf.target_path):
os.makedirs(conf.target_path, exist_ok=True)
generate_results(dataloader, diffusion, device, conf)
else:
print(f"Target path {conf.target_path} already exists!")
exit(0)
else:
conf.target_path = 'evaluate/test_set_TS_20_percent/evaluate_240_seg_mid8_guide_150_step3_0.5_hybrid_full/2025-11-19_15-47-03'
# Load results
results = []
for file in os.listdir(conf.target_path):
if file.endswith(".pt"):
res = torch.load(os.path.join(conf.target_path, file))
results.append(res)
# Evaluate metrics
evaluate_metrics(results, conf)
if __name__ == "__main__":
main()