Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import io
|
2 |
+
import requests
|
3 |
+
from PIL import Image
|
4 |
+
import torch
|
5 |
+
import numpy
|
6 |
+
|
7 |
+
from transformers import DetrFeatureExtractor, DetrForSegmentation
|
8 |
+
from transformers.models.detr.feature_extraction_detr import rgb_to_id
|
9 |
+
|
10 |
+
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
11 |
+
image = Image.open(requests.get(url, stream=True).raw)
|
12 |
+
|
13 |
+
feature_extractor = DetrFeatureExtractor.from_pretrained("facebook/detr-resnet-50-panoptic")
|
14 |
+
model = DetrForSegmentation.from_pretrained("facebook/detr-resnet-50-panoptic")
|
15 |
+
|
16 |
+
# prepare image for the model
|
17 |
+
inputs = feature_extractor(images=image, return_tensors="pt")
|
18 |
+
|
19 |
+
# forward pass
|
20 |
+
outputs = model(**inputs)
|
21 |
+
|
22 |
+
# use the `post_process_panoptic` method of `DetrFeatureExtractor` to convert to COCO format
|
23 |
+
processed_sizes = torch.as_tensor(inputs["pixel_values"].shape[-2:]).unsqueeze(0)
|
24 |
+
result = feature_extractor.post_process_panoptic(outputs, processed_sizes)[0]
|
25 |
+
|
26 |
+
# the segmentation is stored in a special-format png
|
27 |
+
panoptic_seg = Image.open(io.BytesIO(result["png_string"]))
|
28 |
+
panoptic_seg = numpy.array(panoptic_seg, dtype=numpy.uint8)
|
29 |
+
# retrieve the ids corresponding to each mask
|
30 |
+
panoptic_seg_id = rgb_to_id(panoptic_seg)
|