Dibiddo commited on
Commit
0168843
·
verified ·
1 Parent(s): 34873be

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -1
app.py CHANGED
@@ -1,3 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  def detect_objects(image):
2
  if image is None:
3
  raise ValueError("No image uploaded!") # 检查图像是否为 None
@@ -38,10 +58,40 @@ def detect_objects(image):
38
  "box": box,
39
  })
40
 
41
- # 检查并绘制边界框和标签到原始图像上
42
  draw = ImageDraw.Draw(original_image)
43
  if box[1] < box[3]: # 确保 y_min < y_max
44
  draw.rectangle(box[:4], outline="red", width=3)
45
  draw.text((box[0], box[1]), f"{detections[-1]['label']} ({detections[-1]['confidence']})", fill="red")
46
 
47
  return original_image, detections
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from qai_hub_models.models.detr_resnet50 import Model
4
+ from PIL import Image, ImageDraw
5
+ import numpy as np
6
+
7
+ # 注册 AVIF 支持(根据所安装的插件选择一种)
8
+ try:
9
+ from pillow_avif import register_avif_opener
10
+ register_avif_opener()
11
+ except ImportError:
12
+ try:
13
+ import pillow_heif
14
+ pillow_heif.register_heif_opener()
15
+ except ImportError:
16
+ print("AVIF support not available. Please install 'pillow-avif-plugin' or 'pillow-heif'.")
17
+
18
+ # 加载模型
19
+ torch_model = Model.from_pretrained()
20
+
21
  def detect_objects(image):
22
  if image is None:
23
  raise ValueError("No image uploaded!") # 检查图像是否为 None
 
58
  "box": box,
59
  })
60
 
61
+ # 绘制边界框和标签到原始图像上
62
  draw = ImageDraw.Draw(original_image)
63
  if box[1] < box[3]: # 确保 y_min < y_max
64
  draw.rectangle(box[:4], outline="red", width=3)
65
  draw.text((box[0], box[1]), f"{detections[-1]['label']} ({detections[-1]['confidence']})", fill="red")
66
 
67
  return original_image, detections
68
+
69
+ # 创建 Gradio 接口,自动处理 AVIF 图像并转换为 PNG 格式以供显示和处理。
70
+ with gr.Blocks() as iface:
71
+ gr.Markdown("# Object Detection with DETR-ResNet50")
72
+
73
+ with gr.Row():
74
+ with gr.Column(scale=1):
75
+ image_input = gr.Image(type="numpy", label="Upload Image (supports PNG, JPEG, AVIF...)")
76
+ submit_button = gr.Button("Submit")
77
+ clear_button = gr.Button("Clear")
78
+ with gr.Column(scale=1):
79
+ output_image = gr.Image(label="Detected Image")
80
+ output_json = gr.JSON(label="Detections")
81
+
82
+ def on_submit(image):
83
+ try:
84
+ detected_image, detections = detect_objects(image)
85
+ return detected_image, detections
86
+ except Exception as e:
87
+ return None, {"error": str(e)}
88
+
89
+ def on_clear():
90
+ return None, None, None # 清空输入和输出
91
+
92
+ submit_button.click(on_submit, inputs=image_input, outputs=[output_image, output_json])
93
+ clear_button.click(on_clear, inputs=None, outputs=[image_input, output_image, output_json]) # 修复清除功能
94
+
95
+ # 启动应用程序
96
+ if __name__ == "__main__":
97
+ iface.launch()