PIL(Pillow)模块对图片进行简单操作以及matplotlib绘制图像直方图
环境:MacOS + Python2.7
1. 模块介绍
- PIL(Pillow)
PIL(Python Imaging Library)库,Python平台的图像处理标准库,但这个库现在已经停止更新了,所以使用Pillow, 它是由PIL fork而来的库。
安装方式(homebrew),在terminal输入
brew install Homebrew/science/pillow
#根据brew提示输入下面两行
mkdir -p /Users/Lychee/Library/Python/2.7/lib/python/site-packages
echo 'import site; site.addsitedir("/usr/local/lib/python2.7/site-packages")' >> /Users/Lychee/Library/Python/2.7/lib/python/site-packages/homebrew.pth在python环境测试,无报错则成功
from PIL import Image2. 对图片的基本操作
图片打开与显示
有两种方法:
1)利用操作系统自带图片浏览器打开from PIL import Image img = Image.open('./my_pictures/img.jpg') img.show()2) 结合matplotlib绘制图片
from PIL import Image import matplotlib.pyplot as plt img = Image.open('./my_pictures/img.jpg') plt.figure("flower") plt.imshow(img) plt.show()注意:在运行这段代码时可能会报错:
File “/usr/local/lib/python2.7/site-packages/PIL/Image.py”, line 709, in tostring
raise NotImplementedError(“tostring() has been removed. ”
NotImplementedError: tostring() has been removed. Please call tobytes() instead.是由于更新后的PIL中tostring()已经被舍弃,解决方式是直接打开出错的代码:Image.py,可以找到报错位置
将这段代码修改为:
然后保存即可。
再次运行上面的代码段,显示结果为:
这样显示的好处在于可以自定义名称,绘制坐标系等等。提取图片直方图
提取直方图的思路是:统计图像中像素点为某个值的个数,RGB彩色图像的提取就是将R\G\B三种颜色分别的0-255像素统计出来,然后绘制直方图。
对图像做的处理是:现将图像的R\G\B分离,然后将图像矩阵转换为一维(flatten函数)矩阵,接下来再开始统计。
# -*- coding: utf-8 -*-
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
src = Image.open('./my_pictures/img.jpg')
r,g,b = src.split() #分离R\G\B
plt.figure("flowerHist")
#要对图像求直方图,就需要先把图像矩阵进行flatten操作,使之变为一维数组,然后再进行统计
#分别提取R\G\B统计值,叠加绘图
ar = np.array(r).flatten()
plt.hist(ar,bins = 256, normed = 1, facecolor = 'red', edgecolor = 'red', hold = 1)
ag = np.array(g).flatten()
plt.hist(ag,bins = 256, normed = 1, facecolor = 'green', edgecolor = 'green', hold = 1)
ab = np.array(b).flatten()
plt.hist(ab,bins = 256, normed = 1, facecolor = 'blue', edgecolor = 'blue', hold = 1)
plt.show()参考博客:感谢~
http://blog.csdn.net/fuwenyan/article/details/53676153
http://www.linuxdiyf.com/linux/30432.html
版权声明:本文为Mengwei_Ren原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。