PyTorch – 如何将图像调整到指定大小?


Resize() 变换将输入图像调整到指定大小。它是 torchvision.transforms 模块提供的变换之一。Resize() 接受 PIL 和张量图像。张量图像是一个形状为 [C, H, W] 的 torch 张量,其中 C 是通道数,H 是图像高度,W 是图像宽度。

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

语法

torchvision.transforms.Resize(size)(img)

参数

  • Size – 将输入图像调整到的尺寸。size 是一个类似 (h, w) 的序列,其中 h 和 w 分别是输出图像的高度和宽度。如果 size 是一个整数,则调整大小后的图像将是正方形图像。

它返回一个指定大小的调整大小后的图像。

步骤

我们可以使用以下步骤将输入图像调整到指定大小。

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

import torch
import torchvision
import torchvision.transforms as T
from PIL import Image
import matplotlib.pyplot as plt
  • 读取输入图像。输入图像可以是 PIL 图像或 torch 张量或一批 torch 张量。

img = Image.open('lounge.jpg')
  • 定义一个变换,将图像调整到指定大小。例如,对于矩形裁剪,给定大小为 (300,350),对于正方形裁剪,给定大小为 250。根据您的需要更改裁剪大小。

# transform for rectangular resize
transform = T.Resize((300,350))

# transform for square resize
transform = T.Resize(250)
  • 将上面定义的变换应用于输入图像,以调整输入图像的大小。

resized_img = transform(img)
  • 显示调整大小后的图像。

plt.imshow(resized_img)

输入图像

此图像用作以下所有示例中的输入文件。

示例 1

输入图像调整为 (300, 350)。原始图像大小为 (700,700)

# import the required libraries
import torch
import torchvision.transforms as T
from PIL import Image
import matplotlib.pyplot as plt

# read the input image
img = Image.open('lounge.jpg')

# compute the size(width, height) of image
size = img.size
print("Size of the Original image:", size)

# define transformt o resize the image with given size
transform = T.Resize(size = (250,450))

# apply the transform on the input image
img = transform(img)
print("Size after resize:", img.size)
plt.imshow(img)
plt.show()

输出

它将返回调整大小后的图像,并在控制台上打印原始图像和输出图像的大小。

Size of the Original image: (640, 427)
Size after resize: (450, 250)

示例 2

让我们看另一个例子 -

import torch
import torchvision.transforms as T
from PIL import Image
import matplotlib.pyplot as plt

img = Image.open('lounge.jpg')
size = img.size
print("Size of Original image:", size)

transform = T.Resize(size = (400,200))
img = transform(img)

plt.imshow(img)
print("Size after resize:", img.size)
plt.show()

输出

它将产生以下输出 -

Size of the Original image: (640, 427)
Size after resize: (200, 400)

更新于: 2022年1月6日

33K+ 浏览量

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.