Python编程-计算图像直方图

来源:互联网 发布:手机网游破解软件 编辑:程序博客网 时间:2024/06/02 02:54

灰度直方图:反映的是一幅图像中各灰度级像素出现的频率。以灰度级为横坐标,纵坐标为灰度级的频率(或各灰度级的个数),绘制而成的关系图就是灰度直方图。它是图像的一个重要特征,反映了图像灰度分布的情况,同时也是直方图均衡化的基础。
频率的计算式为 这里写图片描述
直方图的计算:
这里写图片描述 这里写图片描述

                该图像像元总数 为8 * 8 = 64 , i = [0,7]                                      v0 = 5 / 64                              v1 = 12 / 64                              v2 = 18 / 64                              v3 = 8 / 64                              v4 = 1 / 64                              v5 = 5 /64                              v6 = 8 / 64                              v7 = 5 /64

Python代码实现:
该篇文章仅是本人做实验的的结果,代码的执行效率可能不高,比不上pylab中封装好的hist(),欢迎广大在图像处理或计算机视觉上有兴趣的网友提出好的优化算法。

from PIL import Imagefrom numpy import *import matplotlib.pyplot as pltdef calHist(path):    #open the image and convert to grayscale     #transform it into array    img = array(Image.open(path).convert("L"))    m = img.shape[0]#get the number of row    n = img.shape[1]#get the number of column    l = m * n    img = img.reshape(l)#adjust img to one dimension    histo = zeros(256)#create a matrix with all of 0    histo = histo.reshape(256)    for value in range(256):        for i in img:            if i == value:               histo[value] = histo[value] + 1    #histo = histo / l    return histodef drawHist(myList,Title,xLabel,yLabel,xMin,xMax,yMin,yMax):    plt.hist(myList,256)    plt.xlabel(xLabel)    plt.xlim(xMin,xMax)    plt.ylabel(yLabel)    plt.ylim(yMin,yMax)    plt.title(Title)    plt.show()

声明:本人第一次写博客,有一些文字内容参考了网上一些文档或PPT。博客的版面设计弄得不好看,请多见谅!

原创粉丝点击