使用Python进行数字图像处理

来源:互联网 发布:承蒙厚爱 却知不恭 编辑:程序博客网 时间:2024/06/03 15:06

PIL(Python Imaging Library),是Python平台上的图像处理标准库。功能非常强大,API却简单易用。
由于PIL仅支持到Python2.7,加上年久失修,于是一群志愿者在PIL的基础上创建了兼容的版本,名叫Pillow,支持最新的Python3.x,又加入了许多新的特性。

— 廖雪峰

1. 安装Pillow

在命令行使用pip安装即可。

pip install pillow

官方文档:
Pillow官方文档

2. 操作图像

2.1 图像的打开、旋转和显示

将图像旋转90°,显示

from PIL import Imageim = Image.open("Middlebury_02_noisy_depth.PNG")im.rotate(45).show()

2.2 图像的保存

为当前目录中的PNG文件创建一个128*128的缩略图。

from PIL import Imageimport glob,ossize = 128,128for infile in glob.glob("*.PNG"):    file,ext = os.path.splitext(infile)    im = Image.open(infile)    im.thumbnail(size)    im.save(file + ".thumbnail","PNG")

官网参考

2.3 同时展示多张图片

Display this image.

Image.show(title=None,command=None)

This method is mainly intended for debugging purposes.
On windows, it saves the image to a temporary BMP file and uses the standard BMP display utility to show it (usually Paint).

Parameters:

  • title:Optional title to use for the image window,where possible
  • command:command used to show the image

这个任务对于opencv和Matlab都很简单。
opencv的实现:在一个窗口中显示两张图片
Matlab的实现:用subplot即可。

那么用python如何做到这一点儿呢?网上找了很多方法,感觉均是云里雾里的,直到我看到了下面这句话:(福音的柑橘)

在 python 中除了用 opencv,也可以用 matplotlib 和 PIL 这两个库操作图片。本人偏爱 matpoltlib,因为它的语法更像 matlab。

在matplotlib中,一个Figure对象可以包含多个子图(Axes),可以使用subplot()快速绘制。
matplotlib绘制多个子图——subplot

#!/usr/bin/env python3        # -*- coding: utf-8 -*-  import matplotlib.pyplot as pltimport numpy as npdef f(t):    return np.exp(-t) * np.cos(2 * np.pi * t)if __name__=='__main__':    t1 = np.arange(0, 5, 0.1)    t2 = np.arange(0, 5, 0.02)    plt.figure(12)    plt.subplot(221)    plt.plot(t1, f(t1), 'bo', t2, f(t2), 'r--')    plt.subplot(222)    plt.plot(t2, np.cos(2 * np.pi * t2), 'r--')    plt.subplot(212)    plt.plot([1,2,3,4],[1,4,9,16])    plt.show()

这里写图片描述

2 0
原创粉丝点击