图像分析一:灰度直方图和直方图均衡化

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()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xiangyong58

喝杯茶还能肝到天亮,共同进步

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值