PyTorch – 如何以給定機率隨機反轉影像顏色?


**RandomInvert()** 變換以給定機率隨機反轉影像的顏色。**torchvision.transforms** 模組提供了許多重要的變換,可用於對影像資料執行不同型別的操作。

**RandomInvert()** 接受 PIL 影像和張量影像或張量影像批次。張量影像是一個形狀為 [**3, H, W**] 的 PyTorch 張量,其中 H 是影像高度,W 是影像寬度。張量影像批次也是一個 torch 張量,形狀為 [**B, 3, H, W**],其中 B 是批次中的影像數量。

語法

torchvision.transforms.RandomInvert(p)(img)

它以給定機率 p 返回隨機顏色反轉的影像。

  • 如果 **p** = 1,則返回顏色反轉的影像。

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

  • 如果 **p** 在 (0,1) 範圍內,則返回隨機顏色反轉影像的機率為 p。

  • img 是輸入的 PIL 影像或張量影像。

步驟

我們可以使用以下步驟以給定機率隨機反轉輸入影像的顏色:

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

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

img = Image.open('stairs.jpg')
  • 定義一個變換,以給定機率 p 隨機反轉原始輸入影像的顏色。

transform = T.RandomInvert(p = 0.25)
  • 將上述定義的變換應用於輸入影像以反轉輸入影像的顏色。

inverted_img = transform(img)
  • 顯示隨機顏色反轉的影像。

inverted_img.show()

輸入影像

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

示例 1

在此程式中,我們將機率設定為 1,以便輸出肯定是一張顏色反轉的影像。

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

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

# define a transform to randomly invert
# the color with probability=1
transform = T.RandomInvert(p=1)

# apply the above transform on input image
img = transform(img)
img.show()

輸出

它將產生以下輸出:

示例 2

讓我們來看另一個例子:

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

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

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

# apply the transform four times
invert_imgs = [transform(img) for _ in range(4)]
fig = plt.figure(figsize=(7,4))
rows, cols = 2,2
for j in range(0, len(invert_imgs)):
   fig.add_subplot(rows, cols, j+1)
   plt.imshow(invert_imgs[j])
   plt.xticks([])
   plt.yticks([])
plt.show()

輸出

它將產生以下輸出:

在上面的輸出中,注意,在四張影像中,至少有一張影像的顏色被反轉,因為我們將機率設定為 0.25。

更新於:2022年1月6日

614 次瀏覽

啟動你的職業生涯

完成課程獲得認證

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