zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python-OpenCV图像处理-10-直方图的操作

PythonOpencv图像处理 操作 10 直方图
2023-09-14 09:13:04 时间

均值化:

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)

 因为这里的直方图均衡化只可用灰度图像。

cv2.equalizeHist函数原型:equalizeHist(src[, dst]) 。函数equalizeHist的作用:直方图均衡化,提高图像质量。

直方图均衡化:如果一副图像的像素占有很多的灰度级而且分布均匀,那么这样的图像往往有高对比度和多变的灰度色调。直方图均衡化就是一种能仅靠输入图像直方图信息自动达到这种效果的变换函数。它的基本思想是对图像中像素个数多的灰度级进行展宽,而对图像中像素个数少的灰度进行压缩,从而扩展像元取值的动态范围,提高了对比度和灰度色调的变化,使图像更加清晰。

局部增强:

#局部增强
def clahe_demo(image):
    gray =cv.cvtColor(image,cv.COLOR_BGR2GRAY)
    clahe =cv.createCLAHE(clipLimit=5.0,tileGridSize=(8,8))
    dst =clahe.apply(gray)
    cv.imshow("clahe_demo",dst)

全局直方图均衡化可能得到是一种全局意义上的均衡化,但是有的时候这种操作并不是很好,会把某些不该调整的部分给调整了。Opencv中还有一种直方图均衡化,它是一种局部直方图均衡化,也就是是说把整个图像分成许多小块(比如按10*10作为一个小块),那么对每个小块进行均衡化。

createCLAHE函数原型:createCLAHE([, clipLimit[, tileGridSize]])
clipLimit参数表示对比度的大小。
tileGridSize参数表示每次处理块的大小 。

clahe = cv.createCLAHE(clipLimit=5, tileGridSize=(8, 8))
dst = clahe.apply(gray) 把clahe这种局部直方图均衡化应用到灰度图gray

直方图的比较:

#直方图的比较
def create_rgb_hist(image):
    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):
    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))

巴氏距离:越小越相似

相关性:越接近于1越相似

卡方:越小越相似

测试demo:

src =cv.imread("C:\\Users\\william\\Pictures\\go.jpg")
cv.namedWindow("input image",cv.WINDOW_AUTOSIZE)
cv.imshow("input image",src)
clahe_demo(src)
image1 =cv.imread("C:\\Users\\william\\Pictures\\go.jpg")
image2 =cv.imread("C:\\Users\\william\\Pictures\\demo.jpg")
hist_compare(image1,image2)
cv.waitKey(0)
cv.destroyAllWindows()