(model, path, dataset, opt)
| 50 | return (intersection + smooth) / (union + smooth) |
| 51 | |
| 52 | def test(model, path, dataset, opt): |
| 53 | data_path = os.path.join(path, dataset) |
| 54 | image_root = f'{data_path}/images/' |
| 55 | gt_root = f'{data_path}/masks/' |
| 56 | model.eval() |
| 57 | |
| 58 | test_loader = get_loader( |
| 59 | image_root=image_root, gt_root=gt_root, |
| 60 | batchsize=opt.test_batchsize, trainsize=opt.img_size, |
| 61 | shuffle=False, split='test', color_image=opt.color_image |
| 62 | ) |
| 63 | |
| 64 | DSC, IOU, total_images = 0.0, 0.0, 0 |
| 65 | with torch.no_grad(): |
| 66 | for pack in test_loader: |
| 67 | images, gts, original_shapes, _ = pack |
| 68 | images = images.cuda() |
| 69 | gts = gts.cuda().float() |
| 70 | |
| 71 | ress = model(images) |
| 72 | if not isinstance(ress, list): |
| 73 | ress = [ress] |
| 74 | # Take the primary output |
| 75 | predictions = ress[-1] |
| 76 | |
| 77 | for i in range(len(images)): |
| 78 | # Note: original_shapes in some loaders is [W, H], in others [H, W] |
| 79 | # We ensure it matches your specific data loader's return order |
| 80 | h_orig, w_orig = int(original_shapes[0][i]), int(original_shapes[1][i]) |
| 81 | |
| 82 | # 1. Prediction Resize (Bilinear for soft maps) |
| 83 | p = predictions[i].unsqueeze(0) |
| 84 | pred_resized = F.interpolate(p, size=(h_orig, w_orig), mode='bilinear', align_corners=False) |
| 85 | pred_resized = pred_resized.sigmoid().squeeze() |
| 86 | |
| 87 | # 2. Local Normalization |
| 88 | pred_resized = (pred_resized - pred_resized.min()) / (pred_resized.max() - pred_resized.min() + 1e-8) |
| 89 | |
| 90 | # 3. GT Resize (NEAREST to maintain binary mask integrity) |
| 91 | g = gts[i].unsqueeze(0) |
| 92 | gt_resized = F.interpolate(g, size=(h_orig, w_orig), mode='nearest').squeeze() |
| 93 | |
| 94 | #print(pred_resized.shape, gt_resized.shape, g.shape) |
| 95 | |
| 96 | # 4. Binary Thresholding |
| 97 | input_binary = (pred_resized >= 0.5).float() |
| 98 | target_binary = (gt_resized >= 0.2).float() |
| 99 | |
| 100 | # Applying original thresholding (0.5 for pred, 0.2 for target) |
| 101 | DSC += dice_coefficient(input_binary, target_binary).item() |
| 102 | IOU += iou(input_binary, target_binary).item() |
| 103 | total_images += 1 |
| 104 | |
| 105 | return DSC / total_images, IOU / total_images, total_images |
| 106 | |
| 107 | def train(train_loader, model, optimizer, epoch, opt, model_name): |
| 108 | model.train() |
no test coverage detected