ryuzo314 commited on
Commit
6012b68
1 Parent(s): 82aa00f

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -0
app.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image, ImageDraw
2
+ import gradio as gr
3
+ import torch
4
+ from transformers import DetrImageProcessor, DetrForObjectDetection
5
+
6
+ #モデルの読み込み
7
+ processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50", revision="no_timm")
8
+ model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50", revision="no_timm")
9
+
10
+ def detect_objects(image):
11
+ # 画像をモデルに入力する形式に変換
12
+ inputs = processor(images=image, return_tensors="pt")
13
+ outputs = model(**inputs)
14
+
15
+ # 出力を処理し、信頼度が0.9以上の検出結果を取得
16
+ target_sizes = torch.tensor([image.size[::-1]])
17
+ results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.9)[0]
18
+
19
+ # 検出結果を画像に描画
20
+ draw = ImageDraw.Draw(image)
21
+ for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
22
+ box = [round(i, 2) for i in box.tolist()]
23
+ draw.rectangle(box, outline="red", width=3)
24
+ draw.text((box[0], box[1]), f"{model.config.id2label[label.item()]}: {round(score.item(), 3)}", fill="red")
25
+
26
+ return image
27
+
28
+ demo = gr.Interface(
29
+ fn=detect_objects,
30
+ inputs=gr.Image(type="pil", label="Input Image"),
31
+ outputs=gr.Image(type="pil", label="Output Image with Detected Objects"),
32
+ title="Object Detection with DETR",
33
+ description="Upload an image to detect objects using the DETR model."
34
+ )
35
+
36
+ demo.launch()