Spaces:
Build error
Build error
# -------------------------------------------------------- | |
# X-Decoder -- Generalized Decoding for Pixel, Image, and Language | |
# Copyright (c) 2022 Microsoft | |
# Licensed under The MIT License [see LICENSE for details] | |
# Written by Xueyan Zou ([email protected]) | |
# -------------------------------------------------------- | |
import torch | |
import numpy as np | |
from PIL import Image | |
from torchvision import transforms | |
from utils.visualizer import Visualizer | |
from detectron2.utils.colormap import random_color | |
from detectron2.data import MetadataCatalog | |
from detectron2.structures import BitMasks | |
t = [] | |
t.append(transforms.Resize(512, interpolation=Image.BICUBIC)) | |
transform = transforms.Compose(t) | |
metadata = MetadataCatalog.get('ade20k_panoptic_train') | |
def open_instseg(model, image, texts, inpainting_text, *args, **kwargs): | |
thing_classes = [x.strip() for x in texts.split(',')] | |
thing_colors = [random_color(rgb=True, maximum=255).astype(np.int32).tolist() for _ in range(len(thing_classes))] | |
thing_dataset_id_to_contiguous_id = {x:x for x in range(len(thing_classes))} | |
MetadataCatalog.get("demo").set( | |
thing_colors=thing_colors, | |
thing_classes=thing_classes, | |
thing_dataset_id_to_contiguous_id=thing_dataset_id_to_contiguous_id, | |
) | |
with torch.no_grad(): | |
model.model.sem_seg_head.predictor.lang_encoder.get_text_embeddings(thing_classes + ["background"], is_eval=True) | |
metadata = MetadataCatalog.get('demo') | |
model.model.metadata = metadata | |
model.model.sem_seg_head.num_classes = len(thing_classes) | |
image_ori = transform(image) | |
width = image_ori.size[0] | |
height = image_ori.size[1] | |
image = np.asarray(image_ori) | |
images = torch.from_numpy(image.copy()).permute(2,0,1).cuda() | |
batch_inputs = [{'image': images, 'height': height, 'width': width}] | |
outputs = model.forward(batch_inputs) | |
visual = Visualizer(image_ori, metadata=metadata) | |
inst_seg = outputs[-1]['instances'] | |
inst_seg.pred_masks = inst_seg.pred_masks.cpu() | |
inst_seg.pred_boxes = BitMasks(inst_seg.pred_masks > 0).get_bounding_boxes() | |
demo = visual.draw_instance_predictions(inst_seg) # rgb Image | |
res = demo.get_image() | |
MetadataCatalog.remove('demo') | |
torch.cuda.empty_cache() | |
return Image.fromarray(res), '', None | |