deep-learning-analytics
commited on
Commit
•
8f9088a
1
Parent(s):
ed646ee
inference script
Browse files
app.py
ADDED
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sklearn.metrics import accuracy_score
|
2 |
+
import os
|
3 |
+
import pandas as pd
|
4 |
+
# import cv2
|
5 |
+
import numpy as np
|
6 |
+
import torch
|
7 |
+
from transformers import SegformerForSemanticSegmentation, SegformerFeatureExtractor
|
8 |
+
from torch import nn
|
9 |
+
import streamlit as st
|
10 |
+
|
11 |
+
|
12 |
+
raw_image = st.file_uploader('Raw Input Image')
|
13 |
+
if raw_image is not None:
|
14 |
+
|
15 |
+
df = pd.read_csv('class_dict_seg.csv')
|
16 |
+
classes = df['name']
|
17 |
+
palette = df[[' r', ' g', ' b']].values
|
18 |
+
id2label = classes.to_dict()
|
19 |
+
label2id = {v: k for k, v in id2label.items()}
|
20 |
+
|
21 |
+
image = np.asarray(raw_image)
|
22 |
+
|
23 |
+
feature_extractor = SegformerFeatureExtractor(align=False, reduce_zero_label=False)
|
24 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
25 |
+
model = SegformerForSemanticSegmentation.from_pretrained("deep-learning-analytics/segformer_semantic_segmentation",
|
26 |
+
ignore_mismatched_sizes=True,
|
27 |
+
num_labels=len(id2label), id2label=id2label, label2id=label2id,
|
28 |
+
reshape_last_stage=True)
|
29 |
+
model = model.to(device)
|
30 |
+
|
31 |
+
# prepare the image for the model (aligned resize)
|
32 |
+
feature_extractor_inference = SegformerFeatureExtractor(do_random_crop=False, do_pad=False)
|
33 |
+
|
34 |
+
pixel_values = feature_extractor_inference(image, return_tensors="pt").pixel_values.to(device)
|
35 |
+
model.eval()
|
36 |
+
outputs = model(pixel_values=pixel_values)# logits are of shape (batch_size, num_labels, height/4, width/4)
|
37 |
+
logits = outputs.logits.cpu()
|
38 |
+
|
39 |
+
# First, rescale logits to original image size
|
40 |
+
upsampled_logits = nn.functional.interpolate(logits,
|
41 |
+
size=image.shape[:-1], # (height, width)
|
42 |
+
mode='bilinear',
|
43 |
+
align_corners=False)
|
44 |
+
|
45 |
+
# Second, apply argmax on the class dimension
|
46 |
+
seg = upsampled_logits.argmax(dim=1)[0]
|
47 |
+
color_seg = np.zeros((seg.shape[0], seg.shape[1], 3), dtype=np.uint8) # height, width, 3\
|
48 |
+
for label, color in enumerate(palette):
|
49 |
+
color_seg[seg == label, :] = color
|
50 |
+
# Convert to BGR
|
51 |
+
color_seg = color_seg[..., ::-1]
|
52 |
+
|
53 |
+
# Show image + mask
|
54 |
+
img = np.array(image) * 0.5 + color_seg * 0.5
|
55 |
+
img = img.astype(np.uint8)
|
56 |
+
|
57 |
+
st.image(img, caption="Segmented Image")
|