penguin218 commited on
Commit
c34b829
·
verified ·
1 Parent(s): 8542f6d
Files changed (1) hide show
  1. app.py +29 -83
app.py CHANGED
@@ -1,25 +1,30 @@
 
 
 
1
  import gradio as gr
2
  import torch
3
  from torchvision import transforms
4
  from PIL import Image
5
- import json
6
  import os
7
- import datetime
8
  from model import get_mobilenet_model
9
 
10
- # 推理设置
11
  device = "cuda" if torch.cuda.is_available() else "cpu"
 
 
 
12
  model, _, _ = get_mobilenet_model(num_classes=16)
13
- checkpoint = torch.load("best_model.pth", map_location=device, weights_only=False)
14
- model.load_state_dict(checkpoint['state_dict'])
15
  model.to(device)
16
  model.eval()
17
 
18
- # 加载类别信息
19
  with open("class_eg_to_cn.json", "r", encoding="utf-8") as f:
20
  class_eg_to_cn = json.load(f)
 
21
  with open("num_to_class.json", "r", encoding="utf-8") as f:
22
  idx2label = json.load(f)
 
23
  with open("class_inf.json", "r", encoding="utf-8") as f:
24
  plant_info = json.load(f)
25
 
@@ -29,88 +34,29 @@ transform = transforms.Compose([
29
  transforms.ToTensor(),
30
  ])
31
 
32
- # 存储检测记录(内存中)
33
- history = []
34
-
35
-
36
- def predict(image):
37
- image_tensor = transform(image).unsqueeze(0).to(device)
38
  with torch.no_grad():
39
- output = model(image_tensor)
40
  probs = torch.softmax(output, dim=1)
41
  conf, pred = torch.max(probs, 1)
42
- label_en = idx2label[str(pred.item())]
43
- label_cn = class_eg_to_cn[label_en]
44
- intro = plant_info.get(label_en, "暂无介绍")
45
-
46
- # 保存图像快照到本地(临时)
47
- os.makedirs("history_imgs", exist_ok=True)
48
- timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
49
- image_path = f"history_imgs/{timestamp}.png"
50
- image.save(image_path)
51
 
52
- # 添加到历史记录
53
- history.append({
54
- "image": image_path,
55
- "label": label_cn,
56
- "confidence": f"{conf.item():.2f}",
57
- "time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
58
- })
59
-
60
- return label_cn, float(conf.item()), intro
61
-
62
-
63
- def get_history():
64
- if not history:
65
- return [], [], [], []
66
- imgs = [entry["image"] for entry in history]
67
- labels = [entry["label"] for entry in history]
68
- confs = [entry["confidence"] for entry in history]
69
- times = [entry["time"] for entry in history]
70
- return imgs, labels, confs, times
71
-
72
-
73
- # UI
74
- with gr.Blocks(css="body { font-family: sans-serif; display: flex; }") as demo:
75
  with gr.Row():
76
- with gr.Column(scale=1, min_width=200): # Left navigation bar
77
- gr.Markdown("## 🌱 功能导航", elem_id="nav")
78
- btn1 = gr.Button("图像识别", elem_id="btn1")
79
- btn2 = gr.Button("检测记录", elem_id="btn2")
80
-
81
  with gr.Column(scale=3):
82
- # 图像识界面
83
- with gr.Box() as img_recognition:
84
- gr.Markdown("## 植物识别系统")
85
- with gr.Row():
86
- with gr.Column(scale=2):
87
- img_input = gr.Image(type="pil", label="上传植物图像")
88
- btn = gr.Button("识别")
89
- with gr.Column(scale=3):
90
- out_label = gr.Textbox(label="识别类别")
91
- out_conf = gr.Textbox(label="置信度")
92
- out_desc = gr.Textbox(label="植物介绍", lines=5)
93
- btn.click(fn=predict, inputs=img_input, outputs=[out_label, out_conf, out_desc])
94
-
95
- # 检测记录界面
96
- with gr.Box() as detection_history:
97
- gr.Markdown("## 最近识别记录")
98
- show_btn = gr.Button("刷新记录")
99
- history_gallery = gr.Gallery(label="历史图像", elem_id="history_gallery", columns=1, height="auto")
100
- label_list = gr.Textbox(label="识别类别")
101
- conf_list = gr.Textbox(label="置信度")
102
- time_list = gr.Textbox(label="检测时间")
103
-
104
- show_btn.click(fn=get_history, inputs=[], outputs=[history_gallery, label_list, conf_list, time_list])
105
-
106
- # 显示第一个界面
107
- img_recognition.visible = True
108
- detection_history.visible = False
109
 
110
- # 设置按钮点击事件来切换页面
111
- btn1.click(fn=lambda: (img_recognition.update(visible=True), detection_history.update(visible=False)), inputs=[],
112
- outputs=[])
113
- btn2.click(fn=lambda: (img_recognition.update(visible=False), detection_history.update(visible=True)), inputs=[],
114
- outputs=[])
115
 
116
- demo.launch()
 
1
+ # app.py
2
+ import json
3
+
4
  import gradio as gr
5
  import torch
6
  from torchvision import transforms
7
  from PIL import Image
 
8
  import os
 
9
  from model import get_mobilenet_model
10
 
11
+ # 自动检测是否使用GPU
12
  device = "cuda" if torch.cuda.is_available() else "cpu"
13
+
14
+ # 加载模型
15
+ weights_path = "best_model.pth"
16
  model, _, _ = get_mobilenet_model(num_classes=16)
17
+ checkpoint = torch.load(weights_path, map_location=device, weights_only=False)
18
+ model.load_state_dict(checkpoint['state_dict']) # 注意这里是 checkpoint['state_dict']
19
  model.to(device)
20
  model.eval()
21
 
 
22
  with open("class_eg_to_cn.json", "r", encoding="utf-8") as f:
23
  class_eg_to_cn = json.load(f)
24
+
25
  with open("num_to_class.json", "r", encoding="utf-8") as f:
26
  idx2label = json.load(f)
27
+
28
  with open("class_inf.json", "r", encoding="utf-8") as f:
29
  plant_info = json.load(f)
30
 
 
34
  transforms.ToTensor(),
35
  ])
36
 
37
+ # 推理函数
38
+ def predict(img):
39
+ image = transform(img).unsqueeze(0).to(device)
 
 
 
40
  with torch.no_grad():
41
+ output = model(image)
42
  probs = torch.softmax(output, dim=1)
43
  conf, pred = torch.max(probs, 1)
44
+ cn_label = class_eg_to_cn[idx2label[str(pred.item())]]
45
+ intro = plant_info.get(idx2label[str(pred.item())], "暂无介绍")
46
+ return cn_label, float(conf.item()), intro
 
 
 
 
 
 
47
 
48
+ # Gradio界面
49
+ with gr.Blocks(css="body { background-color: #90caf9; font-family: sans-serif; }") as demo:
50
+ gr.Markdown("## 🌱 基于深度学习的植物识别系统", elem_id="title")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  with gr.Row():
52
+ with gr.Column(scale=2):
53
+ image_input = gr.Image(type="pil", label="选择图像")
54
+ btn = gr.Button("开始检测", elem_id="detect")
 
 
55
  with gr.Column(scale=3):
56
+ label_output = gr.Textbox(label="类")
57
+ confidence_output = gr.Textbox(label="置信度")
58
+ description_output = gr.Textbox(label="相关介绍", lines=5)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
+ btn.click(fn=predict, inputs=image_input, outputs=[label_output, confidence_output, description_output])
 
 
 
 
61
 
62
+ demo.launch()