Hakureirm commited on
Commit
4b635e1
·
verified ·
1 Parent(s): b482a00

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -10
app.py CHANGED
@@ -12,19 +12,39 @@ model = YOLO('NailongKiller.yolo11n.pt').to(device)
12
 
13
  @spaces.GPU
14
  def predict(img):
15
- # 优化图像预处理
16
- img_resized = np.array(Image.fromarray(img).resize((640, 640)))
17
- # 规范化像素值到 0-1 范围
18
- img_tensor = torch.tensor(img_resized, dtype=torch.float32).permute(2, 0, 1).unsqueeze(0).div(255.0).to(device)
19
 
20
- # 设置模型预测参数以加快后处理速度
 
 
 
 
 
 
 
 
 
 
 
 
21
  results = model.predict(
22
- img_tensor,
23
- conf=0.50, # 提高置信度阈值
24
- iou=0.45, # 调整 IOU 阈值
25
- max_det=100 # 限制最大检测数量
26
  )
27
- return results[0].plot()
 
 
 
 
 
 
 
 
 
28
 
29
  demo = gr.Interface(
30
  fn=predict,
 
12
 
13
  @spaces.GPU
14
  def predict(img):
15
+ # 将输入图像转换为PIL Image对象
16
+ input_image = Image.fromarray(img)
17
+ original_size = input_image.size
 
18
 
19
+ # 计算填充尺寸
20
+ max_size = max(original_size)
21
+ pad_w = max_size - original_size[0]
22
+ pad_h = max_size - original_size[1]
23
+
24
+ # 创建方形画布并保持宽高比
25
+ padded_img = Image.new('RGB', (max_size, max_size), (114, 114, 114)) # 使用灰色填充
26
+ padded_img.paste(input_image, (pad_w//2, pad_h//2))
27
+
28
+ # 转换为numpy数组并进行预测
29
+ img_array = np.array(padded_img)
30
+
31
+ # 进行预测
32
  results = model.predict(
33
+ img_array,
34
+ conf=0.50, # 置信度阈值
35
+ iou=0.45, # IOU阈值
36
+ max_det=100 # 最大检测数量
37
  )
38
+
39
+ # 获取预测结果
40
+ result_img = results[0].plot()
41
+
42
+ # 裁剪回原始尺寸
43
+ if pad_w > 0 or pad_h > 0:
44
+ result_img = result_img[pad_h//2:pad_h//2 + original_size[1],
45
+ pad_w//2:pad_w//2 + original_size[0]]
46
+
47
+ return result_img
48
 
49
  demo = gr.Interface(
50
  fn=predict,