#-*-coding: UTF-8 -*-
import torch
from PIL import Image
from torchvision import transforms
import cv2
import numpy as np
device = torch.device('cuda')
transform=transforms.Compose([
transforms.Resize(224),
# 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 ="/home/shiyy/nas/all_workspace/cattle_recognition/data/second_cow/all/filter_day_night_aug/0/day_13301_000018.jpg-head-110_320_697_868.jpg"
model = torch.load("./models/dayn_resnet34_cow_best_model.pth") #402 out
model.eval() #必须加评估
device = torch.device('cuda')
net=model
net = net.cuda()#=net.to(device) 转移到CUDA上
torch.no_grad()
img=Image.open(img_path)
img=transform(img).unsqueeze(0)
img_ = img.cuda()#img.to(device) 转移到CUDA上
outputs = net(img_)
_, predicted = torch.max(outputs, 1) #返回一维数组
print (predicted.shape) #tensor([0], device='cuda:0'))
print (predicted[0].cpu()) #cuda tensor 变成 cpu tensor
print (predicted[0].item()) #一个,tensor,值直接取得元素
# prediect() ##PIL读取图片测试
###或者 cv2读取图片返回
def one_img(image):## 填充白色,左右填充,resize 不变形
# image = cv2.imread("/home/shiyy/nas/all_workspace/cattle_recognition/data/second_cow/night_crop_head/2/IMG_20191029_183533.jpg-head-1154_444_2517_2840.jpg")
target_size=224#max(height,width)
height = image.shape[0]
width = image.shape[1]
if height !=width: #如果长宽不同,用最大值,作为目标resize,尺寸
height = image.shape[0]
width = image.shape[1]
ratio = float(height) / width
# if ratio > 100.0 or ratio < 0.01:
# continue
if height >= width:
height = target_size
width = int(target_size / ratio)
top_offset = 0
bottom_offset = 0
if (target_size - width) % 2 == 0:
left_offset = int((target_size - width) / 2)
right_offset = int((target_size - width) / 2)
else:
left_offset = int((target_size - width) / 2) + 1
right_offset = int((target_size - width) / 2)
else:
width = target_size
height = int(target_size * ratio)
left_offset = 0
right_offset = 0
if (target_size - height) % 2 == 0:
top_offset = int((target_size - height) / 2)
bottom_offset = int((target_size - height) / 2)
else:
top_offset = int((target_size - height) / 2) + 1
bottom_offset = int((target_size - height) / 2)
resize_img = cv2.resize(image, (width, height))
WHITE = [255,255,255]
resize_img = cv2.copyMakeBorder(resize_img, top_offset, bottom_offset,
left_offset, right_offset, cv2.BORDER_CONSTANT, value=WHITE)
# print (image.shape)
# cv2.imshow("see", resize_img)
# cv2.waitKey(0)
return resize_img
else :
resize_img = cv2.resize(image, (target_size,target_size))
return resize_img
def cv2img_process(img):
####分类图片预处理,
img = one_img(img)#add pad white resize 224
assert (img.shape[0]==224 and img.shape[1]==224),"img not resize 224"
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
img = np.float32(img)
img = np.ascontiguousarray(img[..., ::-1])
img = img.transpose(2, 0, 1)# Convert Img from BGR to RGB
for channel, _ in enumerate(img):
# Normalization
img[channel] /= 255
img[channel] -= mean[channel]
img[channel] /= std[channel]
# img = (img/255 - mean) / std
# Convert to float tensor
img = torch.from_numpy(img).float().unsqueeze(0) #chw to bchw,加一个维度,并将numpy 变成torch
print (type(img))
print (img.shape)
# Convert to Pytorch variable
# img = Variable(img, requires_grad=false)
return img
def prediect():
img_path ="/home/shiyy/nas/all_workspace/cattle_recognition/data/second_cow/all/filter_day_night_aug/0/day_13301_000018.jpg-head-110_320_697_868.jpg"
model = torch.load("./models/dayn_resnet34_cow_best_model.pth") #402 out
model.eval() #必须加评估,否则输出值不对
device = torch.device('cuda')
net=model
net = net.cuda()#=net.to(device) 转移到CUDA上
torch.no_grad()
img=cv2.imread(img_path)
img_ = cv2img_process(img) #数据处理,need to bchw
img_=img_.cuda()
outputs = net(img_)
_, predicted = torch.max(outputs, 1) #返回一维数组
print (predicted.shape) #tensor([0], device='cuda:0'))
print (predicted[0].cpu()) #cuda tensor 变成 cpu tensor
print (predicted[0].item()) #一个,tensor,值直接取得元素
prediect()
pytorch 读取,训练数据加变量Variable,在GPU上加速处理
https://blog.csdn.net/qq_41776781/article/details/93967961 Variable的理解
https://blog.csdn.net/weixin_41680653/article/details/93750326 pytorch文档阅读(四)如何在GPU上训练
https://blog.csdn.net/ax7399/article/details/84557410 pytorch使用指定GPU训练
# 首先是引入pytorch相关的数据包
import torch
from torch.autograd import Variable
# 然后定义pytorch中的tensor 并将tensor转化成Variable的形式
x_tensor = torch.ones(3)
print('张量的类型以及具体值:\n', type(x_tensor), x_tensor)
x_var = Variable(x_tensor, requires_grad = True)
print('变量的类型以及具体的值:\n', type(x_var), x_var)
criterion = nn.CrossEntropyLoss()
criterion = criterion.cuda()
loss = criterion(out, label)
#download the dataset
train_set = CIFAR10("./data_cifar10", train=True, transform=data_tf, download=True)
train_data = torch.utils.data.DataLoader(train_set, batch_size=64, shuffle=True)
for im, label in train_data:
i = i + 1
im = im.cuda()#把数据迁移到CUDA上
im = Variable(im)#把数据放到Variable里
label = label.cuda()
label =Variable(label)
out = net(im)#the output should have the size of (N,10)
低版本加载高版本,pytorch 模型
def load_network(self, load_path, network, strict=True):
if isinstance(network, nn.DataParallel):
network = network.module
model_dict = torch.load(load_path)
filtered = {k: v for k, v in model_dict.items() if 'num_batches_tracked' not in k}
network.load_state_dict(filtered, strict=strict)
# network.load_state_dict(torch.load(load_path), strict=strict)
Pytorch1.0 与 0.4版的兼容问题解决
https://blog.csdn.net/qq_36038293/article/details/88911792
https://www.jianshu.com/p/cfca9c4338e7,pytorch 三种格式加载图片
https://www.cnblogs.com/ocean1100/p/9494640.html图片转换细节
to_tensor()函数看到,函数接受PIL Image或numpy.ndarray,将其先由HWC转置为CHW格式,再转为float后每个像素除以255.