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
广告
© . All rights reserved.