torch 中各种图像格式转换的实现方法

所属分类: 脚本专栏 / python 阅读数: 1666
收藏 0 赞 0 分享
  • PIL:使用python自带图像处理库读取出来的图片格式
  • numpy:使用python-opencv库读取出来的图片格式
  • tensor:pytorch中训练时所采取的向量格式(当然也可以说图片)

PIL与Tensor相互转换

import torch
from PIL import Image
import 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 cv2
import torch
import matplotlib.pyplot as plt

def 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也可以改为256

def tensor_to_np(tensor):
 img = tensor.mul(255).byte()
 img = img.cpu().numpy().squeeze(0).transpose((1, 2, 0))
 return img

def 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://www.jb51.net/article/177291.htm

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

Python常见加密模块用法分析【MD5,sha,crypt模块】

这篇文章主要介绍了Python常见加密模块用法,结合实例形式较为详细的分析了MD5,sha与crypt模块加密的相关实现方法与操作技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

Python向日志输出中添加上下文信息

这篇文章主要介绍了Python向日志输出中添加上下文信息的方法,非常不错,具有参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

Python实现的简单dns查询功能示例

这篇文章主要介绍了Python实现的简单dns查询功能,结合实例形式分析了Python基于socket模块的dns信息查询实现技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

利用Anaconda完美解决Python 2与python 3的共存问题

Anaconda 是 Python 的一个发行版,如果把 Python 比作 Linux,那么 Anancoda 就是 CentOS 或者 Ubuntu,下面这篇文章主要给大家介绍了利用Anaconda完美解决Python 2与python 3共存问题的相关资料,文中介绍的非常详
收藏 0 赞 0 分享

Python随机读取文件实现实例

这篇文章主要介绍了Python随机读取文件的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

用生成器来改写直接返回列表的函数方法

下面小编就为大家带来一篇用生成器来改写直接返回列表的函数方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

python爬虫入门教程--快速理解HTTP协议(一)

http协议是互联网里面最重要,最基础的协议之一,我们的爬虫需要经常和http协议打交道。下面这篇文章主要给大家介绍了关于python爬虫入门之快速理解HTTP协议的相关资料,文中介绍的非常详细,需要的朋友可以参考借鉴,下面来一起看看吧。
收藏 0 赞 0 分享

老生常谈Python进阶之装饰器

下面小编就为大家带来一篇老生常谈Python进阶之装饰器。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

浅谈Python基础之I/O模型

下面小编就为大家带来一篇浅谈Python基础之I/O模型。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

python如何获取服务器硬件信息

这篇文章主要为大家详细介绍了python获取服务器硬件信息的相关代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享
查看更多