python计算机视觉 1.3.5 图像平均
1.3.5 图像平均 图像平均操作是减少图像噪声的一种简单方式,通常用于艺术特效。 我们可以简单 地从图像列表中计算出一幅平均图像。假设所有的图像具有相同的大小, 我们可以 将这些图像简单地相加,然后除以图像的数目,来计算平均图像。 下面的函数可以 用于计算平均图像,将其添加到 imtool.py 文件里:
def compute_average(imlist):
""" Compute the average of a list of images. """ # open first image and make into array of type float averageim = array(Image.open(imlist[0]), 'f') skipped = 0 for imname in imlist[1:]: try: averageim += array(Image.open(imname)) except: print imname + "...skipped" skipped += 1 averageim /= (len(imlist) - skipped) # return average as uint8 return array(averageim, 'uint8')
该函数包括一些基本的异常处理技巧,可以自动跳过不能打开的图像。 我们还可以 使用 mean() 函数计算平均图像。mean() 函数需要将所有的图像堆积到一个数组中; 也就是说,如果有很多图像,该处理方式需要占用很多内存。
读取照片文件的函数
返回值为: 路径/文件名(这里为照片).后缀(这里后缀格式为.png)
def get_imlist(path): """ Returns a list of filenames for all jpg images in a directory. """ return [os.path.join(path,f) for f in os.listdir(path) if f.endswith('.png')]
以上两个函数都在本书附带的名为PCV的库中,新手学习本书之前一定先去这个网站http://programmingcomputervision.com/ 下载 PCV库 装好,这是一个小坑。。。。
# -*- coding: utf-8 -*- from PCV.tools.imtools import get_imlist 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) filelist = get_imlist('D:/pictures') #文件夹下的图片文件名(包括后缀名) print filelist avg = imtools.compute_average(filelist) for impath in filelist: im1 = array(Image.open(impath)) subplot(2, 2, filelist.index(impath)+1) imshow(im1) imNum=str(filelist.index(impath)+1) title(u'待平均图像'+imNum, fontproperties=font) axis('off') subplot(2, 2, 4) imshow(avg) title(u'平均后的图像', fontproperties=font) axis('off') show()
最后看一下效果吧!