torch 中各种图像格式转换的实现方法
技术  /  管理员 发布于 7年前   322
PIL与Tensor相互转换
import torchfrom PIL import Imageimport matplotlib.pyplot as plt# loader使用torchvision中自带的transforms函数loader = transforms.Compose([ transforms.ToTensor()]) unloader = transforms.ToPILImage()# 输入图片地址# 返回tensor变量def image_loader(image_name): image = Image.open(image_name).convert('RGB') image = loader(image).unsqueeze(0) return image.to(device, torch.float)# 输入PIL格式图片# 返回tensor变量def PIL_to_tensor(image): image = loader(image).unsqueeze(0) return image.to(device, torch.float)# 输入tensor变量# 输出PIL格式图片def tensor_to_PIL(tensor): image = tensor.cpu().clone() image = image.squeeze(0) image = unloader(image) return image#直接展示tensor格式图片def imshow(tensor, title=None): image = tensor.cpu().clone() # we clone the tensor to not do changes on it image = image.squeeze(0) # remove the fake batch dimension image = unloader(image) plt.imshow(image) if title is not None: plt.title(title) plt.pause(0.001) # pause a bit so that plots are updated#直接保存tensor格式图片def save_image(tensor, **para): dir = 'results' image = tensor.cpu().clone() # we clone the tensor to not do changes on it image = image.squeeze(0) # remove the fake batch dimension image = unloader(image) if not osp.exists(dir): os.makedirs(dir) image.save('results_{}/s{}-c{}-l{}-e{}-sl{:4f}-cl{:4f}.jpg' .format(num, para['style_weight'], para['content_weight'], para['lr'], para['epoch'], para['style_loss'], para['content_loss']))
numpy 与 tensor相互转换
import cv2import torchimport matplotlib.pyplot as pltdef toTensor(img): assert type(img) == np.ndarray,'the img type is {}, but ndarry expected'.format(type(img)) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = torch.from_numpy(img.transpose((2, 0, 1))) return img.float().div(255).unsqueeze(0) # 255也可以改为256def tensor_to_np(tensor): img = tensor.mul(255).byte() img = img.cpu().numpy().squeeze(0).transpose((1, 2, 0)) return imgdef show_from_cv(img, title=None): img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) plt.figure() plt.imshow(img) if title is not None: plt.title(title) plt.pause(0.001)def show_from_tensor(tensor, title=None): img = tensor.clone() img = tensor_to_np(img) plt.figure() plt.imshow(img) if title is not None: plt.title(title) plt.pause(0.001)
N张图片一起转换.
# 将 N x H x W X C 的numpy格式图片转化为相应的tensor格式def toTensor(img): img = torch.from_numpy(img.transpose((0, 3, 1, 2))) return img.float().div(255).unsqueeze(0)
参考:https:///article/177291.htm
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号