torch 中各种图像格式转换
- 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://oldpan.me/archives/pytorch-tensor-image-transform
torch 中各种图像格式转换的更多相关文章
- OpenCV中IplImage图像格式与BYTE图像数据的转换
最近在将Karlsruhe Institute of Technology的Andreas Geiger发表在ACCV2010上的Efficent Large-Scale Stereo Matchin ...
- torch中的多线程threads学习
torch中的多线程threads学习 torch threads threads 包介绍 threads package的优势点: 程序中线程可以随时创建 Jobs被以回调函数的形式提交给线程系统, ...
- java中数据类型的转换
数据类型的转换,分为自动转换和强制转换. 自动转换是程序执行过程中“悄然”进行的转换,不需要用户提前声明,一般是从位数低的类型向位数高的类型转换 强制转换必须在代码中声明,转换顺序不受限制 自动数据类 ...
- java语言中数值自动转换的优先顺序
转换原则:从低精度向高精度转换byte .short.int.long.float.double.char数据类型的转换,分为自动转换和强制转换.自动转换是程序在执行过程中“悄然”进行的转换,不需要用 ...
- 关于myeclipse中maven项目转换相关设置
关于myeclipse中maven项目转换相关设置 在myeclipse菜单中,Configure->Convert to Maven Project 这个菜单 如果没有的话,需要做如下设置: ...
- java中汉字自动转换成拼音
java中汉字自动转换成拼音 1.需要下载jar包 pinyin4j.2.5.0.jar ,加入到WEB-INF下的lib里边,右键add to bulid path. 2.[代码]PinYinUti ...
- c++中的强制转换static_cast、dynamic_cast、reinterpret_cast的不同用法儿
c++中的强制转换static_cast.dynamic_cast.reinterpret_cast的不同用法儿 虽然const_cast是用来去除变量的const限定,但是static_cast ...
- .Net 中表达式的转换
.Net 中表达式的转换 如: a>0 && (c>a || a <b ) || (a>b || c>1) 转换后 (((a > 0) a ...
- js中的时间转换—毫秒转换成日期时间
转自:http://www.javascript100.com/?p=181 前几天,在项目中遇到js时间增加问题,要将js毫秒时间转换成日期时间 var oldTime = (new Date(&q ...
随机推荐
- 使用IDEA2017.3.5搭建SSM框架
转载自博客园,附上原文地址https://www.cnblogs.com/hackyo/p/6646051.html?utm_source=itdadao&utm_medium=referra ...
- 【集合系列】- 深入浅出的分析 Properties
一.摘要 在集合系列的第一章,咱们了解到,Map 的实现类有 HashMap.LinkedHashMap.TreeMap.IdentityHashMap.WeakHashMap.Hashtable.P ...
- 洛谷 3111 [USACO14DEC]牛慢跑Cow Jog_Sliver 题解
本蒟蒻又来发题解了, 一道较水的模拟题. 题意不过多解释, 思路如下: 在最开始的时候求出每头牛在t秒的位置(最终位置 然后,如果后一头牛追上了前一头牛,那就无视它, 把它们看成一个整体. else ...
- postman+newman+html测试报告(接口自动化)
1.安装node.js(Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境) 下载安装node.js,下载地址:https://nodejs.org/en/ 2.安 ...
- 牛客竞赛-Who killed Cock Robin
Who killed Cock Robin? I, said the Sparrow, With my bow and arrow,I killed Cock Robin. Who saw him d ...
- XML与JSON解析
[XML简介] XML在线校验工具: http://tool.oschina.net/codeformat/xml 可扩展标记语言(EXtensible Markup Language) 一种标记语言 ...
- 拓展KMP分析
拓展kmp是对KMP算法的扩展,它解决如下问题: 定义母串S,和字串T,设S的长度为n,T的长度为m,求T与S的每一个后缀的最长公共前缀,也就是说,设extend数组,extend[i]表示T与S[i ...
- Vue - 简单实现一个命令式弹窗组件
前言 在日常工作中弹窗组件是很常用的组件,但用得多还是别人的,空闲时间就自己来简单实现一个弹窗组件 涉及知识点:extend.$mount.$el 使用方式: this.$Confirm({ titl ...
- 纯手工搭建K8s(单节点)
准备说明: 因为为纯手动搭建,所以针对安装时需要的一些安装包需提前下载好 cfssl_linux-amd64. cfssljson_linux-amd64. cfssl-certinfo_linux- ...
- 高仿 django插拔式 及 settings配置文件
目录 基于django中间件实现插拔式 仿django settings 基于django中间件实现插拔式 start.py from notify import * send_all('好嗨哦') ...