Hakureirm commited on
Commit
34d8201
·
verified ·
1 Parent(s): 4689493

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +14 -16
app.py CHANGED
@@ -8,25 +8,22 @@ import numpy as np
8
 
9
  app = FastAPI()
10
  device = 'cuda' if torch.cuda.is_available() else 'cpu'
11
- model = YOLO('nailong_yolo11.pt').to(device)
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(img_array)
@@ -35,11 +32,6 @@ def predict(img):
35
  # 获取预测结果
36
  result_img = result.plot()
37
 
38
- # 裁剪回原始尺寸
39
- if pad_w > 0 or pad_h > 0:
40
- result_img = result_img[pad_h//2:pad_h//2 + original_size[1],
41
- pad_w//2:pad_w//2 + original_size[0]]
42
-
43
  # 处理检测信息
44
  info = {
45
  "detected": len(result.boxes) > 0,
@@ -70,6 +62,12 @@ def predict(img):
70
  for idx, det in enumerate(info["detections"], 1):
71
  output_text += f"\n 目标 {idx}: {det['class']} (置信度: {det['confidence']})"
72
 
 
 
 
 
 
 
73
  return result_img, output_text
74
 
75
  demo = gr.Interface(
 
8
 
9
  app = FastAPI()
10
  device = 'cuda' if torch.cuda.is_available() else 'cpu'
11
+ model = YOLO('nailong_yolo11.onnx').to(device)
12
 
13
  @spaces.GPU
14
  def predict(img):
15
  # 将输入图像转换为PIL Image对象
16
  input_image = Image.fromarray(img)
 
17
 
18
+ # 保持长宽比的情况下调整尺寸
19
+ w, h = input_image.size
20
+ scale = min(640/w, 640/h)
21
+ new_w, new_h = int(w * scale), int(h * scale)
22
+ if scale != 1:
23
+ input_image = input_image.resize((new_w, new_h), Image.LANCZOS)
 
 
24
 
25
  # 转换为numpy数组并进行预测
26
+ img_array = np.array(input_image)
27
 
28
  # 进行预测
29
  results = model.predict(img_array)
 
32
  # 获取预测结果
33
  result_img = result.plot()
34
 
 
 
 
 
 
35
  # 处理检测信息
36
  info = {
37
  "detected": len(result.boxes) > 0,
 
62
  for idx, det in enumerate(info["detections"], 1):
63
  output_text += f"\n 目标 {idx}: {det['class']} (置信度: {det['confidence']})"
64
 
65
+ # 如果需要将结果图像缩放回原始尺寸
66
+ if scale != 1:
67
+ result_img = Image.fromarray(result_img)
68
+ result_img = result_img.resize((w, h), Image.LANCZOS)
69
+ result_img = np.array(result_img)
70
+
71
  return result_img, output_text
72
 
73
  demo = gr.Interface(