analytics-jiten commited on
Commit
06f29dc
1 Parent(s): 06effc4

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -0
app.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ from transformers import AutoImageProcessor, AutoModelForObjectDetection
4
+ from PIL import Image, ImageDraw
5
+ import torch
6
+
7
+ image_processor = AutoImageProcessor.from_pretrained('hustvl/yolos-small')
8
+ model = AutoModelForObjectDetection.from_pretrained('hustvl/yolos-small')
9
+
10
+ colors = ["red",
11
+ "orange",
12
+ "yellow",
13
+ "green",
14
+ "blue",
15
+ "indigo",
16
+ "violet",
17
+ "brown",
18
+ "black",
19
+ "slategray",
20
+ ]
21
+
22
+ # Resized image width
23
+ WIDTH = 600
24
+
25
+ def detect(image):
26
+ width, height = image.size
27
+ ratio = float(WIDTH) / float(width)
28
+ new_h = height * ratio
29
+
30
+ image = image.resize((int(WIDTH), int(new_h)), Image.Resampling.LANCZOS)
31
+
32
+ inputs = image_processor(images=image, return_tensors="pt")
33
+ outputs = model(**inputs)
34
+
35
+ # convert outputs to COCO API
36
+ target_sizes = torch.tensor([image.size[::-1]])
37
+ results = image_processor.post_process_object_detection(outputs,
38
+ threshold=0.9,
39
+ target_sizes=target_sizes)[0]
40
+
41
+ draw = ImageDraw.Draw(image)
42
+
43
+ # label and the count
44
+ counts = {}
45
+
46
+ for score, label in zip(results["scores"], results["labels"]):
47
+ label_name = model.config.id2label[label.item()]
48
+ if label_name not in counts:
49
+ counts[label_name] = 0
50
+ counts[label_name] += 1
51
+
52
+ count_results = {k: v for k, v in (sorted(counts.items(), key=lambda item: item[1], reverse=True)[:10])}
53
+ label2color = {}
54
+ for idx, label in enumerate(count_results):
55
+ label2color[label] = colors[idx]
56
+
57
+ for label, box in zip(results["labels"], results["boxes"]):
58
+ label_name = model.config.id2label[label.item()]
59
+
60
+ if label_name in count_results:
61
+ box = [round(i, 4) for i in box.tolist()]
62
+ x1, y1, x2, y2 = tuple(box)
63
+ draw.rectangle((x1, y1, x2, y2), outline=label2color[label_name], width=2)
64
+ draw.text((x1, y1), label_name, fill="white")
65
+
66
+ df = pd.DataFrame({
67
+ 'label': [label for label in count_results],
68
+ 'counts': [counts[label] for label in count_results]
69
+ })
70
+
71
+ return image, df, count_results
72
+
73
+ demo = gr.Interface(
74
+ fn=detect,
75
+ examples=["examples/football.jpg", "examples/cats.jpg"],
76
+ inputs=[gr.inputs.Image(label="Input image", type="pil")],
77
+ outputs=[gr.Image(label="Output image"), gr.BarPlot(show_label=False, x="label", y="counts", x_title="Labels", y_title="Counts", vertical=False), gr.Textbox(show_label=False)],
78
+ title="YOLO Object Detection",
79
+ cache_examples=False
80
+ )
81
+
82
+ demo.launch()