PyTorch之图像和Tensor填充的实例


Posted in Python onAugust 18, 2019

在PyTorch中可以对图像和Tensor进行填充,如常量值填充,镜像填充和复制填充等。在图像预处理阶段设置图像边界填充的方式如下:

import vision.torchvision.transforms as transforms
 
img_to_pad = transforms.Compose([
    transforms.Pad(padding=2, padding_mode='symmetric'),
    transforms.ToTensor(),
   ])

对Tensor进行填充的方式如下:

import torch.nn.functional as F
 
feature = feature.unsqueeze(0).unsqueeze(0)
avg_feature = F.pad(feature, pad = [1, 1, 1, 1], mode='replicate')

这里需要注意一点的是,transforms.Pad只能对PIL图像格式进行填充,而F.pad可以对Tensor进行填充,目前F.pad不支持对2D Tensor进行填充,可以通过unsqueeze扩展为4D Tensor进行填充。

F.pad的部分源码如下:

@torch._jit_internal.weak_script
def pad(input, pad, mode='constant', value=0):
 # type: (Tensor, List[int], str, float) -> Tensor
 r"""Pads tensor.
 Pading size:
  The number of dimensions to pad is :math:`\left\lfloor\frac{\text{len(pad)}}{2}\right\rfloor`
  and the dimensions that get padded begins with the last dimension and moves forward.
  For example, to pad the last dimension of the input tensor, then `pad` has form
  `(padLeft, padRight)`; to pad the last 2 dimensions of the input tensor, then use
  `(padLeft, padRight, padTop, padBottom)`; to pad the last 3 dimensions, use
  `(padLeft, padRight, padTop, padBottom, padFront, padBack)`.
 Padding mode:
  See :class:`torch.nn.ConstantPad2d`, :class:`torch.nn.ReflectionPad2d`, and
  :class:`torch.nn.ReplicationPad2d` for concrete examples on how each of the
  padding modes works. Constant padding is implemented for arbitrary dimensions.
  Replicate padding is implemented for padding the last 3 dimensions of 5D input
  tensor, or the last 2 dimensions of 4D input tensor, or the last dimension of
  3D input tensor. Reflect padding is only implemented for padding the last 2
  dimensions of 4D input tensor, or the last dimension of 3D input tensor.
 .. include:: cuda_deterministic_backward.rst
 Args:
  input (Tensor): `Nd` tensor
  pad (tuple): m-elem tuple, where :math:`\frac{m}{2} \leq` input dimensions and :math:`m` is even.
  mode: 'constant', 'reflect' or 'replicate'. Default: 'constant'
  value: fill value for 'constant' padding. Default: 0
 Examples::
  >>> t4d = torch.empty(3, 3, 4, 2)
  >>> p1d = (1, 1) # pad last dim by 1 on each side
  >>> out = F.pad(t4d, p1d, "constant", 0) # effectively zero padding
  >>> print(out.data.size())
  torch.Size([3, 3, 4, 4])
  >>> p2d = (1, 1, 2, 2) # pad last dim by (1, 1) and 2nd to last by (2, 2)
  >>> out = F.pad(t4d, p2d, "constant", 0)
  >>> print(out.data.size())
  torch.Size([3, 3, 8, 4])
  >>> t4d = torch.empty(3, 3, 4, 2)
  >>> p3d = (0, 1, 2, 1, 3, 3) # pad by (0, 1), (2, 1), and (3, 3)
  >>> out = F.pad(t4d, p3d, "constant", 0)
  >>> print(out.data.size())
  torch.Size([3, 9, 7, 3])
 """
 assert len(pad) % 2 == 0, 'Padding length must be divisible by 2'
 assert len(pad) // 2 <= input.dim(), 'Padding length too large'
 if mode == 'constant':
  ret = _VF.constant_pad_nd(input, pad, value)
 else:
  assert value == 0, 'Padding mode "{}"" doesn\'t take in value argument'.format(mode)
  if input.dim() == 3:
   assert len(pad) == 2, '3D tensors expect 2 values for padding'
   if mode == 'reflect':
    ret = torch._C._nn.reflection_pad1d(input, pad)
   elif mode == 'replicate':
    ret = torch._C._nn.replication_pad1d(input, pad)
   else:
    ret = input # TODO: remove this when jit raise supports control flow
    raise NotImplementedError
 
  elif input.dim() == 4:
   assert len(pad) == 4, '4D tensors expect 4 values for padding'
   if mode == 'reflect':
    ret = torch._C._nn.reflection_pad2d(input, pad)
   elif mode == 'replicate':
    ret = torch._C._nn.replication_pad2d(input, pad)
   else:
    ret = input # TODO: remove this when jit raise supports control flow
    raise NotImplementedError
 
  elif input.dim() == 5:
   assert len(pad) == 6, '5D tensors expect 6 values for padding'
   if mode == 'reflect':
    ret = input # TODO: remove this when jit raise supports control flow
    raise NotImplementedError
   elif mode == 'replicate':
    ret = torch._C._nn.replication_pad3d(input, pad)
   else:
    ret = input # TODO: remove this when jit raise supports control flow
    raise NotImplementedError
  else:
   ret = input # TODO: remove this when jit raise supports control flow
   raise NotImplementedError("Only 3D, 4D, 5D padding with non-constant padding are supported for now")
 return ret

