写一段可运行的Python代码:基于Pytorch实现中药材中草药分类识别希望最后可以实现输入图片后自动输出中草药名称。
首先需要准备好训练好的模型和对应的标签,然后使用Pytorch中的torchvision库加载并预处理输入的图片,最后使用模型进行预测并输出结果。
示例代码如下:
import torch
import torchvision.transforms as transforms
from PIL import Image
# 加载模型和标签
model = torch.load('model.pth')
labels = ['草乌', '当归', '川芎', '丹参', '地黄', '黄芪', '枸杞子', '款冬花', '人参', '三七', '山药', '石斛', '首乌', '天麻', '五味子', '仙茅', '细辛', '玄参', '野菊花', '益母草']
# 读取输入图片并预处理
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])
])
img = Image.open('test.jpg')
img = transform(img)
img = img.unsqueeze(0) # 添加batch维度
# 使用模型进行预测
output = model(img)
_, predicted = torch.max(output, 1)
print('预测结果:', labels[predicted[0]])
其中,model.pth是训练好的模型文件,test.jpg是待识别的图片文件。labels是中药材的名称列表,根据模型输出的类别索引可以获取对应的中药材名称
原文地址: https://www.cveoy.top/t/topic/hsfA 著作权归作者所有。请勿转载和采集!