File size: 15,872 Bytes
5471715 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 | 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()
|