如何用Python将PIL图像转换为灰度

536 阅读1分钟

PIL是Python成像库,为Python解释器提供了图像编辑功能。

将PIL图像转换成灰度

要在Python中把PIL 图像转换成灰度,可以使用**ImageOps.grayscale()**方法。PIL模块提供了ImageOps类,它提供了各种方法来帮助我们修改图像。

为了在Python中打开图像,PIL提供了一个带有open()图像的Image类。因此,我们可以打开图像。

Pillow支持各种图像文件格式,如PNG、JPEG、PPM、GIF、TIFF和BMP。

Pillow支持图像编辑操作,如裁剪调整大小、向图像添加文本、旋转和灰度。

ImageOps.grayscale()

ImageOps.grayscale()函数将RGB图像转换为灰度图像。完整的像素会变成灰色,而不会看到其他颜色。

语法

ImageOps.grayscale(image)

参数

它需要一个图像作为参数,将其转换为灰度。这是一个必要的参数,因为它是一个输入图像。

例子

使用PIL.ImageOps.grayscale()方法将RGB图像转换为灰度图像:

# Importing Image and ImageOps module from PIL package
from PIL import Image, ImageOps

# creating an og_image object
og_image = Image.open("./forest.jpg")
og_image.show()

# applying grayscale method
gray_image = ImageOps.grayscale(og_image)
gray_image.show()

输出

Convert PIL Image to Grayscale in Python

你可以使用save()方法保存灰度图像:

# Importing Image and ImageOps module from PIL package
from PIL import Image, ImageOps

# creating an og_image object
og_image = Image.open("./forest.jpg")

# applying grayscale method
gray_image = ImageOps.grayscale(og_image)
gray_image.save('gray_image.png')

save()方法在我们的文件系统中存储图像。它需要一个叫做文件名的参数。

如果你运行上述代码,图像将被保存在你当前的项目文件夹中。

这就是在Python中把PIL图像转换成灰度的过程。