源码:
import cv2 as cv
import numpy as np
# 整体的直方图均衡化,可以增强图片对比度,但整体的
# 直方图均衡化可能会造成图片的某些部分的信息丢失。
# OpenCV中的直方图均衡化都是基于灰度图像,所以彩色图像要先转成灰度图。
def equalHist_demo(image):
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
# cv.equalizeHist()自动调整图像的对比度,把图像变清晰化,对比度增强,是图像增强的一个手段。
dst = cv.equalizeHist(gray)
cv.imshow("equal-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("clahe-demo", dst)
def create_rgb_hist(image):
h, w, c = image.shape
# 直方图的数据类型必须是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
print(rgbHist.shape)
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))
print("----------Hello Python----------")
src = cv.imread("C:/cvtest/0000.jpg")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
equalHist_demo(src)
clahe_demo(src)
image1 = cv.imread("C:/cvtest/0000.jpg")
image2 = cv.imread("C:/cvtest/woman1.jpg")
hist_compare(image1, image2)
cv.waitKey(0)
cv.destroyAllWindows()