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 Deque 模块使用详解
Jul 04 Python
python利用matplotlib库绘制饼图的方法示例
Dec 18 Python
Python实现将json文件中向量写入Excel的方法
Mar 26 Python
python 循环读取txt文档 并转换成csv的方法
Oct 26 Python
Django框架设置cookies与获取cookies操作详解
May 27 Python
OpenCV 轮廓检测的实现方法
Jul 03 Python
Django 响应数据response的返回源码详解
Aug 06 Python
postman传递当前时间戳实例详解
Sep 14 Python
下载官网python并安装的步骤详解
Oct 12 Python
python实现数字炸弹游戏程序
Jul 17 Python
Python基础数据类型tuple元组的概念与用法
Aug 02 Python
Python 图片添加美颜效果
Apr 28 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
PHP中CURL的CURLOPT_POSTFIELDS参数使用细节
2014/03/17 PHP
完美解决php 导出excle的.csv格式的数据时乱码问题
2017/02/18 PHP
详解PHP函数 strip_tags 处理字符串缺陷bug
2017/06/11 PHP
js tab 选项卡
2009/04/26 Javascript
JS实现在Repeater控件中创建可隐藏区域的代码
2010/09/16 Javascript
javascript自适应宽度的瀑布流实现思路
2013/02/20 Javascript
JS实现点击图片在当前页面放大并可关闭的漂亮效果
2013/10/18 Javascript
jQuery中复合属性选择器用法实例
2014/12/31 Javascript
浅谈Sticky组件的改进实现
2016/03/22 Javascript
json格式的javascript对象用法分析
2016/07/04 Javascript
详解MVC如何使用开源分页插件(shenniu.pager.js)
2016/12/16 Javascript
Bootstrap面板使用方法
2017/01/16 Javascript
canvas滤镜效果实现代码
2017/02/06 Javascript
浅谈Webpack打包优化技巧
2018/06/12 Javascript
在vue项目中引用Iview的方法
2018/09/14 Javascript
vue 的点击事件获取当前点击的元素方法
2018/09/15 Javascript
微信小程序仿知乎实现评论留言功能
2018/11/28 Javascript
jquery简单实现纵向的无缝滚动代码实例
2019/04/01 jQuery
vue.js中使用echarts实现数据动态刷新功能
2019/04/16 Javascript
对Tensorflow中的变量初始化函数详解
2018/07/27 Python
Python实现的连接mssql数据库操作示例
2018/08/17 Python
在python中使用xlrd获取合并单元格的方法
2018/12/26 Python
python 基于TCP协议的套接字编程详解
2019/06/29 Python
Python生态圈图像格式转换问题(推荐)
2019/12/02 Python
Tensorflow设置显存自适应,显存比例的操作
2020/02/03 Python
Python中使用aiohttp模拟服务器出现错误问题及解决方法
2020/10/31 Python
阿迪达斯意大利在线商店:adidas意大利
2016/09/19 全球购物
Feelunique德国官方网站:欧洲最大的在线美容零售商
2019/07/20 全球购物
技术总监的工作职责
2013/11/13 职场文书
区域销售经理岗位职责
2013/12/10 职场文书
承诺书格式范文
2014/06/03 职场文书
交通安全宣传标语(100条)
2019/08/22 职场文书
MySQL Shell的介绍以及安装
2021/04/24 MySQL
安装pytorch时报sslerror错误的解决方案
2021/05/17 Python
Python初学者必备的文件读写指南
2021/06/23 Python
详解MySQL的内连接和外连接
2023/05/08 MySQL