在Python中使用PIL模块处理图像的教程

yipeiwu_com6年前Python基础

PIL:Python Imaging Library,已经是Python平台事实上的图像处理标准库了。PIL功能非常强大,但API却非常简单易用。
安装PIL

在Debian/Ubuntu Linux下直接通过apt安装:

$ sudo apt-get install python-imaging

Mac和其他版本的Linux可以直接使用easy_install或pip安装,安装前需要把编译环境装好:

$ sudo easy_install PIL

如果安装失败,根据提示先把缺失的包(比如openjpeg)装上。

Windows平台就去PIL官方网站下载exe安装包。
操作图像

来看看最常见的图像缩放操作,只需三四行代码:

import Image

# 打开一个jpg图像文件,注意路径要改成你自己的:
im = Image.open('/Users/michael/test.jpg')
# 获得图像尺寸:
w, h = im.size
# 缩放到50%:
im.thumbnail((w//2, h//2))
# 把缩放后的图像用jpeg格式保存:
im.save('/Users/michael/thumbnail.jpg', 'jpeg')

其他功能如切片、旋转、滤镜、输出文字、调色板等一应俱全。

比如,模糊效果也只需几行代码:

import Image, ImageFilter

im = Image.open('/Users/michael/test.jpg')
im2 = im.filter(ImageFilter.BLUR)
im2.save('/Users/michael/blur.jpg', 'jpeg')

效果如下:

201542995252889.jpg (500×300)

PIL的ImageDraw提供了一系列绘图方法,让我们可以直接绘图。比如要生成字母验证码图片:

import Image, ImageDraw, ImageFont, ImageFilter
import random

# 随机字母:
def rndChar():
  return chr(random.randint(65, 90))

# 随机颜色1:
def rndColor():
  return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))

# 随机颜色2:
def rndColor2():
  return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))

# 240 x 60:
width = 60 * 4
height = 60
image = Image.new('RGB', (width, height), (255, 255, 255))
# 创建Font对象:
font = ImageFont.truetype('Arial.ttf', 36)
# 创建Draw对象:
draw = ImageDraw.Draw(image)
# 填充每个像素:
for x in range(width):
  for y in range(height):
    draw.point((x, y), fill=rndColor())
# 输出文字:
for t in range(4):
  draw.text((60 * t + 10, 10), rndChar(), font=font, fill=rndColor2())
# 模糊:
image = image.filter(ImageFilter.BLUR)
image.save('code.jpg', 'jpeg');

我们用随机颜色填充背景,再画上文字,最后对图像进行模糊,得到验证码图片如下:

201542995319069.jpg (240×60)

如果运行的时候报错:

IOError: cannot open resource

这是因为PIL无法定位到字体文件的位置,可以根据操作系统提供绝对路径,比如:

复制代码 代码如下:
'/Library/Fonts/Arial.ttf'

要详细了解PIL的强大功能,请请参考PIL官方文档:

http://effbot.org/imagingbook/

相关文章

Python绘图Matplotlib之坐标轴及刻度总结

Python绘图Matplotlib之坐标轴及刻度总结

学习https://matplotlib.org/gallery/index.html 记录,描述不一定准确,具体请参考官网 Matplotlib使用总结图 import ma...

解决在Python编辑器pycharm中程序run正常debug错误的问题

解决在Python编辑器pycharm中程序run正常debug错误的问题

初学Python,写了一小段程序,在pycharm中debug一直报错,在网上搜了很久,尝试多种方法后还是没有用。 尝试了很久之后,发现这个问题是由于: 1、程序中有中文注释。 2、程...

Python+微信接口实现运维报警

说到运维报警,我觉得都可以写个长篇历史来详细解释了报警的前世来生,比如最早报警都是用邮件,但邮件实时性不高,比如下班回家总不能人一直盯着邮箱吧,所以邮件这种报警方式不适合用来报紧急的故障...

python中的__init__ 、__new__、__call__小结

1.__new__(cls, *args, **kwargs)  创建对象时调用,返回当前对象的一个实例;注意:这里的第一个参数是cls即class本身2.__init__(s...

python中日期和时间格式化输出的方法小结

本文实例总结了python中日期和时间格式化输出的方法。分享给大家供大家参考。具体分析如下: python格式化日期时间的函数为datetime.datetime.strftime();...