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 面向对象 成员的访问约束
Dec 23 Python
简单理解Python中基于生成器的状态机
Apr 13 Python
浅谈numpy数组的几种排序方式
Dec 15 Python
python初学之用户登录的实现过程(实例讲解)
Dec 23 Python
python绘制热力图heatmap
Mar 23 Python
利用Python代码实现一键抠背景功能
Dec 29 Python
python实现tail -f 功能
Jan 17 Python
Python基于xlrd模块处理合并单元格
Jul 28 Python
浅谈anaconda python 版本对应关系
Oct 07 Python
解决pycharm导入numpy包的和使用时报错:RuntimeError: The current Numpy installation (‘D:\\python3.6\\lib\\site-packa的问题
Dec 08 Python
pytorch 如何把图像数据集进行划分成train,test和val
May 31 Python
Python一些基本的图像操作和处理总结
Jun 23 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
地球防卫队:陪着奥特曼打小怪兽的人类力量 那些经典队服
2020/03/08 日漫
判断是否为指定长度内字符串的php函数
2010/02/16 PHP
PHP array_multisort() 函数的深入解析
2013/06/20 PHP
php中heredoc与nowdoc介绍
2014/12/25 PHP
php简单smarty入门程序实例
2015/06/11 PHP
php 二维数组时间排序实现代码
2016/11/19 PHP
php判断IP地址是否在多个IP段内
2020/08/18 PHP
Prototype使用指南之selector.js
2007/01/10 Javascript
window.showModalDialog使用手册
2007/01/11 Javascript
javascript定义变量时有var和没有var的区别探讨
2014/07/21 Javascript
微信中一些常用的js方法汇总
2015/03/12 Javascript
AngularJS 让人爱不释手的八种功能
2016/03/23 Javascript
jQuery实现的自适应焦点图效果完整实例
2016/08/24 Javascript
js实现九宫格的随机颜色跳转
2017/02/19 Javascript
vue-resource 拦截器(interceptor)的使用详解
2017/07/04 Javascript
详解angularJS自定义指令间的相互交互
2017/07/05 Javascript
js 两数组去除重复数值的实例
2017/12/06 Javascript
nestjs中异常过滤器Exceptionfilter的具体使用
2021/02/07 Javascript
[02:10]2018DOTA2亚洲邀请赛赛前采访-Liquid
2018/04/03 DOTA
自己编程中遇到的Python错误和解决方法汇总整理
2015/06/03 Python
Python中偏函数用法示例
2018/06/07 Python
python 顺时针打印矩阵的超简洁代码
2018/11/14 Python
Python实现图片批量加入水印代码实例
2019/11/30 Python
Python3 读取Word文件方式
2020/02/13 Python
打包PyQt5应用时的注意事项
2020/02/14 Python
html5 初试 indexedDB(推荐)
2016/07/21 HTML / CSS
Agoda西班牙:全球特价酒店预订
2017/06/03 全球购物
阿根廷旅游网站:almundo阿根廷
2018/02/12 全球购物
俄罗斯运动鞋商店:Sneakerhead
2018/05/10 全球购物
公立医院改革实施方案
2014/03/14 职场文书
革命英雄事迹演讲稿
2014/09/13 职场文书
黄山导游词
2015/01/31 职场文书
2015教师个人德育工作总结
2015/07/22 职场文书
2019年让高校“心动”的自荐信
2019/03/25 职场文书
Python实现照片卡通化
2021/12/06 Python
排查MySQL生产环境索引没有效果
2022/04/11 MySQL