如何在 PyTorch 中调整图像亮度?


图像的亮度是在图像捕获后对其强度的度量。要调整图像的亮度,我们应用 **adjust_brightness()**。它是 **torchvision.transforms** 模块提供的功能转换之一。此模块包含许多可用于操作图像数据的重要的功能转换。

**adjust_brightness()** 转换接受 PIL 和张量图像。张量图像是一个形状为 **[C, H, W]** 的 PyTorch 张量,其中 C 是通道数,**H** 是图像高度,**W** 是图像宽度。此转换还接受一批张量图像。一批张量图像是一个形状为 **[B, C, H, W]** 的张量,其中 B 是批次中图像的数量。如果图像既不是 PIL 图像也不是张量图像,那么我们首先将其转换为张量图像,然后应用 **adjust_brightness()**。

语法

torchvision.transforms.functional.adjust_brightness(img, brightness_factor)

参数

  • **img** - 要调整亮度的图像。它是 PIL 图像或 Torch 张量。它可以是单个图像或一批图像。

  • **brightness_factor** - 一个非负浮点数。0 给出一个黑色图像,1 给出原始图像。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

它返回亮度调整后的图像。

步骤

要调整图像的亮度,可以按照以下步骤操作

  • 导入所需的库。在以下所有示例中,所需的 Python 库为 **torch、Pillow 和 torchvision**。请确保您已安装它们。

import torch import torchvision import torchvision.transforms.functional as F from PIL import Image
  • 读取输入图像。输入图像为 PIL 图像或 Torch 张量。

img = Image.open('Nature1.jpg')
  • 使用所需的亮度因子调整图像的亮度。

img = F.adjust_brightness(img, 0.3)
  • 可视化亮度调整后的图像。

img.show()

输入图像

我们将在以下示例中使用此图像作为输入文件。

示例 1

在以下 Python 程序中,我们使用 **brightness_factor=0.3** 调整图像的亮度。

# Import the required libraries import torch from PIL import Image import torchvision.transforms.functional as F # read the input image img = Image.open('Nature1.jpg') # adjust the brightness of image img = F.adjust_brightness(img, 0.3) # display the brightness adjusted image img.show()

输出

示例 2

在以下 Python 程序中,我们使用 **brightness_factor=1.6** 调整图像的亮度。

import torch from PIL import Image import torchvision.transforms.functional as F img = Image.open('Nature1.jpg') img.show() img = F.adjust_brightness(img, 1.6) img.show()

输出

更新于: 2022年1月20日

2K+ 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告