首先在树莓派上搭建好pytorch环境,这里我python版本是3.7
下面要做的工作就是调用已经训练好的模板net=torch.load('模板的路径',map_location='cpu')
当然少不了对图像尺寸格式先进行统一
transform=transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485,0.456,0.406],
std=[0.229,0.224,0.225])
])
之后,就是基本一些调用,这些都可以在pytorch官网上查阅
下面我粘出我的完整代码:
import torch
from PIL import Image
from torchvision import transforms
import numpy
import matplotlib
device = torch.device("cuda"if torch.cuda.is_available() else "cpu")
#下面是对图像尺寸和格式进行一定的转换
transform=transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485,0.456,0.406],
std=[0.229,0.224,0.225])
])
def prediect(img_path):
net=torch.load('模型路径.pth',map_location='cpu')
net=net.to(device) #最开始读取数据时的tensor变量copy一份到device所指定的GPU上去,之后的运算都在GPU上进行。
torch.no_grad()
img=Image.open(img_path)
img=transform(img).unsqueeze(0)
img_ = img.to(device)
outputs = net(img_)
#torch.max()这个函数返回的是两个值,第一个是行的最大值,第二个是行最大值的索引,dim是max函数索引的维度0/1,0是每列的最大值,1是每行的最大值,计算准确度时我们只需要第二个
_, predicted = torch.max(outputs,dim=1)
# print(predicted)
d = predicted[0].tolist() # tensor张量转换为list,得到的结果是一个数字,这样会有利于我们的调用
print('照片可能是 :',d)
if __name__ == '__main__':
prediect('图片路径')
下面是我运行结果
这个15表示训练模型是的序列号