如何在 PyTorch 中调整图像的色调?
图像的色调是指三种原色(红、蓝、黄)和三种二次色(橙、绿、紫)。为了调整图像的色调,我们应用adjust_hue(). 它是torchvision.transforms模块提供的功能转换之一。
adjust_hue()转换接受 PIL 和张量图像。张量图像是形状为[C, H, W] 的 PyTorch 张量,其中C是通道数,H是图像高度,W是图像宽度。此变换还接受一批张量图像。
通过将图像转换为HSV(Hue、Saturation、Value)并循环移动色调通道 (H) 中的强度来调整图像色调。然后将图像转换回原始图像模式。
如果图像既不是 PIL 图像也不是张量图像,那么我们首先将其转换为张量图像,然后应用adjust_hue(). 色调应在[-0.5, 0.5] 范围内。-0.5和0.5将给出具有互补色的图像,而 0 将给出原始图像。
语法
torchvision.transforms.functional.adjust_hue(img, hue_factor)
参数
img - 要调整色调的图像。它是 PIL 图像或火炬张量。它可能是单个图像或一批图像
hue_factor - [−0.5, 0.5] 范围内的浮点数。0 给出纯灰色图像,而 -0.5 和 0.5 将给出具有互补色的图像。
输出结果
它返回色调调整后的图像。
脚步
要调整图像的色调,可以按照以下步骤进行
导入所需的库。在以下所有示例中,所需的 Python 库是torch、Pillow和torchvision。确保您已经安装了它们。
import torchimport 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
fromtorchvision.ioimport read_image
import torchvision.transforms.functional as F
importtorchvision.transformsas 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
fromtorchvision.ioimport read_image
import torchvision.transforms.functional as F
importtorchvision.transformsas 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()
以上是 如何在 PyTorch 中调整图像的色调? 的全部内容, 来源链接: utcz.com/z/363473.html