python opencv彩色图像自适应直方图均衡化

import numpy as np
import cv2 as cv

# 彩色图像进行自适应直方图均衡化
def hisEqulColor(img):
    ## 将RGB图像转换到YCrCb空间中
    ycrcb = cv.cvtColor(img, cv.COLOR_BGR2YCR_CB)
    # 将YCrCb图像通道分离
    channels = cv.split(ycrcb)
    # 以下代码详细注释见官网:
    # https://docs.opencv.org/4.1.0/d5/daf/tutorial_py_histogram_equalization.html
    clahe = cv.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
    clahe.apply(channels[0], channels[0])
    cv.merge(channels, ycrcb)
    cv.cvtColor(ycrcb, cv.COLOR_YCR_CB2BGR, img)
    return img


img = cv.imread(r'C:\Users\thorne\PycharmProjects\biyesheji\image\2.jpeg')
img1 = img.copy()
#自适应直方图均衡化后的图res1
res1 = hisEqulColor(img1)
#拼接图res
res = np.hstack((img, res1))
#例图太大了,缩小一下
#正常显示的话就是cv.imshow('img+img1',res)
img_test2=cv.resize(res, (0, 0), fx=0.5, fy=0.5, interpolation=cv.INTER_NEAREST)
cv.imshow('img+img1',img_test2)
cv.waitKey(0)

运行结果:

python opencv彩色图像自适应直方图均衡化_第1张图片


补充:还有全局自适应直方图均衡化

#!/usr/bin/env python
# coding=utf-8
import cv2 as cv

# 彩色图像全局直方图均衡化
def hisEqulColor1(img):
    # 将RGB图像转换到YCrCb空间中
    ycrcb = cv.cvtColor(img, cv.COLOR_BGR2YCR_CB)
    # 将YCrCb图像通道分离
    channels = cv.split(ycrcb)
    # 对第1个通道即亮度通道进行全局直方图均衡化并保存
    cv.equalizeHist(channels[0], channels[0])
    # 将处理后的通道和没有处理的两个通道合并,命名为ycrcb
    cv.merge(channels, ycrcb)
    # 将YCrCb图像转换回RGB图像
    cv.cvtColor(ycrcb, cv.COLOR_YCR_CB2BGR, img)
    return img

img = cv.imread(r'C:\Users\thorne\PycharmProjects\biyesheji\image\2.jpeg')
img1 = img.copy()
#全局自适应直方图均衡化
res1 = hisEqulColor1(img1)
#例图太大了,缩小一下
#正常显示的话就是cv.imshow('img1',res1)
img_test=cv.resize(res1, (0, 0), fx=0.5, fy=0.5, interpolation=cv.INTER_NEAREST)
cv.imshow('img1',img_test)
cv.waitKey(0)

运行结果:(我就显示了全局均衡化后的图) 

python opencv彩色图像自适应直方图均衡化_第2张图片

 

你可能感兴趣的:(计算机视觉,opencv,计算机视觉,python)