File size: 1,519 Bytes
b816225
 
 
 
 
8658411
 
56153f5
8658411
b816225
 
 
 
8658411
b816225
 
 
 
3df38dc
b816225
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8658411
 
 
 
 
 
b816225
 
 
 
 
 
 
 
8658411
b816225
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import gradio as gr
import torch
from torchvision import transforms
from PIL import Image
from timm import create_model
import json

with open('class_names.json', 'r') as json_file:
    class_mapping = json.load(json_file)


# 加载模型
def load_model(model_path):
    model = create_model('resnet18', pretrained=False, num_classes=len(class_mapping))
    model.load_state_dict(torch.load(model_path, map_location=torch.device('cpu')))
    model.eval()
    return model

model = load_model("res18_nabird555_acc596.pth")

# 定义图像预处理
def preprocess_image(image):
    transform = transforms.Compose([
        transforms.Resize((224, 224)),
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
    ])
    return transform(image).unsqueeze(0)

# 定义推理函数
def classify_image(image):
    image = preprocess_image(image)
    with torch.no_grad():
        outputs = model(image)
        
        _, predicted_class = torch.max(outputs, 1)
        predicted_class_idx = predicted_class.item()
        predicted_class_name = class_mapping[str(predicted_class_idx)]

    return predicted_class_name

# 创建 Gradio 接口
title = "Bird Species Classifier"
description = "Upload an image of a bird, and the model will predict its species."

interface = gr.Interface(
    fn=classify_image,
    inputs=gr.Image(type="pil"),
    outputs="text",
    title=title,
    description=description,
)

if __name__ == "__main__":
    interface.launch()