Views
No views yet
1from transformers import AutoImageProcessor, AutoModelForObjectDetection
2import torch
3from PIL import Image, ImageDraw
4import matplotlib.pyplot as plt
5
6# เปิดรูปภาพจากพาธในเครื่อง
7url = "../pic/0fda72a2-f383-4f69-af8e-e16a0fbac621.jpg"
8image = Image.open(url)
9
10# แปลงรูปภาพเป็น RGB หากเป็น grayscale
11if image.mode != "RGB":
12 image = image.convert("RGB")
13
14processor = AutoImageProcessor.from_pretrained("0llheaven/detr-finetuned")
15model = AutoModelForObjectDetection.from_pretrained("0llheaven/detr-finetuned")
16
17inputs = processor(images=image, return_tensors="pt")
18outputs = model(**inputs)
19
20# กรองการทำนายที่มีความแม่นยำมากกว่า 0.9
21target_sizes = torch.tensor([image.size[::-1]])
22results = processor.post_process_object_detection(outputs, target_sizes=target_sizes)
23
24print(results)
25# # วาดกรอบรอบวัตถุที่ตรวจพบในภาพ
26draw = ImageDraw.Draw(image)
27for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
28 box = [round(i, 2) for i in box.tolist()]
29 draw.rectangle(box, outline="red", width=3)
30 draw.text((box[0], box[1]), f"{model.config.id2label[label.item()]}: {round(score.item(), 3)}", fill="red")
31
32# แสดงผลภาพ
33plt.figure(figsize=(10, 10))
34plt.imshow(image)
35plt.axis('off')
36plt.show()