计算机视觉:基于Python PIL库下的图片基本处理方法

  首先要给自己的python加载PIL(Python Imagin Libray,图像处理类库)。需要特别注意的是,PIL只支持到Python 2.7版本,Python2.7之后的Python版本需要加载PIL的派生Pillow,Pillow可以通过在cmd命令行里:

pip install Pillow

或者是同样在命令行cmd里:

easy_install Pillow

安装成功后就可以使用PIL库里的一些操作来对图像进行处理了。

以下是使用PIL 库进行的一些图像处理

首先是本次处理的原图:

首先让我们在IDE导入需要使用到的python库

>>> pil_m=Image.open("D:/pythondemo/1/test2.jpg")
>>> im=array(pil_m)
>>> imshow(im)
<matplotlib.image.AxesImage object at 0x0000027C1111E748>
>>> x=[100,100,400,400]
>>> y=[200,500,200,500]
>>> plot(x,y,'r*')
[<matplotlib.lines.Line2D object at 0x0000027C1111EB00>]
>>> title('picture')
Text(0.5, 1.0, 'picture')
>>> show()

读入这张图片

 pil_m=Image.open("D:/pythondemo/1/test2.jpg")

#读取图像到数组中

im=array(pil_m)

imshow(im)
<matplotlib.image.AxesImage object at 0x0000027C103FC278>
>>> show()

在图像里绘制一些点和线:

>>> pil_m=Image.open("D:/pythondemo/1/test2.jpg")
>>> im=array(pil_m)
>>> imshow(im)
<matplotlib.image.AxesImage object at 0x0000027C1111E748>
>>> x=[100,100,400,400]
>>> y=[200,500,200,500]
>>> plot(x,y,'r*')
[<matplotlib.lines.Line2D object at 0x0000027C1111EB00>]
>>> title('picture')
Text(0.5, 1.0, 'picture')
>>> show()

将图像转换成灰度图像,绘制直方图:

>>> im=array(pil_m.convert('L'))
>>> figure()
>>> gray()
>>> contour(im,origin='image')
>>> axis('equal')
>>> axis('off')
>>> figure()
>>> hist(im.flatten(),128)
>>> show()

 

图像的直方图均衡:

首先先打开图片,并将图片处理成灰度图像。

im=array(Image.open('test2.jpg').convert('L'));

下面这个函数时直方图均衡化的具体实现。

from PIL import Image
from numpy import *
def histeq(im,nbr_bins=256):
 
  
  
  imhist,bins = histogram(im.flatten(),nbr_bins,normed=True)
  cdf = imhist.cumsum() # cumulative distribution function
  cdf = 255 * cdf / cdf[-1] 
 

  im2 = interp(im.flatten(),bins[:-1],cdf)
 
  return im2.reshape(im.shape), cdf

这个函数前的两个包的导入不要忽略了,不然可能会出现histogram未定义的报错。

之后调用函数,即可实现直方图均衡。

im2,cdf=imtool.histeq(im)
imshow(im2)
show()

可以见到,经过直方图均衡,图像的视觉效果更佳了。

高斯滤波:

使用高斯滤波需要导入python的Scipy包,它提供了一些图像处理需要的操作,可以实现数值积分、优化、统计、信号处理等等功能。

导入方法是在cmd命令行里:

pip install scipy

本次进行处理的原图依然采用我们进行直方图均衡时的图片。

 from PIL import Image
 from numpy import*
 from scipy.ndimage import filters

 #使用σ=2的高斯滤波器
 im2=filters.gaussian_filter(im,2)
 #使用σ=5的高斯滤波器
 im2=filters.gaussian_filter(im,5)
 #使用σ=10的高斯滤波器
 im2=filters.gaussian_filter(im,5)  
 

 

 

 

                                                            

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值