Update app.py
Browse files
app.py
CHANGED
@@ -4,44 +4,22 @@ import torch
|
|
4 |
from torchvision import transforms
|
5 |
from PIL import Image
|
6 |
import torch.nn.functional as F
|
|
|
7 |
|
8 |
-
# 加载模型
|
9 |
-
class SimpleModel(torch.nn.Module):
|
10 |
-
def __init__(self, num_classes=3):
|
11 |
-
super(SimpleModel, self).__init__()
|
12 |
-
self.fc = torch.nn.Linear(3 * 224 * 224, num_classes)
|
13 |
-
|
14 |
-
def forward(self, x):
|
15 |
-
x = x.view(x.size(0), -1)
|
16 |
-
return self.fc(x)
|
17 |
-
|
18 |
-
# 初始化模型并加载权重
|
19 |
-
model = SimpleModel(num_classes=3)
|
20 |
-
model_path = "model.pth"
|
21 |
-
model.load_state_dict(torch.load(model_path, map_location=torch.device("cpu")))
|
22 |
-
model.eval()
|
23 |
-
|
24 |
-
|
25 |
-
def preprocess(image: Image.Image):
|
26 |
-
transform = transforms.Compose([
|
27 |
-
transforms.Resize((224, 224)),
|
28 |
-
transforms.ToTensor(),
|
29 |
-
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
30 |
-
])
|
31 |
-
return transform(image).unsqueeze(0)
|
32 |
|
|
|
|
|
33 |
|
34 |
-
def
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
return f"Predicted: {class_names[top_class]} (Confidence: {probabilities[top_class]:.2f})"
|
41 |
|
42 |
|
43 |
app = gr.Interface(
|
44 |
-
fn=
|
45 |
inputs=gr.Image(type="pil"), # 接收输入图片,返回 PIL 格式
|
46 |
outputs="text", # 输出分类结果
|
47 |
title="Image Classification with PyTorch",
|
|
|
4 |
from torchvision import transforms
|
5 |
from PIL import Image
|
6 |
import torch.nn.functional as F
|
7 |
+
from ultralytics import YOLO
|
8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
|
10 |
+
# 加载模型
|
11 |
+
model = YOLO("nabird_det_ep3.pt")
|
12 |
|
13 |
+
def yolo_det(image: Image.Image):
|
14 |
+
|
15 |
+
output = model.predict(image, save=False)
|
16 |
+
print(output)
|
17 |
+
|
18 |
+
return output
|
|
|
19 |
|
20 |
|
21 |
app = gr.Interface(
|
22 |
+
fn=yolo_det, # 推理函数
|
23 |
inputs=gr.Image(type="pil"), # 接收输入图片,返回 PIL 格式
|
24 |
outputs="text", # 输出分类结果
|
25 |
title="Image Classification with PyTorch",
|