Python Pillow - 增強對比度



增強對比度是指提高影像可見性和質量的過程。這是一種影像處理技術,透過調整強度值或顏色的分佈,來增加影像中各種元素(如物體、形狀、邊緣和紋理)之間的差異。此技術廣泛應用於醫學影像、計算機視覺、遙感和攝影等領域,以提高影像質量並獲得更詳細的視覺資訊。

Python Pillow (PIL) 庫在其 ImageEnhance 模組中提供了Contrast() 類,用於對影像應用對比度增強。

增強影像對比度

要調整影像的對比度,您可以將ImageEnhance.Contrast() 類與增強因子一起應用於影像物件。它可以控制影像的對比度,就像調整電視機的對比度一樣。

以下是 ImageEnhance.Contrast() 類的語法:

class PIL.ImageEnhance.Contrast(image)

以下是實現影像對比度增強的步驟:

  • 使用ImageEnhance.Contrast() 類建立一個對比度物件。

  • 然後使用contrast_object.enhance() 方法應用增強因子。

增強因子是一個傳遞給通用單介面方法 enhance(factor) 的浮點值,它在調整影像對比度方面起著重要作用。當使用 0.0 的因子時,它將產生一個純灰色的影像。1.0 的因子將給出原始影像,而當使用更大的值時,影像的對比度會增加,使其在視覺上更清晰。

示例

以下示例演示瞭如何使用 PIL.ImageEnhance 模組實現高對比度影像。

from PIL import Image, ImageEnhance

# Open the input image 
image = Image.open('Images/flowers.jpg')

# Create an ImageEnhance object for adjusting contrast
enhancer = ImageEnhance.Contrast(image)

# Display the original image
image.show()

# Enhance the contrast by a factor of 2 and display the result
enhancer.enhance(2).show()

輸入影像

sky flowers

輸出影像

輸出輸入影像的高對比度版本:

image enhance contrast

示例

要降低影像的對比度,可以使用小於 1 的對比度增強因子。以下是一個示例,說明了如何使用 PIL.ImageEnhance.Contrast 類建立輸入影像的低對比度版本。

from PIL import Image, ImageEnhance

# Open the input image 
image = Image.open('Images/flowers.jpg')

# Create an ImageEnhance object for adjusting contrast
enhancer = ImageEnhance.Contrast(image)

# Display the original image
image.show()

# Reduce the contrast by a factor of 0.5 and display the result
enhancer.enhance(0.5).show()

輸入影像

sky flowers

輸出影像

輸出輸入影像的低對比度版本:

low contrasted image
廣告