torchvision库简介(翻译)
部分跟新于:4.24日 torchvision 0.2.2.post3
torchvision是独立于pytorch的关于图像操作的一些方便工具库。
torchvision的详细介绍在:https://pypi.org/project/torchvision/
torchvision主要包括一下几个包:
- vision.datasets : 几个常用视觉数据集,可以下载和加载,这里主要的高级用法就是可以看源码如何自己写自己的Dataset的子类
- vision.models : 流行的模型,例如 AlexNet, VGG, ResNet 和 Densenet 以及 与训练好的参数。
- vision.transforms : 常用的图像操作,例如:随机切割,旋转,数据类型转换,图像到tensor ,numpy 数组到tensor , tensor 到 图像等。
- vision.utils : 用于把形似 (3 x H x W) 的张量保存到硬盘中,给一个mini-batch的图像可以产生一个图像格网。
安装
Anaconda:
conda install torchvision -c pytorch
pip:
pip install torchvision 由于此包是配合pytorch的对于图像处理来说必不可少的,
对于以后要用的torch来说一站式的anaconda是首选,毕竟人生苦短。
(anaconda + vscode +pytorch 非常好用) 值得推荐!
以下翻译自 : https://pytorch.org/docs/master/torchvision/
数据集 torchvision.datasets
包括以下数据集:
数据集有 API: - __getitem__ - __len__ 他们都是 torch.utils.data.Dataset的子类。这样我们在实现我们自己的Dataset数据集的时候至少要实现上边两个方法。
因此, 他们可以使用torch.utils.data.DataLoader里的多线程 (python multiprocessing) 。
例如:
torch.utils.data.DataLoader(coco_cap, batch_size=args.batchSize, shuffle=True, num_workers=args.nThreads)
在构造上每个数据集的API有一些轻微的差异,但是都包含以下参数:
- transform - 接受一个图像返回变换后的图像的函数
- 常用的操作如 ToTensor, RandomCrop等. 他们可以通过transforms.Compose被组合在一起。 (见以下transforms 章节)
- target_transform - 一个对目标值进行变换的函数。例如,输入一个图片描述,返回一个编码后的张量(a tensor of word indices)。
每个数据集都有类似参数,所以很容易通过一个掌握其他全部。
MNIST
dset.MNIST(root, train=True, transform=None, target_transform=None, download=False)
root:数据的目录,里边有 processed/training.pt 和processed/test.pt 的内容
train: True -使用训练集, False -使用测试集.
transform: 给输入图像施加变换
target_transform:给目标值(类别标签)施加的变换
download: 是否下载mnist数据集
COCO
This requires the COCO API to be installed
Captions:
dset.CocoCaptions(root="dir where images are", annFile="json annotation file", [transform, target_transform])
Example:
import torchvision.datasets as dset
import torchvision.transforms as transforms
cap = dset.CocoCaptions(root = 'dir where images are',
annFile = 'json annotation file',
transform=transforms.ToTensor()) print('Number of samples: ', len(cap))
img, target = cap[3] # load 4th sample print("Image Size: ", img.size())
print(target)
Output:
Number of samples: 82783
Image Size: (3L, 427L, 640L)
[u'A plane emitting smoke stream flying over a mountain.',
u'A plane darts across a bright blue sky behind a mountain covered in snow',
u'A plane leaves a contrail above the snowy mountain top.',
u'A mountain that has a plane flying overheard in the distance.',
u'A mountain view with a plume of smoke in the background']
Detection:
dset.CocoDetection(root="dir where images are", annFile="json annotation file", [transform, target_transform])
LSUN
dset.LSUN(db_path, classes='train', [transform, target_transform])
- db_path = root directory for the database files
- classes =
- 'train' - all categories, training set
- 'val' - all categories, validation set
- 'test' - all categories, test set
- ['bedroom_train', 'church_train', …] : a list of categories to load
CIFAR
dset.CIFAR10(root, train=True, transform=None, target_transform=None, download=False)
dset.CIFAR100(root, train=True, transform=None, target_transform=None, download=False)
- root : root directory of dataset where there is folder cifar-10-batches-py
- train : True = Training set, False = Test set
- download : True = downloads the dataset from the internet and puts it in root directory. If dataset is already downloaded, does not do anything.
STL10
dset.STL10(root, split='train', transform=None, target_transform=None, download=False)
root : root directory of dataset where there is folder stl10_binary
- split : 'train' = Training set, 'test' = Test set, 'unlabeled' = Unlabeled set,
-
'train+unlabeled' = Training + Unlabeled set (missing label marked as -1)
- download : True = downloads the dataset from the internet and
-
puts it in root directory. If dataset is already downloaded, does not do anything.
SVHN
dset.SVHN(root, split='train', transform=None, target_transform=None, download=False)
root : root directory of dataset where there is folder SVHN
split : 'train' = Training set, 'test' = Test set, 'extra' = Extra training set
- download : True = downloads the dataset from the internet and
-
puts it in root directory. If dataset is already downloaded, does not do anything.
ImageFolder
一个通用的数据加载器,图像应该按照以下方式放置:
root/dog/xxx.png
root/dog/xxy.png
root/dog/xxz.png root/cat/123.png
root/cat/nsdf3.png
root/cat/asd932_.png
dset.ImageFolder(root="root folder path", [transform, target_transform])
ImageFolder有以下成员:
- self.classes - 类别名列表
- self.class_to_idx - 类别名到标签,例如 “狗”-->[1,0,0]
- self.imgs - 一个包括 (image path, class-index) 元组的列表。
Imagenet-12
This is simply implemented with an ImageFolder dataset.
The data is preprocessed as described here
PhotoTour
Learning Local Image Descriptors Data http://phototour.cs.washington.edu/patches/default.htm
import torchvision.datasets as dset
import torchvision.transforms as transforms
dataset = dset.PhotoTour(root = 'dir where images are',
name = 'name of the dataset to load',
transform=transforms.ToTensor()) print('Loaded PhotoTour: {} with {} images.'
.format(dataset.name, len(dataset.data)))
模型
models 子包含了以下的模型框架:
这里对于每种模型里可能包含很多子模型,比如Resnet就有 34,51,101,152不同层数。
这些成熟的模型的意义就是你可以在torchvision的安装路径下找到 可以通过命令 print(torchvision.models.__file__) #'d:\\Anaconda3\\lib\\site-packages\\torchvision\\models\\__init__.py'
学习这些优秀的模型是如何搭建的。
你可以用随机参数初始化一个模型:
import torchvision.models as models
resnet18 = models.resnet18()
alexnet = models.alexnet()
vgg16 = models.vgg16()
squeezenet = models.squeezenet1_0()
我们提供了预训练的ResNet的模型参数,以及 SqueezeNet 1.0 and 1.1, and AlexNet, 使用 PyTorch model zoo. 可以在构造函数里添加 pretrained=True:
import torchvision.models as models
resnet18 = models.resnet18(pretrained=True)
alexnet = models.alexnet(pretrained=True)
squeezenet = models.squeezenet1_0(pretrained=True)
所有的预训练模型期待输入同样标准化的数据,例如mini-baches 包括形似(3*H*W)的3通道的RGB图像,H,W最少是224。
图像的范围必须在[0,1]之间,然后使用 mean=[0.485, 0.456, 0.406] and std=[0.229, 0.224, 0.225] 进行标准化。
相关的例子在: the imagenet example here <https://github.com/pytorch/examples/blob/42e5b996718797e45c46a25c55b031e6768f8440/imagenet/main.py#L89-L101>
变换
变换(Transforms)是常用的图像变换。可以通过 transforms.Compose进行连续操作:
transforms.Compose
你可以组合几个变换在一起,例如:
transform = transforms.Compose([
transforms.RandomSizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean = [ 0.485, 0.456, 0.406 ],
std = [ 0.229, 0.224, 0.225 ]),
])
PIL.Image支持的变换
Scale(size, interpolation=Image.BILINEAR)
缩放输入的 PIL.Image到给定的“尺寸”。 ‘尺寸’ 指的是较短边的尺寸.
例如,如果 height > width, 那么图像将被缩放为 (size * height / width, size) - size: 图像较短边的尺寸- interpolation: Default: PIL.Image.BILINEAR
CenterCrop(size) - 从中间裁剪图像到指定大小
从中间裁剪一个 PIL.Image 到给定尺寸. 尺寸可以是一个元组 (target_height, target_width) 或一个整数,整数将被认为是正方形的尺寸 (size, size)
RandomCrop(size, padding=0)
Crops the given PIL.Image at a random location to have a region of the given size. size can be a tuple (target_height, target_width) or an integer, in which case the target will be of a square shape (size, size) If padding is non-zero, then the image is first zero-padded on each side with padding pixels.
RandomHorizontalFlip()
随机进行PIL.Image图像的水平翻转,概率是0.5.
RandomSizedCrop(size, interpolation=Image.BILINEAR)
Random crop the given PIL.Image to a random size of (0.08 to 1.0) of the original size and and a random aspect ratio of 3/4 to 4/3 of the original aspect ratio
This is popularly used to train the Inception networks - size: size of the smaller edge - interpolation: Default: PIL.Image.BILINEAR
Pad(padding, fill=0)
Pads the given image on each side with padding number of pixels, and the padding pixels are filled with pixel value fill. If a 5x5 image is padded with padding=1 then it becomes 7x7
对于 torch.*Tensor 的变换
Normalize(mean, std)
Given mean: (R, G, B) and std: (R, G, B), will normalize each channel of the torch.*Tensor, i.e. channel = (channel - mean) / std
转换变换
- ToTensor() - Converts a PIL.Image (RGB) or numpy.ndarray (H x W x C) in the range [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0]
- ToPILImage() - Converts a torch.*Tensor of range [0, 1] and shape C x H x W or numpy ndarray of dtype=uint8, range[0, 255] and shape H x W x C to a PIL.Image of range [0, 255]
广义变换
Lambda(lambda)
Given a Python lambda, applies it to the input img and returns it. For example:
transforms.Lambda(lambda x: x.add(10))
便利函数
make_grid(tensor, nrow=8, padding=2, normalize=False, range=None, scale_each=False)
Given a 4D mini-batch Tensor of shape (B x C x H x W), or a list of images all of the same size, makes a grid of images
normalize=True will shift the image to the range (0, 1), by subtracting the minimum and dividing by the maximum pixel value.
if range=(min, max) where min and max are numbers, then these numbers are used to normalize the image.
scale_each=True will scale each image in the batch of images separately rather than computing the (min, max) over all images.
Example usage is given in this notebook <https://gist.github.com/anonymous/bf16430f7750c023141c562f3e9f2a91>
save_image(tensor, filename, nrow=8, padding=2, normalize=False, range=None, scale_each=False)
Saves a given Tensor into an image file.
If given a mini-batch tensor, will save the tensor as a grid of images.
All options after filename are passed through to make_grid. Refer to it’s documentation for more details
用以输出图像的拼接,很方便。
没想到这篇文章阅读量这么大,考虑跟新下。
图像引擎:由于需要读取处理图片所以需要相关的图像库。现在torchvision可以支持多个图像读取库,可以切换。
使用的函数是:
torchvision.
get_image_backend
() #获取图像存取引擎
torchvision.
set_image_backend
(backend) #改变图像读取引擎
#backend (string) –图像引擎的名字:是 {‘PIL’, ‘accimage’}其中之一。 accimage
包使用的是因特尔(Intel) IPP 库。它的速度快于PIL,但是并不支持很多的图像操作。
由于这个是后边的,普通用处不大,知道即可。
torchvision库简介(翻译)的更多相关文章
- BerkeleyDB库简介
BerkeleyDB库简介 BerkeleyDB(简称为BDB)是一种以key-value为结构的嵌入式数据库引擎: 嵌入式:bdb提供了一系列应用程序接口(API),调用这些接口很简单,应用程序和b ...
- LevelDB库简介
LevelDB库简介 一.LevelDB入门 LevelDB是Google开源的持久化KV单机数据库,具有很高的随机写,顺序读/写性能,但是随机读的性能很一般,也就是说,LevelDB很适合应用在查询 ...
- MXNet深度学习库简介
MXNet深度学习库简介 摘要: MXNet是一个深度学习库, 支持C++, Python, R, Scala, Julia, Matlab以及JavaScript等语言; 支持命令和符号编程; 可以 ...
- Python3.x:第三方库简介
Python3.x:第三方库简介 环境管理 管理 Python 版本和环境的工具 p – 非常简单的交互式 python 版本管理工具. pyenv – 简单的 Python 版本管理工具. Vex ...
- php spl标准库简介(SPL是Standard PHP Library(PHP标准库)(直接看代码实例,特别方便)
php spl标准库简介(SPL是Standard PHP Library(PHP标准库)(直接看代码实例,特别方便) 一.总结 直接看代码实例,特别方便易懂 thinkphp控制器利眠宁不支持(说明 ...
- 免费淘宝IP地址库简介及PHP/C#调用实例
https://yq.aliyun.com/ziliao/25800?spm=a2c4e.11155472.0.0.68027abfcpFb7O 摘要: 本文讲的是免费淘宝IP地址库简介及PHP/C# ...
- c++模板库(简介)
目 录 STL 简介 ......................................................................................... ...
- 如何构建你自己的Java库【翻译】
原文http://www.programcreek.com/2011/07/build-a-java-library-for-yourself/ 原文和翻译都只是参考,如有不对,欢迎指正. 代码复用是 ...
- css公共库——简介中超过长度显示省略号
在简介.引言中常见:文字只有一排,超出宽度以省略号显示,像这样 实现方法:在公共库定义otw类 .otw{ overflow: hidden; text-overflow: ellipsis; whi ...
随机推荐
- Mysql 数据库意向锁意义
锁:对 “某种范围” 的数据上 “某种锁”1.“某种范围”:行.表 2.“某种锁”2.1 共享锁Shared Locks(S锁)1.兼容性:加了S锁的记录,允许其他事务再加S锁,不允许其他事务再加X锁 ...
- JDBC:随机生成车牌号,批量插入数据库
package InsertTest; /* * 单客户端:批量插入 */ import java.sql.Connection; import java.sql.DriverManager; imp ...
- 解决WDCP3环境gbk网站编码程序乱码问题
因为默认WDCP V3版本环境编码格式是UTF-8版本,如果我们程序采用的是GBK编码肯定都会有乱码问题. 我们到WDCP后台,"网站管理"-"PHP设置",看 ...
- log4net 2.0.8 不支持core 数据库记录日志
经过反编译log4net 标准库的代码,原本有的数据库链接AdoNetAppender 在core里面引用的,没有掉了. 可能新版本会有.
- 强化学习8-时序差分控制离线算法Q-Learning
Q-Learning和Sarsa一样是基于时序差分的控制算法,那两者有什么区别呢? 这里已经必须引入新的概念 时序差分控制算法的分类:在线和离线 在线控制算法:一直使用一个策略选择动作和更新价值函数, ...
- L249 语法
Even when homeless individuals manage to find a shelter that will give them three meals a day and a ...
- 关于“用VS2010的C++导入ADO导入不了,提示无法打开源文件msado15.tlh”的问题
vc++2010中,要使用ado操作数据库,所以在stdafx.h中引入了ado的dll库,引入代码如下: #import "C:/Program Files/Common Files/Sy ...
- 解决At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs
在写spring security小程序时遇到 At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug l ...
- python之pandas用法大全
python之pandas用法大全 更新时间:2018年03月13日 15:02:28 投稿:wdc 我要评论 本文讲解了python的pandas基本用法,大家可以参考下 一.生成数据表1.首先导入 ...
- sqlite的数据类型
参考sqlite官方文档:https://www.sqlite.org/datatype3.html 绝大多数的SQL数据库采用静态的.严格的数据类型,数据库中的值由数据表的列类型定义决定. 然而,s ...