PyTorch – torchvision.transforms – RandomVerticalFlip()


我們使用**RandomVerticalFlip()**變換以給定機率隨機垂直翻轉影像。它是**torchvision.transforms**模組提供的眾多變換之一。此模組包含許多重要的變換,可用於對影像資料執行不同型別的操作。

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

語法

torchvision.transforms.RandomVerticalFlip(p)(img)
  • 如果**p** = 1,則返回垂直翻轉的影像。

  • 如果**p** = 0,則返回原始影像。

  • 如果**p**在(0,1)範圍內,則返回垂直翻轉影像的機率為p。

它以給定機率p隨機角度返回垂直翻轉的影像。

步驟

可以按照以下步驟以給定機率隨機角度垂直翻轉影像:

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

import torch
import torchvision
import torchvision.transforms as T
from PIL import Image
  • 讀取輸入影像。輸入影像是PIL影像或張量影像。

img = Image.open('mountain.jpg')
  • 定義一個變換,以給定機率p隨機垂直翻轉影像。這裡p = 0.25意味著任何輸入影像被垂直翻轉的機率為25%。

transform = T.RandomVerticalFlip(p = 0.25)
  • 將上述定義的變換應用於輸入影像以垂直翻轉影像。

vflipped_img = transform(img)
  • 顯示輸出影像。

vflipped_img.show()

輸入影像

此影像用作以下所有示例中的輸入檔案。

示例1

在這個程式中,我們將p設定為1,因此輸出影像將是垂直翻轉的影像。

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

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

# define a transform with probability = 1
# to vertically flip an image
transform = T.RandomVerticalFlip(p=1)

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

# display the flipped image
img.show()

輸出

它將產生以下輸出:

請注意,由於我們將機率p設定為1,因此輸出影像是垂直翻轉的影像。

示例2

在這個示例中,我們將機率p設定為0.25,因此任何影像被垂直翻轉的機率為25%。

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

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

# define a transform with probability = 0.25
transform = T.RandomVerticalFlip(p=0.25)

# save four output images applying the above transform
imgs = [transform(img) for _ in range(4)]

# display these four output images
fig = plt.figure(figsize=(7,4))
rows, cols = 2,2
for j in range(0, len(imgs)):
   fig.add_subplot(rows, cols, j+1)
   plt.imshow(imgs[j])
   plt.xticks([])
   plt.yticks([])
plt.show()

輸出

它將產生以下輸出:

請注意,在四個輸出影像中,至少有一個影像被垂直翻轉。您可能會得到不同數量的垂直翻轉影像。

更新於:2022年1月6日

844 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.