Python Pillow 使用 Image 模块

Python Pillow 使用 Image 模块

为了显示图像,pillow 库使用其中的一个图像类。pillow 包内的 image 模块包含了一些重要的内置函数,例如载入图像或创建新图像等。

打开、旋转和显示图像

要载入图像,我们简单地从 pillow 导入 image 模块并调用 Image.open(),传递图像文件名。

我们将使用 PIL 模块而不是调用 Pillow 模块,以使其向后兼容一个称为 Python Imaging Library (PIL) 的旧模块。所以我们的代码以from PIL import Image 开始而不是 from Pillow import Image

接下来,我们要通过调用 Image.open() 函数来载入图像,它返回一个 Image 对象数据类型的值。我们对图像对象所做的任何修改都可以使用 save() 方法保存到图像文件。我们接收到的图像对象(通过 Image.open())以后可以用于对该图像对象进行缩放、裁剪、绘制或其他图像处理方法。

示例

以下示例演示了使用 Python Pillow 对图像进行旋转:

from PIL import Image
#Open image using Image module
im = Image.open("images/cuba.jpg")
#Show actual Image
im.show()
#Show rotated Image
im = im.rotate(45)
im.show()

输出

如果你将以上程序保存为Example.py并执行,它将使用标准PNG显示工具显示原始和旋转的图像,如下所示:

实际图像

Python Pillow 使用 Image 模块

旋转图像(45度)

Python Pillow 使用 Image 模块

图像模块的属性

Image类的实例具有一些属性。让我们通过示例来了解其中的一些属性。

Image.filename

此函数用于获取图像的文件名或路径。

>>>image = Image.open('beach1.jpg')
>>> image.filename
'beach1.jpg'

Image.format

此函数返回图像文件的文件格式,如’JPEG’、’BMP’、’PNG’等。

>>> image = Image.open('beach1.jpg')
>>>
>>> image.format
'JPEG'

Image.mode

用于获取图像使用的像素格式。典型的值有 “1”, “L”, “RGB” 或 “CMYK”。

>>> image.mode
'RGB'

Image.size

它返回一个由图像的高度和宽度组成的元组。

>>> image.size
(1280, 721)

Image.width

它仅返回图像的宽度。

>>> image.width
1280

Image.height

它只返回图像的高度。

>>> image.height
721

Image.info

它会返回一个包含与图片相关数据的字典。

>>> image.info
{'jfif': 257, 'jfif_version': (1, 1), 'dpi': (300, 300), 'jfif_unit': 1, 'jfif_density': (300, 300), 'exif': b"Exif\x00\x00MM\x00*\x00\x00\x00
....
....
\xeb\x00\x00'\x10\x00\x00\xd7\xb3\x00\x00\x03\xe8"}

Image.palette

返回颜色调色板表格,如果有的话。

>>> image.palette

输出如上 − 无

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程