如何在 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 給出原始影像。
輸出
它返回亮度調整後的影像。
步驟
要調整影像的亮度,可以按照以下步驟操作
匯入所需的庫。在以下所有示例中,所需的 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()輸出

資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP