Python Pillow 简明教程

Python Pillow - Enhancing Contrast

Enhancing contrast 是指提高图像的清晰度和质量的过程。它是一项图像处理技术,通过调整强度值或颜色的分布,增加图像中各种元素(例如物体、形状、边缘和纹理)之间的差异。该技术广泛应用于医学成像、计算机视觉、遥感和摄影等领域,以提高图像质量和获取更详细的视觉信息。

Python Pillow (PIL) 库在其 ImageEnhance 模块中提供了 Contrast() 类,用于将对比度增强应用于图像。

Enhancing Contrast of an Image

要调整图像的对比度,您可以使用对比度增强因子将 ImageEnhance.Contrast() 类应用于图像对象。它可以控制图像的对比度,就像调整电视机上的对比度一样。

以下是 ImageEnhance.Contrast() 类的语法 −

class PIL.ImageEnhance.Contrast(image)

以下是在图像中实现对比度增强的方法 −

  1. 使用 ImageEnhance.Contrast() 类创建一个对比度对象。

  2. 然后借助 contrast_object.enhance() 方法应用增强因子。

增强因子是传递给常见单个接口方法 enhance(factor) 的浮点值,在调整图像对比度方面起到重要作用。当使用 0.0 的因子时,它将生成一个纯灰色图像。因子 1.0 将给出原始图像,而当使用更大值时,图像的对比度也会增加,使其视觉上更清晰。

Example

以下示例演示了如何使用 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

输出对比度很高的输入图像 −

imageenhance contrast

Example

要降低图像的对比度,您可以使用小于 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