灰度直方图

什么是灰度直方图

在数字图像处理中,灰度直方图是一种计算代价非常小但却很有用的工具,它概括了一幅图像的灰度级信息。
灰度直方图是图像灰度级的函数,用来描述每个灰度级在图像矩阵中的像素个数或者占有率。

灰度直方图作用

图像对比度是通过灰度级范围来度量的,而灰度级范围可通过观察灰度直方图得到,灰度级范围越大代表对比度越高;
反之,对比度越低,低对比度的图像在视觉上给人的感觉是看起来不够清晰,所以通过算法调整图像的灰度值,从而调整图像的对比度是有必要的。

代码

# !/usr/bin/env python
# -*-encoding: utf-8-*-
# author:LiYanwei
# version:0.1


import numpy as np
import cv2
import matplotlib.pyplot as plt


'''
对于8位图来说,图像的灰度级范围是0~255之间的整数
'''
def get_gray_histogram1():
    '''
    matplotlib自带计算直方图计算函数
    :return:
    '''
    image = cv2.imread('img1.jpg', cv2.IMREAD_GRAYSCALE)
    # 获得图像矩阵的高,宽
    rows, cols = image.shape
    # 将二维的图像矩阵,变为一维的数组,便于计算灰度直方图
    pixelSequence = image.reshape([rows * cols, ])
    # 组数
    numberBins = 256
    # 计算灰度直方图
    histogram, bins, patch = plt.hist(pixelSequence, numberBins, facecolor='black', histtype='bar')
    # 设置坐标轴的标签
    plt.xlabel('gray level')
    plt.ylabel('number of pixels')
    # 设置坐标轴的范围
    y_maxValue = np.max(histogram)
    plt.axis([0, 255, 0, y_maxValue])
    plt.show()


def calc_gray_hist(image):
    # 灰度图像矩阵的高、宽
    rows, cols = image.shape
    # 存储灰度直方图
    grayHist = np.zeros([256], np.uint64)
    for r in range(rows):
        for c in range(cols):
            grayHist[image[r][c]] += 1
    return grayHist


def get_gray_histogram2():
    image = cv2.imread('img1.jpg', cv2.IMREAD_GRAYSCALE)
    # 计算灰度直方图
    grayHist = calc_gray_hist(image)
    # 画出灰度直方图
    x_range = range(256)
    plt.plot(x_range, grayHist, 'r', linewidth=2, c='black')
    # 设置坐标轴的范围
    y_maxValue = np.max(grayHist)
    plt.axis([0, 255, 0, y_maxValue])
    # 设置坐标轴的标签
    plt.xlabel('gray level')
    plt.ylabel('number of pixels')
    # 显示灰度直方图
    plt.show()


if __name__ == '__main__':
    # 第一种方法
    get_gray_histogram1()
    # 第二种方法
    get_gray_histogram2()

猜你喜欢

转载自www.cnblogs.com/Py00/p/8881448.html