pytorch实现图像上采样的几种方式

  • 1. torch.nn.Upsample()
  • 2. torch.nn.ConvTranspose2d()
  • 3. torch.nn.functional.interpolate()
  • 其他的API可以参考:

1. torch.nn.Upsample()

torch.nn.Upsample(size=None, scale_factor=None, mode='nearest', align_corners=None)

参数:

  • size (int or Tuple[int] or Tuple[int, int] or Tuple[int, int, int], optional) – 根据不同的输入类型制定的输出大小
  • scale_factor (float or Tuple[float] or Tuple[float, float] or Tuple[float, float, float], optional) – 指定输出为输入的多少倍数。如果输入为tuple,其也要制定为tuple类型
  • mode (str, optional) – 可使用的上采样算法,有nearest, linear, bilinear, bicubic and trilinear. 默认使用nearest
  • align_corners (bool, optional) – 如果为True,输入的角像素将与输出张量对齐,因此将保存下来这些像素的值。仅当使用的算法为linear, bilinear or trilinear时可以使用。默认设置为False

Examples:

>>> input = torch.arange(1, 5, dtype=torch.float32).view(1, 1, 2, 2)
>>> input
tensor([[[[ 1.,  2.],[ 3.,  4.]]]])>>> m = nn.Upsample(scale_factor=2, mode='nearest')
>>> m(input)
tensor([[[[ 1.,  1.,  2.,  2.],[ 1.,  1.,  2.,  2.],[ 3.,  3.,  4.,  4.],[ 3.,  3.,  4.,  4.]]]])>>> m = nn.Upsample(scale_factor=2, mode='bilinear')  # align_corners=False
>>> m(input)
tensor([[[[ 1.0000,  1.2500,  1.7500,  2.0000],[ 1.5000,  1.7500,  2.2500,  2.5000],[ 2.5000,  2.7500,  3.2500,  3.5000],[ 3.0000,  3.2500,  3.7500,  4.0000]]]])>>> m = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
>>> m(input)
tensor([[[[ 1.0000,  1.3333,  1.6667,  2.0000],[ 1.6667,  2.0000,  2.3333,  2.6667],[ 2.3333,  2.6667,  3.0000,  3.3333],[ 3.0000,  3.3333,  3.6667,  4.0000]]]])>>> # Try scaling the same data in a larger tensor
>>>
>>> input_3x3 = torch.zeros(3, 3).view(1, 1, 3, 3)
>>> input_3x3[:, :, :2, :2].copy_(input)
tensor([[[[ 1.,  2.],[ 3.,  4.]]]])
>>> input_3x3
tensor([[[[ 1.,  2.,  0.],[ 3.,  4.,  0.],[ 0.,  0.,  0.]]]])>>> m = nn.Upsample(scale_factor=2, mode='bilinear')  # align_corners=False
>>> # Notice that values in top left corner are the same with the small input (except at boundary)
>>> m(input_3x3)
tensor([[[[ 1.0000,  1.2500,  1.7500,  1.5000,  0.5000,  0.0000],[ 1.5000,  1.7500,  2.2500,  1.8750,  0.6250,  0.0000],[ 2.5000,  2.7500,  3.2500,  2.6250,  0.8750,  0.0000],[ 2.2500,  2.4375,  2.8125,  2.2500,  0.7500,  0.0000],[ 0.7500,  0.8125,  0.9375,  0.7500,  0.2500,  0.0000],[ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000]]]])>>> m = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
>>> # Notice that values in top left corner are now changed
>>> m(input_3x3)
tensor([[[[ 1.0000,  1.4000,  1.8000,  1.6000,  0.8000,  0.0000],[ 1.8000,  2.2000,  2.6000,  2.2400,  1.1200,  0.0000],[ 2.6000,  3.0000,  3.4000,  2.8800,  1.4400,  0.0000],[ 2.4000,  2.7200,  3.0400,  2.5600,  1.2800,  0.0000],[ 1.2000,  1.3600,  1.5200,  1.2800,  0.6400,  0.0000],[ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000]]]])

2. torch.nn.ConvTranspose2d()

torch.nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride=1, padding=0, output_padding=0, bias=True)

Args:

  • in_channels (int): Number of channels in the input image
  • out_channels (int): Number of channels produced by the convolution
  • kernel_size (int or tuple): Size of the convolving kernel
  • stride (int or tuple, optional): Stride of the convolution. Default: 1
  • padding (int or tuple, optional): dilation * (kernel_size - 1) - padding zero-padding
    will be added to both sides of each dimension in the input. Default: 0
  • output_padding (int or tuple, optional): Additional size added to one side
    of each dimension in the output shape. Default: 0
  • groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1
  • bias (bool, optional): If True, adds a learnable bias to the output. Default: True
  • dilation (int or tuple, optional): Spacing between kernel elements. Default: 1

