入门知识

  1. 颜色。如果你有使用颜料画画的经历,那么一定知道混合红、黄、蓝三种颜料可以得到其他的颜色,事实上这三种颜色就是美术中的三原色,它们是不能再分解的基本颜色。在计算机中,我们可以将红、绿、蓝三种色光以不同的比例叠加来组合成其他的颜色,因此这三种颜色就是色光三原色。在计算机系统中,我们通常会将一个颜色表示为一个RGB值或RGBA值(其中的A表示Alpha通道,它决定了透过这个图像的像素,也就是透明度)。

    名称 RGB值 名称 RGB值
    White(白) (255, 255, 255) Red(红) (255, 0, 0)
    Green(绿) (0, 255, 0) Blue(蓝) (0, 0, 255)
    Gray(灰) (128, 128, 128) Yellow(黄) (255, 255, 0)
    Black(黑) (0, 0, 0) Purple(紫) (128, 0, 128)
  2. 像素。对于一个由数字序列表示的图像来说,最小的单位就是图像上单一颜色的小方格,这些小方块都有一个明确的位置和被分配的色彩数值,而这些一小方格的颜色和位置决定了该图像最终呈现出来的样子,它们是不可分割的单位,我们通常称之为像素(pixel)。每一个图像都包含了一定量的像素,这些像素决定图像在屏幕上所呈现的大小,大家如果爱好拍照或者自拍,对像素这个词就不会陌生。

用Pillow处理图像

Pillow是由从著名的Python图像处理库PIL发展出来的一个分支,通过Pillow可以实现图像压缩和图像处理等各种操作。可以使用下面的命令来安装Pillow。

安装

1
pip install pillow
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
D:\Python\Python37\Scripts>easy_install.exe pip
WARNING: The easy_install command is deprecated and will be removed in a future version.
Searching for pip
Best match: pip 20.1.1
Adding pip 20.1.1 to easy-install.pth file
Installing pip-script.py script to d:\python\python37\Scripts
Installing pip.exe script to d:\python\python37\Scripts
Installing pip3-script.py script to d:\python\python37\Scripts
Installing pip3.exe script to d:\python\python37\Scripts
Installing pip3.8-script.py script to d:\python\python37\Scripts
Installing pip3.8.exe script to d:\python\python37\Scripts

Using d:\python\python37\lib\site-packages
Processing dependencies for pip
Finished processing dependencies for pip

D:\Python\Python37\Scripts>pip

Usage:
  pip <command> [options]

Commands:
  install                     Install packages.
  download                    Download packages.
  uninstall                   Uninstall packages.
  freeze                      Output installed packages in requirements format.
  list                        List installed packages.
  show                        Show information about installed packages.
  check                       Verify installed packages have compatible dependencies.
  config                      Manage local and global configuration.
  search                      Search PyPI for packages.
  cache                       Inspect and manage pip's wheel cache.
  wheel                       Build wheels from your requirements.
  hash                        Compute hashes of package archives.
  completion                  A helper command used for command completion.
  debug                       Show information useful for debugging.
  help                        Show help for commands.

