原图:

全局直方图均衡化:

clahe,局部直方图均衡化:

直方图比较:
图1:

图2:

直方图比较结果:
巴氏距离为:0.09168121741644489, 相关度为:0.9793654472068899, 卡方距离为:26024.95389270589

代码部分:

import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt


def equalize_hist(image):
    # 全局直方图均衡化,用于增强对比度
    # 只能处理灰度图像
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    plt.hist(gray.ravel(), 256, [0, 256], color="red")
    dst = cv.equalizeHist(gray)
    plt.hist(dst.ravel(), 256, [0, 256], color="yellow")
    plt.show()
    cv.imshow("equalize_hist", dst)


def clahe_demo(image):
    # 局部直方图均衡化
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    plt.hist(gray.ravel(), 256, [0, 256], color="red")
    clahe = cv.createCLAHE(clipLimit=5.0, tileGridSize=(8, 8))
    dst = clahe.apply(gray)
    plt.hist(dst.ravel(), 256, [0, 256], color="yellow")
    plt.show()
    cv.imshow("clahe", dst)


def create_rgb_hist(image):
    # 生成一个sparse的色彩直方图
    h, w, c = image.shape
    rgbHist = np.zeros([16*16*16, 1], np.float32)
    # 将每种颜色的亮度值分为16组
    bsize = 256 / 16
    for row in range(h):
        for col in range(w):
            # 得到该像素点的颜色值
            b = image[row, col, 0]
            g = image[row, col, 0]
            r = image[row, col, 0]
            # 计算该像素值在直方图中的位置(稀疏直方图)
            index = np.int(b/bsize)*16*16 + np.int(g/bsize)*16 + np.int(r/bsize)
            # 数量加1
            rgbHist[np.int(index), 0] += 1
    return rgbHist


def hist_compare_demo(image1, image2):
    hist1 = create_rgb_hist(image1)
    hist2 = create_rgb_hist(image2)
    """ cv.compareHist: src1:参与比较的图片1 src2:参与比较的图片2 method:比较方法,多种可选 注意:对于src1与src2可以是1,2或者3维的直方图,可以是高密度的也可以是稀疏的 但是超过了3维后,可能就会出现aliasing and sampling problems“混叠采样问题” """
    # 巴氏距离比较
    result1 = cv.compareHist(hist1, hist2, cv.HISTCMP_BHATTACHARYYA)
    # 相关性比较
    result2 = cv.compareHist(hist1, hist2, cv.HISTCMP_CORREL)
    # 卡方比较
    result3 = cv.compareHist(hist1, hist2, cv.HISTCMP_CHISQR)
    print("巴氏距离为:{}, 相关度为:{}, 卡方距离为:{}".format(result1, result2 ,result3))


src = cv.imread("data/pic6.png")
cv.imshow("original", src)
# equalize_hist(src)
# clahe_demo(src)
image1 = cv.imread("data/graf1.png")
image2 = cv.imread("data/graf3.png")
hist_compare_demo(image1, image2)
# 巴氏距离为:0.09168121741644489, 相关度为:0.9793654472068899, 卡方距离为:26024.95389270589


cv.waitKey(0)
cv.destroyAllWindows()

本文地址:https://blog.csdn.net/weixin_43860783/article/details/109954084