|
| 1 | +from numpy.core.fromnumeric import product |
| 2 | +from skimage.segmentation.boundaries import find_boundaries |
| 3 | +import torch |
| 4 | +import numpy as np |
| 5 | +from torchvision.io import read_image |
| 6 | +from torchvision.models.segmentation import fcn_resnet50 |
| 7 | +import matplotlib.pyplot as plt |
| 8 | +from torchvision.transforms.functional import convert_image_dtype |
| 9 | +from torchvision.utils import draw_segmentation_masks |
| 10 | +from torchvision.utils import make_grid |
| 11 | +from pytorch_superpixels.runtime import superpixelise |
| 12 | +from skimage.segmentation import slic, mark_boundaries, find_boundaries |
| 13 | +from pathlib import Path |
| 14 | +from multiprocessing import Pool |
| 15 | +from os import cpu_count |
| 16 | +from functools import partial |
| 17 | + |
| 18 | +import torchvision.transforms.functional as F |
| 19 | + |
| 20 | +def show(imgs): |
| 21 | + if not isinstance(imgs, list): |
| 22 | + imgs = [imgs] |
| 23 | + fix, axs = plt.subplots(ncols=len(imgs), squeeze=False) |
| 24 | + for i, img in enumerate(imgs): |
| 25 | + img = img.detach() |
| 26 | + img = F.to_pil_image(img) |
| 27 | + axs[0, i].imshow(np.asarray(img)) |
| 28 | + axs[0, i].set(xticklabels=[], yticklabels=[], xticks=[], yticks=[]) |
| 29 | + plt.tight_layout() |
| 30 | + plt.show() |
| 31 | + |
| 32 | + |
| 33 | +if __name__ == "__main__": |
| 34 | + sem_classes = [ |
| 35 | + '__background__', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', |
| 36 | + 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', |
| 37 | + 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor' |
| 38 | + ] |
| 39 | + sem_class_to_idx = {cls: idx for (idx, cls) in enumerate(sem_classes)} |
| 40 | + image_dims = [420, 640] |
| 41 | + images = [read_image(str(img)) for img in Path("data").glob("*.jpg")] |
| 42 | + images = [F.center_crop(image, image_dims) for image in images] |
| 43 | + image_size = product(image_dims) |
| 44 | + |
| 45 | + batch_int = torch.stack(images) |
| 46 | + batch = convert_image_dtype(batch_int, dtype=torch.float) |
| 47 | + |
| 48 | + # permute because slic expects the last dimension to be channel |
| 49 | + with Pool(processes = cpu_count()-1) as pool: |
| 50 | + # re-order axes for skimage |
| 51 | + args = [x.permute(1,2,0) for x in batch] |
| 52 | + # 100 segments |
| 53 | + kwargs = {"n_segments":100, "start_label":0, "slic_zero":True} |
| 54 | + func = partial(slic, **kwargs) |
| 55 | + masks_100sp = pool.map(func, args) |
| 56 | + # 1000 segments |
| 57 | + kwargs["n_segments"] = 1000 |
| 58 | + func = partial(slic, **kwargs) |
| 59 | + masks_1000sp = pool.map(func, args) |
| 60 | + |
| 61 | + |
| 62 | + model = fcn_resnet50(pretrained=True, progress=False) |
| 63 | + model = model.eval() |
| 64 | + |
| 65 | + normalized_batch = F.normalize(batch, mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)) |
| 66 | + outputs = model(batch)['out'] |
| 67 | + |
| 68 | + normalized_masks = torch.nn.functional.softmax(outputs, dim=1) |
| 69 | + num_classes = normalized_masks.shape[1] |
| 70 | + |
| 71 | + def generate_all_class_masks(outputs, masks): |
| 72 | + masks = np.stack(masks) |
| 73 | + masks = torch.from_numpy(masks) |
| 74 | + outputs_sp = superpixelise(outputs, masks) |
| 75 | + normalized_masks_sp = torch.nn.functional.softmax(outputs_sp, dim=1) |
| 76 | + return normalized_masks_sp[i].argmax(0) == torch.arange(num_classes)[:, None, None] |
| 77 | + |
| 78 | + to_show = [] |
| 79 | + for i, image in enumerate(images): |
| 80 | + # before |
| 81 | + all_classes_masks = normalized_masks[i].argmax(0) == torch.arange(num_classes)[:, None, None] |
| 82 | + to_show.append(draw_segmentation_masks(image, masks=all_classes_masks, alpha=.6)) |
| 83 | + # after 100 |
| 84 | + all_classes_masks_sp = generate_all_class_masks(outputs, masks_100sp) |
| 85 | + to_show.append(draw_segmentation_masks(image, masks=all_classes_masks_sp, alpha=.6)) |
| 86 | + # show superpixel boundaries |
| 87 | + boundaries = find_boundaries(masks_100sp[i]) |
| 88 | + to_show[-1][0:2, boundaries] = 255 |
| 89 | + to_show[-1][2, boundaries] = 0 |
| 90 | + # after 1000 |
| 91 | + all_classes_masks_sp = generate_all_class_masks(outputs, masks_1000sp) |
| 92 | + to_show.append(draw_segmentation_masks(image, masks=all_classes_masks_sp, alpha=.6)) |
| 93 | + # show superpixel boundaries |
| 94 | + boundaries = find_boundaries(masks_1000sp[i]) |
| 95 | + to_show[-1][0:2, boundaries] = 255 |
| 96 | + to_show[-1][2, boundaries] = 0 |
| 97 | + show(make_grid(to_show, nrow=6)) |
0 commit comments