1. 灰度直方图
介绍
灰度直方图(Gray histogram)是关于灰度级分布的函数,是对图像中灰度级分布的统计。灰度直方图是将数字图像中的所有像素,按照灰度值的大小,统计其出现的频率。灰度直方图是灰度级的函数,它表示图像中具有某种灰度级的像素的个数,反映了图像中某种灰度出现的频率。
如果将图像总像素亮度(灰度级别)看成是一个随机变量,则其分布情况就反映了图像的统计特性,这可用probability density function (PDF)来刻画和描述,表现为灰度直方图。
实现
以下代码便于理解灰度直方图的计算,其中histogram函数是基于numpy简化的,运行结果如下。
# coding: utf8
from skimage import data
import matplotlib.pyplot as plt
import numpy as np
def histogram(a, bins=10, range=None):
"""
Compute the histogram of a set of data.
"""
import numpy as np
from numpy.core import linspace
from numpy.core.numeric import (arange, asarray)
# 转成一维数组
a = asarray(a)
a = a.ravel()
mn, mx = [mi + 0.0 for mi in range]
ntype = np.dtype(np.intp)
n = np.zeros(bins, ntype)
# 预计算直方图缩放因子
norm = bins / (mx - mn)
# 均分,计算边缘以进行潜在的校正
bin_edges = linspace(mn, mx, bins + 1, endpoint=True)
# 分块对于大数组可以降低运行内存,同时提高速度
BLOCK = 65536
for i in arange(0, len(a), BLOCK):
tmp_a = a[i:i + BLOCK]
tmp_a_data = tmp_a.astype(float)
# 减去Range下限,乘以缩放因子,向下取整
tmp_a = tmp_a_data - mn
tmp_a *= norm
indices = tmp_a.astype(np.intp)
# 对indices标签分别计数,标签等于bins减一
indices[indices == bins] -= 1
n += np.bincount(indices, weights=None,
minlength=bins).astype(ntype)
return n, bin_edges
if __name__ =="__main__":
img=data.coffee()
fig = plt.figure()
f1 = fig.add_subplot(141)
f1.imshow(img)
f1.set_title("image")
f2 = fig.add_subplot(142)
arr=img.flatten()
n, bins, patches = f2.hist(arr, bins=256, facecolor='red')
f2.set_title("plt_hist")
f3 = fig.add_subplot(143)
hist, others = np.histogram(arr, range=(0, arr.max()), bins=256)
f3.plot(others[1:],hist)
f3.set_title("np_hist1")
f4 = fig.add_subplot(144)
hist, others = histogram(arr, range=(0, arr.max()), bins=256)
f4.plot(others[1:], hist)
f4.set_title("np_hist2")
plt.show()