文章目录
建立目录
用来存放测试的图片与结果
# 建立目录
if os.path.exists('test_img'):
print('{} is exited'.format('test_img'))
else:
# 存放测试图片
os.mkdir('test_img')
if os.path.exists('output'):
print('{} is exited'.format('output'))
else:
# 存放结果文件
os.mkdir('output')
代码
使用pytorch自带的 resnet18 模型来预测单张图片的类别,其流程如下:
- 载入数据集
- 对图像进行预处理
- 模型预测
- softmax输出结果
- 对结果进行处理
# coding:gbk
import os
from tkinter import N
from tkinter.tix import InputOnly
from tkinter.ttk import LabeledScale
from tokenize import Ignore
import cv2
import pandas as pd
import numpy as np
import torch
import matplotlib.pyplot as plt
from torchvision import models
from torchvision import transforms
from PIL import Image
import torch.nn.functional as F
import matplotlib
from IPython.display import display
# 预训练图像分类模型预测单张图像-英文
def predict_single_pic_en(img_path,output_path,csv_path):
# 使用GPU
device=torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
print('device:',device)
model=models.resnet18(weights=models.ResNet18_Weights.IMAGENET1K_V1)
# dir(models)# 可以看到所有的模型
model=model.eval()
model=model.to(device)
# 图像预处理:测试集图像预处理-RCTN:缩放裁剪、转Tensor、归一化 只接收pillow格式的图像
test_transform=transforms.Compose([transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485,0.456