图像均衡化与相关性的比较

""" 图像均衡化与相关性的比较 """
import cv2 as cv
import numpy as np


def equalHist_demo(image):
    """ 均衡化 :param image: :return: """
    # 均衡化必须处理的是灰度图像
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    # 均衡化处理函数
    dst = cv.equalizeHist(gray)
    cv.imshow("equalHist_demo", dst)


def clahe_demo(image):
    """ 自定义均衡化处理 :param image: :return: """
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    # 实例化均衡直方图函数
    clahe = cv.createCLAHE(clipLimit=5.0, tileGridSize=(8, 8))
    # 使用.apply进行均衡化操作
    dst = clahe.apply(gray)
    cv.imshow("clahe_demo", dst)


def create_rgb_hist(image):
    """ 这个函数的功能和原理还是不是很清楚 :param image: :return: """
    h, w, c = image.shape
    rgbHist = np.zeros([16 * 16 * 16, 1], np.float32)
    bsize = 256 / 16
    for row in range(h):
        for col in range(w):
            b = image[row, col, 0]
            g = image[row, col, 1]
            r = image[row, col, 2]
            index = np.int(b / bsize) * 16 * 16 + np.int(g / bsize) * 16 + np.int(r / bsize)
            rgbHist[np.int(index), 0] = rgbHist[np.int(index), 0] + 1
    return rgbHist


def hist_compare(image1, image2):
    """ 比较两个图像的相关性 :param image1: :param image2: :return: """
    hist1 = create_rgb_hist(image1)
    hist2 = create_rgb_hist(image2)
    match1 = cv.compareHist(hist1, hist2, cv.HISTCMP_BHATTACHARYYA)
    match2 = cv.compareHist(hist1, hist2, cv.HISTCMP_CORREL)
    match3 = cv.compareHist(hist1, hist2, cv.HISTCMP_CHISQR)
    print("巴氏距离: %s, 相关性: %s, 卡方: %s" % (match1, match2, match3))


src = cv.imread("img.jpg")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
equalHist_demo(src)
clahe_demo(src)

image1 = cv.imread("img.jpg")
image2 = cv.imread("img.jpg")
cv.imshow("image1", image1)
cv.imshow("image2", image2)
hist_compare(image1, image2)

cv.waitKey(0)
cv.destroyAllWindows()

效果展示


这里面我使用的是两张一样的图片,所以可以看到相关性为1.0