本文已参与「新人创作礼」活动,一起开启掘金创作之路。
【python】通过Numpy及SciPy模块实现基本图像处理
1、 Numpy库
应用Numpy库进行图像处理,一个极其有用的例子是灰度变换后进行直方图均衡化。图像均衡化作为预处理操作,在归一化图像强度时是一个很好的方式,并且通过直方图均衡化可以增加图像对比度。下面是对图像直方图进行均衡化处理的例子:
from PIL import Image
from pylab import *
from PCV.tools import imtools
# 添加中文字体支持
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"c:\windows\fonts\SimSun.ttc", size=14)
im = array(Image.open('data/emp3.jpg').convert('L')) # 打开图像,并转成灰度图像
#im = array(Image.open('../data/AquaTermi_lowcontrast.JPG').convert('L'))
im2, cdf = imtools.histeq(im)
figure()
subplot(2, 2, 1)
axis('off')
gray()
title(u'原始图像', fontproperties=font)
imshow(im)
subplot(2, 2, 2)
axis('off')
title(u'直方图均衡化后的图像', fontproperties=font)
imshow(im2)
subplot(2, 2, 3)
axis('off')
title(u'原始直方图', fontproperties=font)
#hist(im.flatten(), 128, cumulative=True, normed=True)
hist(im.flatten(), 128)
subplot(2, 2, 4)
axis('off')
title(u'均衡化后的直方图', fontproperties=font)
#hist(im2.flatten(), 128, cumulative=True, normed=True)
hist(im2.flatten(), 128)
show()
2、SciPy模块
SciPy是一个开源的数学工具包,它是建立在NumPy的基础上的。它提供了很多有效的常规操作,包括数值综合、最优化、统计、信号处理以及图像处理。 图像降噪是一个在尽可能保持图像细节和结构信息时去除噪声的过程。我们可以在SciPy模板的基础上采用Rudin-Osher-Fatemi de-noising(ROF)模型进行降噪。图像去噪可以应用于很多场合,它涵盖了从你的度假照片使之更好看到卫星照片质量提高。如下:
from PIL import Image
from pylab import *
from numpy import *
from numpy import random
from scipy.ndimage import filters
from scipy.misc import imsave
from PCV.tools import rof
""" This is the de-noising example using ROF in Section 1.5. """
# 添加中文字体支持
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"c:\windows\fonts\SimSun.ttc", size=14)
im = array(Image.open('data/emp4.gif').convert('L'))
U,T = rof.denoise(im,im)
G = filters.gaussian_filter(im,10)
figure()
gray()
subplot(1,3,1)
imshow(im)
axis('off')
title(u'原噪声图像', fontproperties=font)
subplot(1,3,2)
imshow(G)
axis('off')
title(u'高斯模糊后的图像', fontproperties=font)
subplot(1,3,3)
imshow(U)
axis('off')
title(u'ROF降噪后的图像', fontproperties=font)
show()