如何在 PyTorch 中裁剪影像中心?


要裁剪影像中心,我們使用 **CenterCrop()**。它是 torchvision.transforms 模組提供的眾多轉換之一。此模組包含許多可用於對影像資料進行操作的重要轉換。

**CenterCrop()** 轉換接受 PIL 和張量影像。張量影像是一個形狀為 **[C, H, W]** 的 PyTorch 張量,其中 C 是通道數,H 是影像高度,W 是影像寬度。

此轉換還接受一批張量影像。一批張量影像是一個形狀為 **[B, C, H, W]** 的張量。**B** 是批次中的影像數量。如果影像既不是 PIL 影像也不是張量影像,則我們首先將其轉換為張量影像,然後應用 **CenterCrop()** 轉換。

語法

torchvision.transforms.CenterCrop(size)

引數

  • **size** – 期望的裁剪尺寸。**size** 是一個類似於 **(h, w)** 的序列,其中 **h** 和 **w** 分別是裁剪影像的高度和寬度。如果 **size** 是一個 **int**,則裁剪後的影像將為正方形影像。

它返回給定大小的裁剪影像。

步驟

我們可以使用以下步驟在中心裁剪給定大小的影像。

  • 匯入所需的庫。在以下所有示例中,所需的 Python 庫為 **torch、Pillow** 和 **torchvision**。確保您已安裝它們。

import torch
import torchvision
import torchvision.transforms as transforms
from PIL import Image
  • 讀取輸入影像。輸入影像為 PIL 影像或形狀為 [..., H, W] 的 torch 張量。

img = Image.open('lena.jpg')
  • 定義一個轉換以在中心裁剪影像。對於矩形裁剪,裁剪大小為 (200,250),對於正方形裁剪,裁剪大小為 250。根據您的需要更改裁剪大小。

# transform for rectangular crop
transform = transforms.CenterCrop((200,250))

# transform for square crop
transform = transforms.CenterCrop(250)
  • 將上面定義的轉換應用於輸入影像以在中心裁剪影像。

img = transform(img)
  • 視覺化裁剪後的影像

img.show()

輸入影像

以下影像用作兩個示例中的輸入影像。

示例 1

以下 Python 程式演示瞭如何在中心裁剪影像。裁剪後的影像為正方形影像。在此程式中,我們將輸入影像讀取為 PIL 影像。

# Python program to crop an image at center
# import required libraries
import torch
import torchvision.transforms as transforms
from PIL import Image

# Read the image
img = Image.open('waves.png')

# define a transform to crop the image at center
transform = transforms.CenterCrop(250)

# crop the image using above defined transform
img = transform(img)

# visualize the image
img.show()

輸出

它將產生以下輸出 -

示例 2

此 Python 程式在中心裁剪影像,並給出指定的高度和寬度。在此程式中,我們將輸入影像讀取為 PIL 影像。

# Python program to crop an image at center
# import torch library
import torch
import torchvision.transforms as transforms
from PIL import Image

# Read the image
img = Image.open('waves.png')

# define a transform to crop the image at center
transform = transforms.CenterCrop((150,500))

# crop the image using above defined transform
img = transform(img)

# visualize the image
img.show()

輸出

生成的輸出影像將為 150px 高和 500px 寬。

示例 3

在此程式中,我們將輸入影像讀取為 OpenCV 影像。我們定義一個轉換,它是三個轉換的組合。我們首先將影像轉換為張量影像,然後應用 **CenterCrop()**,最後將裁剪後的張量影像轉換為 PIL 影像。

# import the required libraries
import torch
import torchvision.transforms as transforms
import cv2

# read the inputimage
img = cv2.imread('waves.png')

# convert image from BGR to RGB
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# Define a transform. It is a composition
# of three transforms
transform = transforms.Compose([
   transforms.ToTensor(),        # Converts to PyTorch Tensor
   transforms.CenterCrop(250),   # crops at center
   transforms.ToPILImage()       # converts the tensor to PIL image
])
# apply the above transform to crop the image
img = transform(img)

# display the cropped image
img.show()

輸出

它將產生以下輸出 -

更新於: 2022年1月6日

4K+ 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告