General Options:
  -h, --help                  Show help.
  --isolated                  Run pip in an isolated mode, ignoring environment variables and user configuration.
  -v, --verbose               Give more output. Option is additive, and can be used up to 3 times.
  -V, --version               Show version and exit.
  -q, --quiet                 Give less output. Option is additive, and can be used up to 3 times (corresponding to WARNING, ERROR, and CRITICAL logging levels).
  --log <path>                Path to a verbose appending log.
  --proxy <proxy>             Specify a proxy in the form [user:passwd@]proxy.server:port.
  --retries <retries>         Maximum number of retries each connection should attempt (default 5 times).
  --timeout <sec>             Set the socket timeout (default 15 seconds).
  --exists-action <action>    Default action when a path already exists: (s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.
  --trusted-host <hostname>   Mark this host or host:port pair as trusted, even though it does not have valid or any HTTPS.
  --cert <path>               Path to alternate CA bundle.
  --client-cert <path>        Path to SSL client certificate, a single file containing the private key and the certificate in PEM format.
  --cache-dir <dir>           Store the cache data in <dir>.
  --no-cache-dir              Disable the cache.
  --disable-pip-version-check
                              Don't periodically check PyPI to determine whether a new version of pip is available for download. Implied with --no-index.
  --no-color                  Suppress colored output
  --no-python-version-warning
                              Silence deprecation warnings for upcoming unsupported Pythons.

D:\Python\Python37\Scripts>pip install pillow
Collecting pillow
  Downloading Pillow-8.3.1-1-cp37-cp37m-win_amd64.whl (3.2 MB)
     |████████████████████████████████| 3.2 MB 435 kB/s
Installing collected packages: pillow
Successfully installed pillow-8.3.1
WARNING: You are using pip version 20.1.1; however, version 21.2.1 is available.
You should consider upgrading via the 'd:\python\python37\python.exe -m pip install --upgrade pip' command.

D:\Python\Python37\Scripts>d:\python\python37\python.exe -m pip install --upgrade pip
Collecting pip
  Downloading pip-21.2.1-py3-none-any.whl (1.6 MB)
     |████████████████████████████████| 1.6 MB 504 kB/s
Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 20.1.1
    Uninstalling pip-20.1.1:
      Successfully uninstalled pip-20.1.1
Successfully installed pip-21.2.1

D:\Python\Python37\Scripts>pip show pip
Name: pip
Version: 21.2.1
Summary: The PyPA recommended tool for installing Python packages.
Home-page: https://pip.pypa.io/
Author: The pip developers
Author-email: distutils-sig@python.org
License: MIT
Location: d:\python\python37\lib\site-packages
Requires:
Required-by:

D:\Python\Python37\Scripts>

按照上面按照后,在编写过程中依然报错,import处下载了一次pil仍报错,又下载了一次pillow后成功了。

Pillow中最为重要的是Image类,可以通过Image模块的open函数来读取图像并获得Image类型的对象。

读取和显示图像

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from PIL import Image

# 读取图像获得Image对象
image = Image.open('messi.jpg')
# 通过Image对象的format属性获得图像的格式
print(image.format) # JPEG
# 通过Image对象的size属性获得图像的尺寸
print(image.size)   # (500, 750)
# 通过Image对象的mode属性获取图像的模式
print(image.mode)   # RGB
# 通过Image对象的show方法显示图像
image.show()

剪裁图像

1
2
# 通过Image对象的crop方法指定剪裁区域剪裁图像
image.crop((200, 150, 480, 400)).show()

生成缩略图

1
2
3
# 通过Image对象的thumbnail方法生成指定尺寸的缩略图
image.thumbnail((128, 128))
image.show()

缩放和黏贴图像

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# 读取neymarjr的照片获得Image对象
ney_image = Image.open('ney.jpg')
# 读取messi的照片获得Image对象
messi_image = Image.open('messi.jpg')
# 从messi的照片上剪裁出messi的头
messi_head = messi_image.crop((200, 150, 480, 400))
width, height = messi_head.size
# 使用Image对象的resize方法修改图像的尺寸
# 使用Image对象的paste方法将messi的头粘贴到ney的照片上
ney_image.paste(messi_head.resize((int(width / 1.5), int(height / 1.5))), (172, 40))
ney_image.show()

旋转和翻转

1
2
3
4
5
6
7
image = Image.open('messi.jpg')
# 使用Image对象的rotate方法实现图像的旋转
image.rotate(45).show()
# 使用Image对象的transpose方法实现图像翻转
# Image.FLIP_LEFT_RIGHT - 水平翻转
# Image.FLIP_TOP_BOTTOM - 垂直翻转
image.transpose(Image.FLIP_TOP_BOTTOM).show()

操作像素

1
2
3
4
5
for x in range(200, 480):
    for y in range(150, 400):
        # 通过Image对象的putpixel方法修改图像指定像素点
        image.putpixel((x, y), (128, 128, 128))
image.show()

滤镜效果

1
2
3
4
5
from PIL import ImageFilter

# 使用Image对象的filter方法对图像进行滤镜处理
# ImageFilter模块包含了诸多预设的滤镜也可以自定义滤镜
image.filter(ImageFilter.CONTOUR).show()

使用Pillow绘图

Pillow中有一个名为ImageDraw的模块,该模块的Draw函数会返回一个ImageDraw对象,通过ImageDraw对象的arclinerectangleellipsepolygon等方法,可以在图像上绘制出圆弧、线条、矩形、椭圆、多边形等形状,也可以通过该对象的text方法在图像上添加文字。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import random

from PIL import Image, ImageDraw, ImageFont


def random_color():
    """生成随机颜色"""
    red = random.randint(0, 255)
    green = random.randint(0, 255)
    blue = random.randint(0, 255)
    return red, green, blue


width, height = 800, 600
# 创建一个800*600的图像,背景色为白色
image = Image.new(mode='RGB', size=(width, height), color=(255, 255, 255))
# 创建一个ImageDraw对象
drawer = ImageDraw.Draw(image)
# 通过指定字体和大小获得ImageFont对象
# font = ImageFont.truetype('Kongxin.ttf', 32)
# 通过ImageDraw对象的text方法绘制文字
#drawer.text((300, 50), 'Hello, world!', fill=(255, 0, 0), font=font)
# 通过ImageDraw对象的line方法绘制两条对角直线
drawer.line((0, 0, width, height), fill=(0, 0, 255), width=2)
drawer.line((width, 0, 0, height), fill=(0, 0, 255), width=2)
xy = width // 2 - 60, height // 2 - 60, width // 2 + 60, height // 2 + 60
# 通过ImageDraw对象的rectangle方法绘制矩形
drawer.rectangle(xy, outline=(255, 0, 0), width=2)
# 通过ImageDraw对象的ellipse方法绘制椭圆
for i in range(4):
    left, top, right, bottom = 150 + i * 120, 220, 310 + i * 120, 380
    drawer.ellipse((left, top, right, bottom), outline=random_color(), width=8)
# 显示图像
image.show()
# 保存图像
image.save('result.png')

注意:上面代码中使用的字体文件需要根据自己准备,可以选择自己喜欢的字体文件并放置在代码目录下。

简单总结

使用Python语言做开发,除了可以用Pillow来处理图像外,还可以使用更为强大的OpenCV库来完成图形图像的处理,OpenCV(Open Source Computer Vision Library)是一个跨平台的计算机视觉库,可以用来开发实时图像处理、计算机视觉和模式识别程序。在我们的日常工作中,有很多繁琐乏味的任务其实都可以通过Python程序来处理,编程的目的就是让计算机帮助我们解决问题,减少重复乏味的劳动。