如何在PyTorch中調整影像對比度?
影像的對比度是指影像各個特徵之間顏色差異的程度。要調整影像的對比度,我們使用 **adjust_contrast()** 函式。它是 **torchvision.transforms** 模組提供的功能轉換之一。此模組包含許多重要的功能轉換,可用於對影像資料進行不同型別的操作。
**adjust_contrast()** 轉換接受 PIL 影像和張量影像。張量影像是一個形狀為 **[C, H, W]** 的 PyTorch 張量,其中 **C** 是通道數,**H** 是影像高度,**W** 是影像寬度。此轉換還接受一批張量影像,它是一個形狀為 **[B, C, H, W]** 的張量,其中 **B** 是一批影像中的影像數量。如果影像既不是 PIL 影像也不是張量影像,則我們首先將其轉換為張量影像,然後應用 **adjust_contrast()**。所有功能轉換都可以從 **torchvision.transforms.functional** 訪問。
語法
torchvision.transforms.functional.adjust_contrast(img, contrast_factor)
引數
**img** - 要調整對比度的影像。它是 PIL 影像或 torch 張量。可以是單個影像或一批影像。
**contrast_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('Nature_canada.jpg')
使用所需的對比度因子調整影像的對比度。
img = F.adjust_contrast(img, 0.3)
視覺化對比度已調整的影像。
img.show()
輸入影像
我們將在以下示例中使用此影像作為輸入檔案。

示例 1
在下面的 Python 程式中,我們使用 **contrast_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('Nature_canada.jpg')
# adjust the contrast of the image
img = F.adjust_contrast(img, 0.3)
# display the contrast adjusted image
img.show()輸出

示例 2
在下面的 Python 程式中,我們使用 **contrast_factor=6.0** 調整輸入影像的對比度。
import torch
from PIL import Image
import torchvision.transforms.functional as F
img = Image.open('Nature_canada.jpg')
img = F.adjust_contrast(img, 6)
img.show()輸出

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