| import gradio as gr |
| from transformers import DetrImageProcessor, DetrForObjectDetection |
| import torch |
| from PIL import Image, ImageDraw |
|
|
| |
| model_name = "facebook/detr-resnet-50" |
| processor = DetrImageProcessor.from_pretrained(model_name) |
| model = DetrForObjectDetection.from_pretrained(model_name) |
|
|
| |
| def detect_objects(image): |
| |
| inputs = processor(images=image, return_tensors="pt") |
| outputs = model(**inputs) |
|
|
| |
| target_sizes = torch.tensor([image.size[::-1]]) |
| results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.5)[0] |
|
|
| draw = ImageDraw.Draw(image) |
| boxes_info = [] |
|
|
| for score, label, box in zip(results["scores"], results["labels"], results["boxes"]): |
| box = [round(i, 2) for i in box.tolist()] |
| draw.rectangle(box, outline="red", width=3) |
| boxes_info.append({ |
| "box": box, |
| "label": model.config.id2label[label.item()], |
| "score": round(score.item(), 3) |
| }) |
|
|
| return image, boxes_info |
|
|
| |
| with gr.Blocks() as demo: |
| img_input = gr.Image(type="pil") |
| output_img = gr.Image(type="pil") |
| output_info = gr.JSON() |
|
|
| btn = gr.Button("ตรวจจับอวัยวะ") |
| btn.click(detect_objects, inputs=img_input, outputs=[output_img, output_info]) |
|
|
| demo.launch() |