如何在 PyTorch 中調整影像的色調?


影像的色調指的是三種原色(紅、藍、黃)和三種次色(橙、綠、紫)。要調整影像的色調,我們應用 **adjust_hue()**。它是 **torchvision.transforms** 模組提供的函式轉換之一。

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

影像色調透過將影像轉換為 **HSV(色相、飽和度、亮度)** 並迴圈移動色相通道 (H) 中的強度來調整。然後將影像轉換回原始影像模式。

如果影像既不是 PIL 影像也不是張量影像,那麼我們首先將其轉換為張量影像,然後應用 **adjust_hue()**。色調應在 **[-0.5, 0.5]** 範圍內。**-0.5** 和 **0.5** 將給出具有互補色的影像,而 0 給出原始影像。

語法

torchvision.transforms.functional.adjust_hue(img, hue_factor)

引數

  • **img** - 要調整色調的影像。它是 PIL 影像或 torch 張量。它可以是單個影像或一批影像

  • **hue_factor** - 範圍在 [−0.5, 0.5] 內的浮點數。0 給出一個純灰色的影像,而 -0.5 和 0.5 將給出具有互補色的影像。

輸出

它返回色調調整後的影像。

步驟

要調整影像的色調,可以按照以下步驟操作

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

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

img = Image.open('meekats.jpg')
  • 使用所需的色調因子調整影像的色調。

img = F.adjust_hue(img, -0.1)
  • 視覺化色調調整後的影像。

img.show()

輸入影像

在以下示例中,我們將使用此影像作為輸入檔案。

示例 1

在此程式中,我們使用 **hue_factor=0.3** 調整輸入影像的色調。

# Import the required libraries
import torch
import torchvision
from PIL import Image
import torchvision.transforms.functional as F

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

# adjust the t=hue
img = F.adjust_hue(img, 0.3)
display the hue adjusted image
img.show()

輸出

示例 2

在此程式中,我們使用 **hue_factor=-0.1** 調整輸入影像的色調。

# Import the required libraries
import torch
import torchvision
from torchvision.io import read_image
import torchvision.transforms.functional as F
import torchvision.transforms as T

# read input image as an image tensor
img = read_image('meekats.jpg')

# hue_factor [-0.5, 0.5]
# adjust hue using hue_factor=-0.1
img1 = F.adjust_hue(img, -0.1)

# convert the image tensor to PIL image
img1 = T.ToPILImage()(img1)
# display the PIL image with adjusted hue
img1.show()

輸出

示例 3

# Import the required libraries
import torch
import torchvision
from torchvision.io import read_image
import torchvision.transforms.functional as F
import torchvision.transforms as T

# read input image as an image tensor
img = read_image('meerkats.jpg')

# hue_factor [-0.5, 0.5]
# Take 3 output image with adjusted different hue_factors
img1 = F.adjust_hue(img, -0.1)
img2 = F.adjust_hue(img, 0) # returns original image
img3 = F.adjust_hue(img, 0.1)
img4 = F.adjust_hue(img, 0.5)

# create a grid of above the output images
grid_img = torchvision.utils.make_grid([img1, img2, img3,
img4], nrow=2)

# convert the grid of image tensors to PIL Image
grid_img = T.ToPILImage()(grid_img)
grid_img.show()

輸出

更新於: 2022年1月20日

2K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.