azhongai666666 commited on
Commit
d09da2f
·
1 Parent(s): 913a668

create app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -0
app.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torchvision.transforms as transforms
3
+ from torchvision import models
4
+ from torch import nn
5
+ import torch.nn.functional as F
6
+ import gradio as gr
7
+ import json
8
+
9
+
10
+ # Get cpu or gpu device for training.
11
+ device = "cuda" if torch.cuda.is_available() else "cpu"
12
+ print(f"Using {device} device")
13
+
14
+ model_path = './resnet18_flower.pth'
15
+ num_classes = 5
16
+ label_name_list = ['daisy', 'dandelion', 'roses', 'sunflowers', 'tulips']
17
+
18
+ # step1: 创建并加载模型
19
+ resnet18 = models.resnet18(pretrained=True)
20
+ num_ftrs = resnet18.fc.in_features
21
+ resnet18.fc = nn.Linear(num_ftrs, num_classes)
22
+ resnet18 = resnet18.to(device)
23
+
24
+ resnet18.load_state_dict(torch.load(model_path,map_location=torch.device('cpu')))
25
+
26
+ model = resnet18
27
+ # model = base_model_vgg13
28
+ model.eval()
29
+
30
+
31
+ # step2: 图片转换
32
+ train_transform = transforms.Compose([
33
+ # transforms.RandomRotation(5),
34
+ # transforms.RandomHorizontalFlip(),
35
+ transforms.Resize((224,224)),
36
+ transforms.ToTensor(),
37
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
38
+ ])
39
+
40
+
41
+ def predict(inp):
42
+ # 定义预处理变换
43
+ transform = train_transform
44
+
45
+ # 加载图片并进行预处理
46
+ # image = Image.open(image_path)
47
+ image = transform(inp).unsqueeze(0).to(device)
48
+
49
+ # step3:使用模型进行预测
50
+ with torch.no_grad():
51
+ output = model(image)
52
+
53
+ # step4:数据后处理
54
+ # 计算预测概率
55
+ pred_score = nn.functional.softmax(output[0], dim=0)
56
+ pred_score = pred_score.cpu().numpy()
57
+
58
+ # 获取预测结果
59
+ pred_index = torch.argmax(output, dim=1).item()
60
+ pred_label = label_name_list[pred_index]
61
+
62
+ # 转为json字符串格式
63
+ result_dict = {'pred_score':str(max(pred_score)),'pred_index':str(pred_index),'pred_label':pred_label }
64
+ result_json = json.dumps(result_dict)
65
+
66
+ return result_json
67
+
68
+
69
+ demo = gr.Interface(fn=predict,
70
+ inputs=gr.Image(type="pil"),
71
+ outputs="text",
72
+ examples=["./592px-Red_sunflower.jpg"],
73
+ )
74
+
75
+ # demo.launch(debug=True)
76
+ demo.launch()