如何在 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.