CoolFace
Apppublic

xdecoder/Instruct-X-Decoder

sourceHugging Faceafl-3.0updated 3y agoView on Hugging Face
163likes
open_sem.py57 linesDownload Raw Back to tasks
1# --------------------------------------------------------2# X-Decoder -- Generalized Decoding for Pixel, Image, and Language3# Copyright (c) 2022 Microsoft4# Licensed under The MIT License [see LICENSE for details]5# Written by Xueyan Zou (xueyan@cs.wisc.edu)6# --------------------------------------------------------7 8import os9import cv210import torch11import numpy as np12from PIL import Image13from torchvision import transforms14from utils.visualizer import Visualizer15from detectron2.utils.colormap import random_color16from detectron2.data import MetadataCatalog17 18 19t = []20t.append(transforms.Resize(512, interpolation=Image.BICUBIC))21transform = transforms.Compose(t)22metadata = MetadataCatalog.get('ade20k_panoptic_train')23 24def open_semseg(model, image, texts, inpainting_text, *args, **kwargs):    25    stuff_classes = [x.strip() for x in texts.split(',')]26    stuff_colors = [random_color(rgb=True, maximum=255).astype(np.int32).tolist() for _ in range(len(stuff_classes))]27    stuff_dataset_id_to_contiguous_id = {x:x for x in range(len(stuff_classes))}28 29    MetadataCatalog.get("demo").set(30        stuff_colors=stuff_colors,31        stuff_classes=stuff_classes,32        stuff_dataset_id_to_contiguous_id=stuff_dataset_id_to_contiguous_id,33    )34    model.model.sem_seg_head.predictor.lang_encoder.get_text_embeddings(stuff_classes + ["background"], is_eval=True)35    metadata = MetadataCatalog.get('demo')36    model.model.metadata = metadata37    model.model.sem_seg_head.num_classes = len(stuff_classes)38 39    with torch.no_grad():40        image_ori = transform(image)41        width = image_ori.size[0]42        height = image_ori.size[1]43        image = transform(image_ori)44        image = np.asarray(image)45        images = torch.from_numpy(image.copy()).permute(2,0,1).cuda()46 47        batch_inputs = [{'image': images, 'height': height, 'width': width}]48        outputs = model.forward(batch_inputs)49        visual = Visualizer(image_ori, metadata=metadata)50 51        sem_seg = outputs[-1]['sem_seg'].max(0)[1]52        demo = visual.draw_sem_seg(sem_seg.cpu(), alpha=0.5) # rgb Image53        res = demo.get_image()54        55    MetadataCatalog.remove('demo')56    torch.cuda.empty_cache()57    return Image.fromarray(res), '', None