如何在PyTorch中对图像进行全方位填充?


为了对图像进行全方位填充,我们可以使用**torchvision.transforms**模块提供的**Pad()**变换。此模块包含许多重要的变换,可用于对图像数据执行不同类型的操作。

**Pad()**变换接受PIL图像和张量图像或一批张量图像。张量图像是一个形状为**[C, H, W]**的torch张量,其中C是通道数,H是图像高度,W是图像宽度。

一批张量图像也是一个形状为**[B, C, H, W]**的torch张量。B是批次中的图像数量。如果图像既不是PIL图像也不是张量图像,则我们首先将其转换为张量图像,然后应用变换。

语法

torchvision.transforms.Pad(padding)(img)

参数

  • Padding –所需的填充大小。**padding**是一个类似于**(l, t, r, b)**的序列,其中l、r、t和b分别是左、上、右和下**padding**大小。填充可以是长度为2的序列。在这种情况下,左填充和右填充相同,上填充和下填充也相同。如果**padding**是整数,则所有侧面的填充都相同。

它返回一个用给定填充大小填充的图像。

步骤

我们可以使用以下步骤对图像进行全方位填充:

  • 导入所需的库。在以下所有示例中,所需的Python库是**torch、Pillow**和**torchvision**。确保您已安装它们。

import torch
import torchvision
import torchvision.transforms as transforms
from PIL import Image
  • 读取输入图像。输入图像是PIL图像或torch张量。

img = Image.open('dove.jpg')
  • 定义一个变换来对图像进行全方位填充。根据您的需要更改填充大小。

# padding same for all sides
transform = transforms.Pad(50)

# to pad 50 -> left/right, 100-> top/bottom
transform = transforms.Pad((50,100))

# to pad 0->left, 50->top, 100-> right, 150-> bottom
transform = transforms.Pad((0,50,100,150))
  • 将上述定义的变换应用于输入图像,以对图像进行全方位填充。

img = transform(img)
  • 可视化填充后的图像

img.show()

输入图像

以下图像是所有示例中使用的输入图像。

示例1

# Python program to pad an image on all sides
# import required libraries
import torch
import torchvision.transforms as transforms
from PIL import Image

# Read the image
img = Image.open('dove.jpg')

# compute width and height of image
width, height = img.size

# define a transform to pad an image on all sides
transform = transforms.Pad(50)

# apply the above transform on the image
img = transform(img)

# resize the image to its original dimension
img = img.resize((width, height))

# dispaly the image
img.show()

输出

它将产生以下输出:

请注意,输出图像中的填充在所有侧面上都是均匀的。

示例2

# Python program to pad an image on all sides
# import required libraries
import torch
import torchvision.transforms as transforms
from PIL import Image

# Read the image
img = Image.open('dove.jpg')
width, height = img.size

# define a transform to pad an image
transform = transforms.Pad([50,100])
# here 50 -> left/right, 100-> top/bottom

# apply the above transforms on the image
img = transform(img)

# resize the image to its original dimension
img = img.resize((width, height))

# dispaly the image
img.show()

输出

它将产生以下输出:

请注意,左右填充相同。同样,顶部和底部的填充也是均匀的。

示例3

# Python program to pad an image on all sides
# import required libraries
import torch
import torchvision.transforms as transforms
from PIL import Image

# Read the image
img = Image.open('dove.jpg')
width, height = img.size

# define a transform to pad an image
transform = transforms.Pad([0,50,100,150])
# here 0->left, 50->top, 100-> right, 150-> bottom
# apply the above transforms on the image
img = transform(img)

# resize the image to its original dimension
img = img.resize((width, height))

# display the image
img.show()

它将产生以下输出:

请注意,输出图像中的填充在各个侧面是不同的。

更新于:2022年1月6日

3K+ 次浏览

启动您的职业生涯

完成课程后获得认证

开始学习
广告
© . All rights reserved.