VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • Python图像处理库:Pillow 初级教程

Image类

Pillow中最重要的类就是Image,该类存在于同名的模块中。可以通过以下几种方式实例化:从文件中读取图片,处理其他图片得到,或者直接创建一个图片。

使用Image模块中的open函数打开一张图片:

1
2
3
4
5
6
>>> from PIL import Image
>>> im = Image.open("lena.ppm")
如果打开成功,返回一个Image对象,可以通过对象属性检查文件内容
>>> from __future__ import print_function
>>> print(im.format, im.size, im.mode)
PPM (512, 512) RGB

format属性定义了图像的格式,如果图像不是从文件打开的,那么该属性值为None;size属性是一个tuple,表示图像的宽和高(单位为像素);mode属性为表示图像的模式,常用的模式为:L为灰度图,RGB为真彩色,CMYK为pre-press图像。

如果文件不能打开,则抛出IOError异常。

当有一个Image对象时,可以用Image类的各个方法进行处理和操作图像,例如显示图片:

1
>>> im.show()

ps:标准版本的show()方法不是很有效率,因为它先将图像保存为一个临时文件,然后使用xv进行显示。如果没有安装xv,该函数甚至不能工作。但是该方法非常便于debug和test。(windows中应该调用默认图片查看器打开)

读写图片

Pillow库支持相当多的图片格式。直接使用Image模块中的open()函数读取图片,而不必先处理图片的格式,Pillow库自动根据文件决定格式。

Image模块中的save()函数可以保存图片,除非你指定文件格式,那么文件名中的扩展名用来指定文件格式。

图片转成jpg格式

1
2
3
4
5
6
7
8
9
10
11
from __future__ import print_function
import os, sys
from PIL import Image
for infile in sys.argv[1:]:
    f, e = os.path.splitext(infile)
    outfile = + ".jpg"
    if infile != outfile:
        try:
            Image.open(infile).save(outfile)
        except IOError:
            print("cannot convert", infile)

save函数的第二个参数可以用来指定图片格式,如果文件名中没有给出一个标准的图像格式,那么第二个参数是必须的。

创建缩略图

1
2
3
4
5
6
7
8
9
10
11
12
13
from __future__ import print_function
import os, sys
from PIL import Image
size = (128128)
for infile in sys.argv[1:]:
    outfile = os.path.splitext(infile)[0+ ".thumbnail"
    if infile != outfile:
        try:
            im = Image.open(infile)
            im.thumbnail(size)
            im.save(outfile, "JPEG")
        except IOError:
            print("cannot create thumbnail for", infile)

相关教程