以上这篇PyTorch之图像和Tensor填充的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python写的服务监控程序实例
Jan 31 Python
Django中对数据查询结果进行排序的方法
Jul 17 Python
总结python实现父类调用两种方法的不同
Jan 15 Python
利用Python脚本实现ping百度和google的方法
Jan 24 Python
在mac下查找python包存放路径site-packages的实现方法
Nov 06 Python
Selenium chrome配置代理Python版的方法
Nov 29 Python
简单了解python元组tuple相关原理
Dec 02 Python
使用tensorflow DataSet实现高效加载变长文本输入
Jan 20 Python
浅谈django不使用restframework自定义接口与使用的区别
Jul 15 Python
六种酷炫Python运行进度条效果的实现代码
Jul 17 Python
使用Python封装excel操作指南
Jan 29 Python
Python使用Opencv打开笔记本电脑摄像头报错解问题及解决
Jun 21 Python
Pytorch Tensor的索引与切片例子
Aug 18 #Python
在PyTorch中Tensor的查找和筛选例子
Aug 18 #Python
对Pytorch神经网络初始化kaiming分布详解
Aug 18 #Python
pytorch中的embedding词向量的使用方法
Aug 18 #Python
Pytorch加载部分预训练模型的参数实例
Aug 18 #Python
在pytorch中查看可训练参数的例子
Aug 18 #Python
浅析PyTorch中nn.Module的使用
Aug 18 #Python
You might like
抓取YAHOO股票报价的类
2009/05/15 PHP
php空间不支持socket但支持curl时recaptcha的用法
2011/11/07 PHP
javascript 贪吃蛇实现代码
2008/11/22 Javascript
JS实现QQ图片一闪一闪的效果小例子
2013/07/31 Javascript
setInterval()和setTimeout()的用法和区别示例介绍
2013/11/17 Javascript
键盘KeyCode值列表汇总
2013/11/26 Javascript
jquery提交form表单简单示例分享
2014/03/03 Javascript
24款热门实用的jQuery插件推荐
2014/12/24 Javascript
jquery.uploadify插件在chrome浏览器频繁崩溃解决方法
2015/03/01 Javascript
Jquery为DIV添加click事件的简单实例
2016/06/02 Javascript
详谈AngularJs 控制器、数据绑定、作用域
2017/07/09 Javascript
利用vue+elementUI实现部分引入组件的方法详解
2017/11/22 Javascript
vue如何解决循环引用组件报错的问题
2018/09/22 Javascript
vue动态绑定class的几种常用方式小结
2019/05/21 Javascript
Vue.js实现大转盘抽奖总结及实现思路
2019/10/09 Javascript
NodeJS多种创建WebSocket监听的方式(三种)
2020/06/04 NodeJs
Python备份Mysql脚本
2008/08/11 Python
Python正确重载运算符的方法示例详解
2017/08/27 Python
Python字符串和字典相关操作的实例详解
2017/09/23 Python
python 实现一个贴吧图片爬虫的示例
2017/10/12 Python
pip安装时ReadTimeoutError的解决方法
2018/06/12 Python
Python合并同一个文件夹下所有PDF文件的方法
2019/03/11 Python
Python爬取数据保存为Json格式的代码示例
2019/04/09 Python
执行Python程序时模块报错问题
2020/03/26 Python
Pandas把dataframe或series转换成list的方法
2020/06/14 Python
在Keras中利用np.random.shuffle()打乱数据集实例
2020/06/15 Python
keras分类模型中的输入数据与标签的维度实例
2020/07/03 Python
详解CSS3弹性伸缩盒
2020/09/21 HTML / CSS
你可能不熟练的十个前端HTML5经典面试题
2018/07/03 HTML / CSS
土木工程专业大学毕业生求职信
2013/10/13 职场文书
人力资源主管的岗位职责
2014/03/15 职场文书
国旗下的演讲稿
2014/05/08 职场文书
印刷技术专业自荐信
2014/09/18 职场文书
考试作弊检讨书
2015/01/27 职场文书
2015年教师节新闻稿
2015/07/17 职场文书
详解Java ES多节点任务的高效分发与收集实现
2021/06/30 Java/Android