torch 中各种图像格式转换的实现方法
作者:core! 时间:2021-04-17 08:08:13
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
来源:https://www.cnblogs.com/sdu20112013/p/11983437.html
标签:torch,图像,转换
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
原生JS封装_new函数实现new关键字的功能
2023-09-05 00:44:27
![](https://img.aspxhome.com/file/2023/1/56041_0s.png)
FCKeditor 编辑器实战技巧 Ⅰ
2008-10-08 10:22:00
![](https://img.aspxhome.com/file/uploadpic/20071/200713110656772.gif)
对python:threading.Thread类的使用方法详解
2022-01-24 04:19:28
PHP header()函数使用详细(301、404等错误设置)
2023-11-02 17:28:23
ORACLE客户端连接服务器的注意事项
2007-08-17 09:57:00
Dreamweaver使用快技法十三则
2009-07-21 12:45:00
利用Python破解生日悖论问题
2022-11-08 02:37:55
![](https://img.aspxhome.com/file/2023/5/67365_0s.jpg)
菜鸟大讲堂:如何查看mysql版本的四种方法
2009-09-05 09:54:00
Python Matplotlib绘制动图平滑曲线
2022-12-28 22:23:40
![](https://img.aspxhome.com/file/2023/0/78490_0s.png)
python使用cPickle模块序列化实例
2022-06-26 22:35:09
Python如何创建装饰器时保留函数元信息
2023-03-29 12:32:46
用代码帮你了解Python基础(3)
2021-03-20 07:22:46
php 一维数组的循环遍历实现代码
2023-06-12 00:49:04
![](https://img.aspxhome.com/file/2023/9/55469_0s.jpg)
Python3.x+pyqtgraph实现数据可视化教程
2023-09-25 23:24:47
![](https://img.aspxhome.com/file/2023/5/69515_0s.jpg)
asp 正则实现清除html文本格式的函数代码
2011-03-09 11:21:00
GC与JS内存泄露
2010-09-25 19:01:00
![](https://img.aspxhome.com/file/UploadPic/20109/25/01-21s.jpg)
Python实现简易五子棋游戏
2023-02-04 07:02:22
![](https://img.aspxhome.com/file/2023/8/65488_0s.jpg)
交互设计:简单
2011-08-27 16:46:27
JS Object.preventExtensions(),Object.seal()与Object.freeze()用法实例分析
2023-09-04 22:44:33
CSS Sprites
2007-10-10 13:21:00