二维卷积的计算公式
- 2维卷积的输出尺寸的计算公式为:
- dilation[0]dilation[0]dilation[0]在nn.Conv2dnn.Conv2dnn.Conv2d中默认为1

转置卷积的计算公式
- Input: (N,Cin,Hin,Win)(N, C_{in}, H_{in}, W_{in})(N,Cin​,Hin​,Win​)
- Output: (N,Cout,Hout,Wout)(N, C_{out}, H_{out}, W_{out})(N,Cout​,Hout​,Wout​)
- 转置卷积在直观上相当于求原始的HinH_{in}Hin​与WinW_{in}Win​
Hout=(Hin−1)×stride[0]−2×padding[0]+dilation[0]×(kernelsize[0]−1)+outputpadding[0]+1H_{out}=(H_{in}−1)×stride[0]−2×padding[0]+dilation[0]×(kernelsize[0]−1)+outputpadding[0]+1 Hout​=(Hin​−1)×stride[0]−2×padding[0]+dilation[0]×(kernelsize[0]−1)+outputpadding[0]+1
Wout=(Win−1)×stride[1]−2×padding[1]+dilation[1]×(kernelsize[1]−1)+outputpadding[1]+1W_{out}=(W_{in}−1)×stride[1]−2×padding[1]+dilation[1]×(kernelsize[1]−1)+outputpadding[1]+1 Wout​=(Win​−1)×stride[1]−2×padding[1]+dilation[1]×(kernelsize[1]−1)+outputpadding[1]+1
Examples:


>>> # With square kernels and equal stride
>>> m = nn.ConvTranspose2d(16, 33, 3, stride=2)
>>> # non-square kernels and unequal stride and with padding
>>> m = nn.ConvTranspose2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2))
>>> input = torch.randn(20, 16, 50, 100)
>>> output = m(input)
>>> # exact output size can be also specified as an argument
>>> input = torch.randn(1, 16, 12, 12)
>>> downsample = nn.Conv2d(16, 16, 3, stride=2, padding=1)
>>> upsample = nn.ConvTranspose2d(16, 16, 3, stride=2, padding=1)
>>> h = downsample(input)
>>> h.size()
torch.Size([1, 16, 6, 6])  # (12-3+2*1)//2+1 = 6
>>> output = upsample(h, output_size=input.size())
>>> output.size()
torch.Size([1, 16, 12, 12]) # 反卷积在公式上相当于卷积的逆运算,实际上不是真正的逆

3. torch.nn.functional.interpolate()

torch.nn.functional.interpolate(input, size=None, scale_factor=None, mode='nearest', align_corners=None, recompute_scale_factor=None)

该函数可以实现图像的上下采样,将输入图像上/下采样到指定的size或者给定的scale_factor。上下采样使用的算法由取决于参数mode。

Parameters

  • input (Tensor) – the input tensor
  • size (int or Tuple[int] or Tuple[int, int] or Tuple[int, int, int]) – output spatial size.
  • scale_factor (float or Tuple[float]) – multiplier for spatial size. If scale_factor is a tuple, its length has to match input.dim().
  • mode (str) – algorithm used for upsampling: nearest | linear | bilinear | bicubic |trilinear | area. Default: nearest
  • align_corners (bool, optional) – Geometrically, we consider the pixels of the input and output as squares rather than points. If set to True, the input and output tensors are aligned by the center points of their corner pixels, preserving the values at the corner pixels. If set to False, the input and output tensors are aligned by the corner points of their corner pixels, and the interpolation uses edge value padding for out-of-boundary values, making this operation independent of input size when scale_factor is kept the same. This only has an effect when mode is linear, bilinear, bicubic or trilinear. Default: False
  • recompute_scale_factor (bool, optional) – recompute the scale_factor for use in the interpolation calculation. If recompute_scale_factor is True, then scale_factor must be passed in and scale_factor is used to compute the output size. The computed output size will be used to infer new scales for the interpolation. Note that when scale_factor is floating-point, it may differ from the recomputed scale_factor due to rounding and precision issues. If recomputed_scale_factor is False, then size or scale_factor will be used directly for interpolation.

Note: 使用mode=‘bicubic’,可能能会产生负值或大于255的图像值,需要使用截断函数result.clamp(min=0, max=255)进行二次调整。

Examples:

import torch
import torch.nn.functional as Finput = torch.randn(2, 3, 256, 256)
down = F.interpolate(input, scale_factor=0.5)
print(down.shape)  # torch.Size([2, 3, 128, 128])
up = F.interpolate(input, scale_factor=2)
print(up.shape)  # torch.Size([2, 3, 512, 512])

其他的API可以参考:

