轻松学Pytorch-使用ResNet50实现图像分类

时间:2022-07-22
本文章向大家介绍轻松学Pytorch-使用ResNet50实现图像分类,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

微信公众号:OpenCV学堂 关注获取更多计算机视觉与深度学习知识

Hello大家好,这篇文章给大家详细介绍一下pytorch中最重要的组件torchvision,它包含了常见的数据集、模型架构与预训练模型权重文件、常见图像变换、计算机视觉任务训练。可以是说是pytorch中非常有用的模型迁移学习神器。本文将会介绍如何使用torchvison的预训练模型ResNet50实现图像分类。

模型

Torchvision.models包里面包含了常见的各种基础模型架构,主要包括:

AlexNet VGG ResNet SqueezeNet DenseNet Inception v3 GoogLeNet ShuffleNet v2 MobileNet v2 ResNeXt Wide ResNet MNASNet

这里我选择了ResNet50,基于ImageNet训练的基础网络来实现图像分类, 网络模型下载与加载如下:

model = torchvision.models.resnet50(pretrained=True).eval().cuda()
tf = 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]
        )])

使用模型实现图像分类

这里首先需要加载ImageNet的分类标签,目的是最后显示分类的文本标签时候使用。然后对输入图像完成预处理,使用ResNet50模型实现分类预测,对预测结果解析之后,显示标签文本,完整的代码演示如下:

with open('imagenet_classes.txt') as f:
    labels = [line.strip() for line in f.readlines()]

src = cv.imread("D:/images/space_shuttle.jpg") # aeroplane.jpg
image = cv.resize(src, (224, 224))
image = np.float32(image) / 255.0
image[:,:,] -= (np.float32(0.485), np.float32(0.456), np.float32(0.406))
image[:,:,] /= (np.float32(0.229), np.float32(0.224), np.float32(0.225))
image = image.transpose((2, 0, 1))
input_x = torch.from_numpy(image).unsqueeze(0)
print(input_x.size())
pred = model(input_x.cuda())
pred_index = torch.argmax(pred, 1).cpu().detach().numpy()
print(pred_index)
print("current predict class name : %s"%labels[pred_index[0]])
cv.putText(src, labels[pred_index[0]], (50, 50), cv.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 2)
cv.imshow("input", src)
cv.waitKey(0)
cv.destroyAllWindows()

运行结果如下:

转ONNX支持

在torchvision中的模型基本上都可以转换为ONNX格式,而且被OpenCV DNN模块所支持,所以,很方便的可以对torchvision自带的模型转为ONNX,实现OpenCV DNN的调用,首先转为ONNX模型,直接使用torch.onnx.export即可转换(还不知道怎么转,快点看前面的例子)。转换之后使用OpenCV DNN调用的代码如下:

with open('imagenet_classes.txt') as f:
    labels = [line.strip() for line in f.readlines()]
net = cv.dnn.readNetFromONNX("resnet.onnx")
src = cv.imread("D:/images/messi.jpg")  # aeroplane.jpg
image = cv.resize(src, (224, 224))
image = np.float32(image) / 255.0
image[:, :, ] -= (np.float32(0.485), np.float32(0.456), np.float32(0.406))
image[:, :, ] /= (np.float32(0.229), np.float32(0.224), np.float32(0.225))
blob = cv.dnn.blobFromImage(image, 1.0, (224, 224), (0, 0, 0), False)
net.setInput(blob)
probs = net.forward()
index = np.argmax(probs)
cv.putText(src, labels[index], (50, 50), cv.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 2)
cv.imshow("input", src)
cv.waitKey(0)
cv.destroyAllWindows()

运行结果见上图,这里就不再贴了。