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.