Pillow Image对象属性

1年前 (2024-04-26)

Image 对象有一些常用的基本属性,这些属性能够帮助我们了解图片的基本信息,下面对这些属性做简单的讲解:

1) size:查看图像的尺寸

from PIL import Image

im = Image.open("C:/Users/Administrator/Desktop/c-net.png")

#打印image对象

print(im)

#查看尺寸

print("宽是%s高是%s"%(im.width,im.height))

#或者通过size查看

print("图像的大小size:",im.size)

输出结果:

<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=455x191 at 0x381C750>

宽是455高是191

图像的大小size: (455, 191)

2) format:查看图片的格式

from PIL import Image

im = Image.open("C:/Users/Administrator/Desktop/c-net.png")

print("图像的格式:",im.format)

输出结果:

图像的格式: PNG

3) readonly:图片是否为只读

from PIL import Image

im = Image.open("C:/Users/Administrator/Desktop/c-net.png")

print("图像是否为只读:",im.readonly)

该属性的返回为 0 或者 1,分别对应着是和否,输出结果如下:

图像是否为只读: 1

4) info:查看图片相关信息

from PIL import Image

im = Image.open("C:/Users/Administrator/Desktop/c-net.png")

# 包括了每英寸像素点大小和截图软件信息

print("图像信息:",im.info)

该属性的返回值为字典格式,输出结果如下:

图像信息: {'dpi': (96, 96), 'Software': 'Snipaste'}

5) mode:图像模式

from PIL import Image

im = Image.open("C:/Users/Administrator/Desktop/c-net.png")

print("图像模式信息:",im.mode)

输出结果:

图像的模式: RGBA

上述涉及了许多图片模式的名称,比如 RGB、RGBA 等,下面对常用的图片模式做简单的总结,如下表所示:

图片模式

mode

描述

1

1 位像素(取值范围 0-1),0表示黑,1 表示白,单色通道。

L

8 位像素(取值范围 0 -255),灰度图,单色通道。

P

8 位像素,使用调色板映射到任何其他模式,单色通道。

RGB

3 x 8位像素,真彩色,三色通道,每个通道的取值范围 0-255。

RGBA

4 x 8位像素,真彩色+透明通道,四色通道。

CMYK

4 x 8位像素,四色通道,可以适应于打印图片。

YCbCr

3 x 8位像素,彩格式,三色通道。

LAB

3 x 8位像素,L * a * b颜色空间,三色通道

HSV

3 x 8位像素,色相,饱和度,值颜色空间,三色通道。

I

32 位有符号整数像素,单色通道。

F

32 位浮点像素,单色通道。