Pytorch数据变换(Transform)
实例化数据库的时候,有一个可选的参数可以对数据进行转换,满足大多神经网络的要求输入固定尺寸的图片,因此要对原图进行Rescale或者Crop操作,然后返回的数据需要转换成Tensor如:
import FaceLandmarksDataset
face_dataset = FaceLandmarksDataset(csv_file='data/faces/face_landmarks.csv',
root_dir='data/faces/',
transform=transforms.Compose([ Rescale(256), RandomCrop(224), ToTensor()]) )
数据转换(Transfrom)发生在数据库中的__getitem__操作中。以上代码中,transforms.Compose(transform_list),Compose即组合的意思,其参数是一个转换操作的列表。如上是[ Rescale(256), RandomCrop(224), ToTensor()],以下是实现这三个转换类。我们将把它们写成可调用的类,而不是简单的函数,这样在每次调用转换时就不需要传递它的参数。为此,我们只需要实现__call__方法,如果需要,还需要实现__init__方法。然后我们可以使用这样的变换:
#创建一个转换可调用类的实例
tsfm = Transform(params)
#使用转换操作实例对样本sample进行转换
transformed_sample = tsfm(sample)
下面观察这些转换是如何应用于图像和标注的。(注:每一个操作对应一个类)
class Rescale(object):
"""Rescale the image in a sample to a given size. Args:
output_size (tuple or int): Desired output size. If tuple, output is
matched to output_size. If int, smaller of image edges is matched
to output_size keeping aspect ratio the same.
""" def __init__(self, output_size):
assert isinstance(output_size, (int, tuple))
self.output_size = output_size def __call__(self, sample):
image, landmarks = sample['image'], sample['landmarks'] h, w = image.shape[:2]
if isinstance(self.output_size, int):
if h > w:
new_h, new_w = self.output_size * h / w, self.output_size
else:
new_h, new_w = self.output_size, self.output_size * w / h
else:
new_h, new_w = self.output_size new_h, new_w = int(new_h), int(new_w) img = transform.resize(image, (new_h, new_w)) # h and w are swapped for landmarks because for images,
# x and y axes are axis 1 and 0 respectively
landmarks = landmarks * [new_w / w, new_h / h] return {'image': img, 'landmarks': landmarks} class RandomCrop(object):
"""Crop randomly the image in a sample. Args:
output_size (tuple or int): Desired output size. If int, square crop
is made.
""" def __init__(self, output_size):
assert isinstance(output_size, (int, tuple))
if isinstance(output_size, int):
self.output_size = (output_size, output_size)
else:
assert len(output_size) == 2
self.output_size = output_size def __call__(self, sample):
image, landmarks = sample['image'], sample['landmarks'] h, w = image.shape[:2]
new_h, new_w = self.output_size top = np.random.randint(0, h - new_h)
left = np.random.randint(0, w - new_w) image = image[top: top + new_h,
left: left + new_w] landmarks = landmarks - [left, top] return {'image': image, 'landmarks': landmarks} class ToTensor(object):
"""Convert ndarrays in sample to Tensors.""" def __call__(self, sample):
image, landmarks = sample['image'], sample['landmarks'] # swap color axis because
# numpy image: H x W x C
# torch image: C X H X W
image = image.transpose((2, 0, 1))
return {'image': torch.from_numpy(image),
'landmarks': torch.from_numpy(landmarks)}
以下来介绍转换的用法。
#获取一条数据
sample = face_dataset[index]
#单独进行操作
scale = Rescale(256)
crope= RandomCrop(224)
scale(sample)
crope(sample)
#使用Compose组合操作
compose = transforms.Compose([Rescale(256),RandomCrop(224)])
compose(sample)
上述转换后数据仍然是PIL类型,如果要求返回是一个tensor,那么还得在Compose的最后一个元素进行Totensor操作。
Pytorch数据变换(Transform)的更多相关文章
- pytorch空间变换网络
pytorch空间变换网络 本文将学习如何使用称为空间变换器网络的视觉注意机制来扩充网络.可以在DeepMind paper 阅读更多有关空间变换器网络的内容. 空间变换器网络是对任何空间变换的差异化 ...
- PyTorch数据加载处理
PyTorch数据加载处理 PyTorch提供了许多工具来简化和希望数据加载,使代码更具可读性. 1.下载安装包 scikit-image:用于图像的IO和变换 pandas:用于更容易地进行csv解 ...
- Pytorch数据读取框架
训练一个模型需要有一个数据库,一个网络,一个优化函数.数据读取是训练的第一步,以下是pytorch数据输入框架. 1)实例化一个数据库 假设我们已经定义了一个FaceLandmarksDataset数 ...
- kaggle数据挖掘竞赛初步--Titanic<数据变换>
完整代码: https://github.com/cindycindyhi/kaggle-Titanic 特征工程系列: Titanic系列之原始数据分析和数据处理 Titanic系列之数据变换 Ti ...
- R学习笔记 第五篇:数据变换和清理
在使用R的分组操作之前,首先要了解R语言包,包实质上是实现特定功能的,预先写好的代码库(library),R拥有大量的软件包,许多包都是由某一领域的专家编写的,但并不是所有的包都有很高的质量的,在使用 ...
- 【转载】PyTorch系列 (二):pytorch数据读取
原文:https://likewind.top/2019/02/01/Pytorch-dataprocess/ Pytorch系列: PyTorch系列(一) - PyTorch使用总览 PyTorc ...
- css变换transform 以及 行内元素的一些说明
变换transform的用法比较简单:[变换其实和普通的css属性,如color等没什么区别,可以为变换应用过渡或动画,就像其他普通css属性一样]#test { transform: transla ...
- R实战 第六篇:数据变换(aggregate+dplyr)
数据分析的工作,80%的时间耗费在处理数据上,而数据处理的主要过程可以分为:分离-操作-结合(Split-Apply-Combine),也就是说,首先,把数据根据特定的字段分组,每个分组都是独立的:然 ...
- Pytorch数据类型转换
Pytorch数据类型转换 载入模块生成数据 import torch import numpy as np a_numpy = np.array([1,2,3]) Numpy转换为Tensor a_ ...
随机推荐
- 【刷题】BZOJ 4817 [Sdoi2017]树点涂色
Description Bob有一棵n个点的有根树,其中1号点是根节点.Bob在每个点上涂了颜色,并且每个点上的颜色不同.定义一条路 径的权值是:这条路径上的点(包括起点和终点)共有多少种不同的颜色. ...
- 【刷题】BZOJ 2154 Crash的数字表格
Description 今天的数学课上,Crash小朋友学习了最小公倍数(Least Common Multiple).对于两个正整数a和b,LCM(a, b)表示能同时被a和b整除的最小正整数.例如 ...
- 【AGC010F】Tree Game
Description 有一棵\(n\)个节点的树(\(n \le 3000\)),第\(i\)条边连接\(a_i,b_i\),每个节点\(i\)上有\(A_i\)个石子,高桥君和青木君将在树上玩游戏 ...
- 【Cf #502 H】The Films(莫队)
题面的简述:总共有$m$种书,书架上共有$n$本书,给出$n$本书的种类,并有$Q$个询问,每次询问给出$l, r, k$.每次询问时都会先出现$k * m$本书,每种书各$k$本,然后再加入书架上的 ...
- joda-time 2.5 包简化java时间操作
原文:https://www.ibm.com/developerworks/cn/java/j-jodatime.html Joda-Time 简介 既然无法摆脱时间,为何不设法简化时间处理? J P ...
- 公钥与私钥对HTTPS的理解(数字证书的需要)
本文转自某大牛链接 文中首先解释了加密解密的一些基础知识和概念,然后通过一个加密通信过程的例子说明了加密算法的作用,以及数字证书的出现所起的作用.接着对数字证书做一个详细的解释,并讨论一下window ...
- UVALive 7505 Hungry Game of Ants (2015Ecfinal)
题意: 长度是n的线段上点的编号从1~n,每个点有一只蚂蚁蚂蚁的体重等于该点的编号,最初每只蚂蚁可以选择向右走或者向左走两只蚂蚁相遇时体重大的吃掉体重小的并且体重增加为两只的体重和,走到边界时掉头,问 ...
- .gitignore 无效问题
利用.gitignore过滤文件,如编译过程中的中间文件,等等,这些文件不需要被追踪管理. 现象: 在.gitignore添加file1文件,以过滤该文件,但是通过Git status查看仍显示fil ...
- rsync命令的基本使用
rsync命令的基本使用 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. rsync服务软件是一款开源,高速的,数据同步(拷贝)工具. 一.rsync服务的特点 1>.本地拷贝 ...
- [Java] 集合框架原理之一:基本结构与源码分析
一.Collection Collection 接口定义了一些基本的方法: int size(); boolean isEmpty(); boolean add(E e); boolean addAl ...