Spaces:
Sleeping
Sleeping
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(
|
| 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 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
def predict(image):
|
| 37 |
-
image_tensor = transform(image).unsqueeze(0).to(device)
|
| 38 |
with torch.no_grad():
|
| 39 |
-
output = model(
|
| 40 |
probs = torch.softmax(output, dim=1)
|
| 41 |
conf, pred = torch.max(probs, 1)
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 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 |
-
|
| 54 |
-
|
| 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=
|
| 77 |
-
gr.
|
| 78 |
-
|
| 79 |
-
btn2 = gr.Button("检测记录", elem_id="btn2")
|
| 80 |
-
|
| 81 |
with gr.Column(scale=3):
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 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()
|