1、直方图均衡化(调整图像对比度,图像清晰化),是图像增强的一个手段,使得亮的地方更亮,暗的地方更暗。可分为全局和局部两个方面。
2、直方图的比较
import cv2 as cv
import numpy as np
# 全局的直方图均衡化
def equalHist_demo(image):
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
dst = cv.equalizeHist(gray)
cv.imshow('equalHist-demo', dst)
# 局部的直方图均衡化
def clahe_demo(image):
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
clahe = cv.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
dst = clahe.apply(gray)
cv.imshow('equalHist-demo', dst)
# 创建彩色图像的直方图
def create_rgb_hist(image):
h, w, c = image.shape
# 创建RGB直方图时,数据类型必须是np.float32类型的
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):
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('C:/Users/Y/Pictures/Saved Pictures/rice.png')
cv.namedWindow('input image', cv.WINDOW_AUTOSIZE)
cv.imshow('input image', src)
clahe_demo(src)
image1 = cv.imread('C:/Users/Y/Pictures/Saved Pictures/lena.png')
image2 = cv.imread('C:/Users/Y/Pictures/Saved Pictures/lenanoise.png')
cv.imshow('image1', image1)
cv.imshow('image2', image2)
hist_compare(image1, image2)
cv.waitKey(0)
cv.destroyAllWindows()
3、直方图均衡化的图像
原图像 均衡化后的图像
2、直方图比较
图像一 图像二
显示结果: