mberkay0 / pretrained-backbones-unet

A PyTorch-based Python library with UNet architecture and multiple backbones for Image Semantic Segmentation.
MIT License
54 stars 12 forks source link

Test script? #2

Closed bc-bytes closed 1 year ago

bc-bytes commented 1 year ago

Do you have a working test script for these models? I just need to get prediction masks from a test set, I don't need metrics.

mberkay0 commented 1 year ago

You can use a script as shown below.

from backbones_unet.utils.dataset import SemanticSegmentationDataset
from torch.utils.data import DataLoader

test_img_path = './images'
# dataloader 
test_dataset = SemanticSegmentationDataset(test_img_path)
test_loader = DataLoader(test_dataset, batch_size=1, shuffle=False, pin_memory=True)

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# probability map threshold
threshold = 0.5

# predictions
preds = []
for imgs in test_loader:
    with torch.no_grad():
        pred = model(imgs.to(device))
        pred[:, :][pred[:, :] >= threshold] = 1
        pred[:, :][pred[:, :] < threshold] = 0
    preds.append(pred)

# predicted masks
preds = torch.mean(torch.stack(preds, dim=0), dim=0).permute((0,2,3,1)).cpu().detach()
bc-bytes commented 1 year ago

Thank you for the quick reply!