Spaces:
Sleeping
Sleeping
Migrate to ZeroGPU and update requirements for compatibility
Browse files
app.py
CHANGED
@@ -6,23 +6,26 @@ import torch
|
|
6 |
import spaces
|
7 |
import numpy as np
|
8 |
|
9 |
-
# 初始化 FastAPI 和模型
|
10 |
app = FastAPI()
|
11 |
-
|
12 |
-
# 检查 GPU 是否可用,并选择设备
|
13 |
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
14 |
model = YOLO('NailongKiller.yolo11n.pt').to(device)
|
15 |
|
16 |
@spaces.GPU
|
17 |
def predict(img):
|
18 |
-
#
|
19 |
img_resized = np.array(Image.fromarray(img).resize((640, 640)))
|
20 |
-
#
|
21 |
-
img_tensor = torch.tensor(img_resized, dtype=torch.float32).permute(2, 0, 1).unsqueeze(0).to(device)
|
22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
return results[0].plot()
|
24 |
|
25 |
-
# Gradio 界面
|
26 |
demo = gr.Interface(
|
27 |
fn=predict,
|
28 |
inputs=gr.Image(label="输入图片"),
|
@@ -33,6 +36,5 @@ demo = gr.Interface(
|
|
33 |
cache_examples=True
|
34 |
)
|
35 |
|
36 |
-
# 启动应用
|
37 |
if __name__ == "__main__":
|
38 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
6 |
import spaces
|
7 |
import numpy as np
|
8 |
|
|
|
9 |
app = FastAPI()
|
|
|
|
|
10 |
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
11 |
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,
|
31 |
inputs=gr.Image(label="输入图片"),
|
|
|
36 |
cache_examples=True
|
37 |
)
|
38 |
|
|
|
39 |
if __name__ == "__main__":
|
40 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|