pytorch实现图像上采样的几种方式相关推荐

  1. 2020.11.03 使用OpenCV进行图像上采样、降采样以及高斯不同操作【OpenCV C++】

    图像上采样,降采样以及高斯不同操作 源代码: // testOpencv12.cpp : 此文件包含 "main" 函数.程序执行将在此处开始并结束. // #include &l ...

  2. 【opencv学习笔记】第五篇:访问图像中像素的三种方式、ROI区域图像叠加和图像混合

    1. 访问图像中像素的三种方式 任何图像处理算法,都是从操作每个像素开始的.在OpenCV中,提供了三种访问每个像素的方法. 方法1:指针访问:C操作符[] 方法2:迭代器iterator 方法3:动 ...

  3. 在电脑屏幕上截图的5种方式

    在电脑屏幕上截图的5种方式 第一种:Ctrl + PrScrn 使用这个组合键截屏,获得的是整个屏幕的图片,截取后ctrl+v键可直接在文档中保存.Alt + PrScrn 这个组合键截屏,获得的结果 ...

  4. 文件上传的三种方式-Java

    前言:负责,因为该项目他(jetty嵌入式开始SpringMvc)实现文件上传的必要性,并拥有java文件上传这一块还没有被曝光.并 Http 更多晦涩协议.因此,这种渐进的方式来学习和实践上载文件的 ...

  5. vue获取上传图片的名字和路径_使用Vue实现图片上传的三种方式

    项目中需要上传图片可谓是经常遇到的需求,本文将介绍 3 种不同的图片上传方式,在这总结分享一下,有什么建议或者意见,请大家踊跃提出来. 没有业务场景的功能都是耍流氓,那么我们先来模拟一个需要实现的业务 ...

  6. 原生态的ajax如何上传文件,原生ajax和iframe框架实现图片文件上传的两种方式

    大家应该可以举出几种常用的异步文件上传功能的实现方式,使用频率较多的有原生ajax和iframe框架,实现图片文件上传,下面就为大家分享图片文件上传的两种方式:原生ajax和iframe框架,供大家参 ...

  7. 消费者在数学上无望的11种方式

    消费者在数学上无望的11种方式 你走进一家星巴克,看到店里对同一杯咖啡提供两种套餐:第一种是加量33%不加价:第二种是原价降价33%.哪种更好? "它们差不多一样!",如果你和参加 ...

  8. python图像降采样_OpenCV:十一、图像上采样和降采样

    前言 目标 本章中,将学习: 图像金字塔概念 采样API 代码演示 图像金字塔概念 图像金字塔是图像中对尺度表达的一种,最主要用于图像的分割,是一种以多分辨率来解释图像的有效但概念简单的结构. 图像金 ...

  9. OpenCV 图像上采样和降采样

    文章目录 相关概念 图像金字塔 高斯金字塔 高斯金字塔的生成过程 高斯不同(Difference of Gaussian-DOG): 拉普拉斯金字塔 采样相关API 上采样(cv::pyrUp) – ...

最新文章

  1. 面向未来的数据中心需要防止立法蠕变
  2. 未能在全局命名空间中找到类型或命名空间名称“Wuqi”
  3. 理解JavaScript面向对象的思路
  4. 二级c语言光盘,二级c语言(光盘).doc
  5. [css] 写出在不固定宽高的元素在固定高度的情况下水平垂直居中的方法
  6. Python | Lambda函数与示例
  7. python列表的小东西_小谈python里 列表 的几种常用用法
  8. 弹出框之对话框和提示框,可共用代码
  9. 升级到 Android Studio 3.0 + Gradle 4.1 遇到的一些坑及解决方案
  10. 系统学习数字图像处理之图像压缩
  11. Javascript特效:响应式改变页面背景颜色
  12. oa系统服务器热备份,如何做好OA系统的日常数据备份
  13. GB35114视频流处理
  14. 奖补多的2022年合肥高新区高成长企业申报时间入选范围及申报条件材料
  15. “千年老二”搜狐:从没有真正意义上成为第一
  16. [刀塔自走棋] 一些数据
  17. Linux添加开机自启、开机自动运行命令、开机启动项的两种方法
  18. KNN算法优缺点总结,以及机器学习流程的总结
  19. python用什么软件编程-初学 Python 需要安装哪些软件?
  20. 招聘网站代码模板 mysql_招聘网站爬虫模板

热门文章

  1. Python盒子:模块、包和程序
  2. 汇编学习笔记之阶码与移码
  3. Python 基础 — 基础语法
  4. 强力推荐一个完善的物流(WMS)管理项目(附代码)
  5. MySQL 中判断奇数的 6 种方法
  6. 常用金属材料 铝及铝合金的特性识别符号
  7. 还在复制粘贴做Word?用PDF转Word吧!
  8. 率土之滨显示没选择服务器,率土之滨自动登录,总是显示未登录服务器
  9. linux vi行首加符号,vi/vim 中如何在每行行首或行尾插入指定字符
  10. 2021年国产软硬件行业发展研究报告