Python图像处理库:Pillow 2.1.0

本文介绍了Python图像处理库Pillow 2.1.0,重点讨论了Image类的使用,包括读写图片、高级图片增强、加水印等操作。在微信跳一跳辅助程序中,Pillow用于处理图像。通过Pillow,可以轻松实现图片的裁剪、旋转、过滤、模式转换等功能,并能对动态图进行处理。
摘要由CSDN通过智能技术生成

因为博主最近稍微研究了一下微信跳一跳辅助程序,从而认识了PIL这么个东东,然后就有了本文

在微信跳一跳中Pillow主要用法:

from PIL import Image
im = Image.open('./autojump.png')
Image.open('./autojump.png').load()

成绩只是附带结果,探究真理最重要!

这里写图片描述
Pillow 2.1.0下载

Pillow is the “friendly” PIL fork by Alex Clark and Contributors. PIL is the Python Imaging Library by Fredrik Lundh and Contributors.

Why a fork?
PIL is not setuptools compatible.

Port existing PIL-based code to Pillow

Pillow is a functional drop-in replacement for the Python Imaging Library. To run your existing PIL-compatible code with Pillow, it needs to be modified to import the Imaging module from the PIL namespace instead of the global namespace. I.e. change:

import Image

to:

from PIL import Image

Note

If your code imports from _imaging, it will no longer work.

The preferred, future proof method of importing the private _imaging module is:

from PIL import Image
_imaging = Image.core

Image类

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

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

>>> from PIL import Image
>>> img = Image.open('./autojump.png')

如果打开成功,返回一个Image对象,可以通过对象属性检查文件内容

>>> from __future__ import print_function
>>> print(img.format,img.size,img.mode)
PNG (1440, 2560) RGBA

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

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

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

>>> img.show()

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

读写图片

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

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

图片转成jpg格式

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 = f + ".jpg"
    if
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值