EverJun2 commited on
Commit
e9fc7a4
·
1 Parent(s): 289adec

feat : 과제 코드 작성

Browse files
Files changed (8) hide show
  1. app.py +96 -0
  2. labels.txt +18 -0
  3. person-1.jpg +0 -0
  4. person-2.jpg +0 -0
  5. person-3.jpg +0 -0
  6. person-4.jpg +0 -0
  7. person-5.jpg +0 -0
  8. requirements.txt +6 -0
app.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from matplotlib import gridspec
3
+ import matplotlib.pyplot as plt
4
+ import numpy as np
5
+ from PIL import Image
6
+ import torch
7
+ from transformers import AutoImageProcessor, AutoModelForSemanticSegmentation
8
+
9
+ MODEL_ID = "mattmdjaga/segformer_b2_clothes"
10
+ processor = AutoImageProcessor.from_pretrained(MODEL_ID)
11
+ model = AutoModelForSemanticSegmentation.from_pretrained(MODEL_ID)
12
+
13
+ def ade_palette():
14
+ """ADE20K palette that maps each class to RGB values."""
15
+ return [
16
+ [204, 87, 92],[112, 185, 212],[45, 189, 106],[234, 123, 67],[78, 56, 123],[210, 32, 89],
17
+ [90, 180, 56],[155, 102, 200],[33, 147, 176],[255, 183, 76],[67, 123, 89],[190, 60, 45],
18
+ [134, 112, 200],[56, 45, 189],[200, 56, 123],[87, 92, 204],[120, 56, 123],[45, 78, 123]
19
+ ]
20
+
21
+ labels_list = []
22
+ with open("labels.txt", "r", encoding="utf-8") as fp:
23
+ for line in fp:
24
+ labels_list.append(line.rstrip("\n"))
25
+
26
+ colormap = np.asarray(ade_palette(), dtype=np.uint8)
27
+
28
+ def label_to_color_image(label):
29
+ if label.ndim != 2:
30
+ raise ValueError("Expect 2-D input label")
31
+ if np.max(label) >= len(colormap):
32
+ raise ValueError("label value too large.")
33
+ return colormap[label]
34
+
35
+ def draw_plot(pred_img, seg_np):
36
+ fig = plt.figure(figsize=(20, 15))
37
+ grid_spec = gridspec.GridSpec(1, 2, width_ratios=[6, 1])
38
+
39
+ plt.subplot(grid_spec[0])
40
+ plt.imshow(pred_img)
41
+ plt.axis('off')
42
+
43
+ LABEL_NAMES = np.asarray(labels_list)
44
+ FULL_LABEL_MAP = np.arange(len(LABEL_NAMES)).reshape(len(LABEL_NAMES), 1)
45
+ FULL_COLOR_MAP = label_to_color_image(FULL_LABEL_MAP)
46
+
47
+ unique_labels = np.unique(seg_np.astype("uint8"))
48
+ ax = plt.subplot(grid_spec[1])
49
+ plt.imshow(FULL_COLOR_MAP[unique_labels].astype(np.uint8), interpolation="nearest")
50
+ ax.yaxis.tick_right()
51
+ plt.yticks(range(len(unique_labels)), LABEL_NAMES[unique_labels])
52
+ plt.xticks([], [])
53
+ ax.tick_params(width=0.0, labelsize=25)
54
+ return fig
55
+
56
+ def run_inference(input_img):
57
+ # input: numpy array from gradio -> PIL
58
+ img = Image.fromarray(input_img.astype(np.uint8)) if isinstance(input_img, np.ndarray) else input_img
59
+ if img.mode != "RGB":
60
+ img = img.convert("RGB")
61
+
62
+ inputs = processor(images=img, return_tensors="pt")
63
+ with torch.no_grad():
64
+ outputs = model(**inputs)
65
+ logits = outputs.logits # (1, C, h/4, w/4)
66
+
67
+ # resize to original
68
+ upsampled = torch.nn.functional.interpolate(
69
+ logits, size=img.size[::-1], mode="bilinear", align_corners=False
70
+ )
71
+ seg = upsampled.argmax(dim=1)[0].cpu().numpy().astype(np.uint8) # (H,W)
72
+
73
+ # colorize & overlay
74
+ color_seg = colormap[seg] # (H,W,3)
75
+ pred_img = (np.array(img) * 0.5 + color_seg * 0.5).astype(np.uint8)
76
+
77
+ fig = draw_plot(pred_img, seg)
78
+ return fig
79
+
80
+ demo = gr.Interface(
81
+ fn=run_inference,
82
+ inputs=gr.Image(type="numpy", label="Input Image"),
83
+ outputs=gr.Plot(label="Overlay + Legend"),
84
+ examples=[
85
+ "person-1.jpg",
86
+ "person-2.jpg",
87
+ "person-3.jpg",
88
+ "person-4.jpg",
89
+ "person-5.jpg"
90
+ ],
91
+ flagging_mode="never",
92
+ cache_examples=False,
93
+ )
94
+
95
+ if __name__ == "__main__":
96
+ demo.launch()
labels.txt ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Background
2
+ Hat
3
+ Hair
4
+ Sunglasses
5
+ Upper-clothes
6
+ Skirt
7
+ Pants
8
+ Dress
9
+ Belt
10
+ Left-shoe
11
+ Right-shoe
12
+ Face
13
+ Left-leg
14
+ Right-leg
15
+ Left-arm
16
+ Right-arm
17
+ Bag
18
+ Scarf
person-1.jpg ADDED
person-2.jpg ADDED
person-3.jpg ADDED
person-4.jpg ADDED
person-5.jpg ADDED
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ torch
2
+ transformers>=4.41.0
3
+ gradio>=4.0.0
4
+ Pillow
5
+ numpy
6
+ matplotlib