0llheaven commited on
Commit
ec00537
·
verified ·
1 Parent(s): 478152c
Files changed (1) hide show
  1. app.py +55 -0
app.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import AutoImageProcessor, AutoModelForObjectDetection
3
+ import torch
4
+ from PIL import Image, ImageDraw
5
+ import matplotlib.pyplot as plt
6
+ import io
7
+
8
+ # โหลดโมเดลและตัวประมวลผล
9
+ processor = AutoImageProcessor.from_pretrained("0llheaven/Conditional-detr-finetuned")
10
+ model = AutoModelForObjectDetection.from_pretrained("0llheaven/Conditional-detr-finetuned")
11
+
12
+ def detect_objects(image):
13
+ # แปลงรูปภาพเป็น RGB หากเป็น grayscale
14
+ if image.mode != "RGB":
15
+ image = image.convert("RGB")
16
+
17
+ # เตรียม input สำหรับโมเดล
18
+ inputs = processor(images=image, return_tensors="pt")
19
+ outputs = model(**inputs)
20
+
21
+ # กรองการทำนายที่มีความแม่นยำมากกว่า 0.5
22
+ target_sizes = torch.tensor([image.size[::-1]])
23
+ results = processor.post_process_object_detection(outputs, target_sizes=target_sizes)
24
+
25
+ # วาดกรอบรอบวัตถุที่ตรวจพบในภาพ
26
+ draw = ImageDraw.Draw(image)
27
+ for result in results:
28
+ scores = result["scores"]
29
+ labels = result["labels"]
30
+ boxes = result["boxes"]
31
+
32
+ for score, label, box in zip(scores, labels, boxes):
33
+ box = [round(i, 2) for i in box.tolist()]
34
+ label_name = "Pneumonia" if label.item() == 0 else "Other"
35
+ draw.rectangle(box, outline="red", width=3)
36
+ draw.text((box[0], box[1]), f"{label_name}: {round(score.item(), 3)}", fill="red")
37
+
38
+ # แปลงภาพเป็นรูปแบบที่สามารถแสดงผลได้ใน Gradio
39
+ output_image = io.BytesIO()
40
+ image.save(output_image, format='PNG')
41
+ output_image.seek(0)
42
+
43
+ return output_image
44
+
45
+ # สร้างอินเตอร์เฟซด้วย Gradio
46
+ interface = gr.Interface(
47
+ fn=detect_objects,
48
+ inputs=gr.inputs.Image(type="pil"),
49
+ outputs=gr.outputs.Image(type="auto"),
50
+ title="Object Detection with Transformers",
51
+ description="Upload an image to detect objects using a fine-tuned Conditional-DETR model."
52
+ )
53
+
54
+ # เปิดใช้งานอินเตอร์เฟซ
55
+ interface.launch()