基于python的opencv项目实战笔记(七)—— 图像直方图

本文介绍了使用Python进行图像处理的基本操作,包括读取图像、直方图定义、彩色直方图统计、掩码操作、直方图均衡化和自适应直方图均衡化。通过实例演示了如何使用OpenCV库和matplotlib绘制直方图,以及clahe(局部对比度增强)的应用。
摘要由CSDN通过智能技术生成
import cv2 as cv
import matplotlib.pyplot as plt
import numpy as np
def cv_show(name,img):
    cv.imshow(name,img)
    cv.waitKey(0)
    cv.destroyAllWindows()
#直方图定义
def cv_hist(img):
    #第二个参数[0]为灰度图,[0][1][2]为彩色图像分别对应BGR。
    #第三个参数为掩模图像。统整幅图像的直方图就把它为 None。但如果要统计图像某一部分的直方图,就需要制作一个掩模图像使用。
    #第四个参数为BIN的数目,第五个参数为像素值范围常为[0,256]。
    hist = cv.calcHist([img], [0], None, [256], [0, 256])
    print(hist.shape)  # (256, 1)
    plt.hist(img.ravel(), 256)
    plt.show()
def cv_histr():
    img = cv.imread('D://cat.png')
    color = ('b', 'g', 'r')
    for i, col in enumerate(color):
        histr = cv.calcHist([img], [i], None, [256], [0, 256])
        plt.plot(histr, color=col)
        plt.xlim([0, 256])
    plt.show()
def cv_mask():
    img = cv.imread('D://cat.png', 0)
    mask = np.zeros(img.shape[:2], np.uint8)
    print(mask.shape)
    mask[100:300, 100:400] = 255#将部分区域改为白色,掩膜
    masked_img = cv.bitwise_and(img,img,mask=mask)#两图片进行与操作
    hist_full = cv.calcHist([img], [0], None, [256], [0, 256])
    hist_mask = cv.calcHist([img], [0], mask, [256], [0, 256])
    plt.subplot(221), plt.imshow(img, 'gray')
    plt.subplot(222), plt.imshow(mask, 'gray')
    plt.subplot(223), plt.imshow(masked_img, 'gray')
    plt.subplot(224), plt.plot(hist_full), plt.plot(hist_mask)
    plt.xlim([0, 256])
    plt.show()
#直方图均衡化
def cv_equ():
    img = cv.imread('D://clahe.png', 0)  # 0表示灰度图 #clahe
    plt.hist(img.ravel(), 256)
    plt.show()
    equ = cv.equalizeHist(img)
    plt.hist(equ.ravel(), 256)
    plt.show()
    res = np.hstack((img,equ))
    cv_show('res',res)
#自适应直方图均衡化
def cv_equ1():
    img = cv.imread('D://clahe.png', 0)  # 0表示灰度图 #clahe
    plt.hist(img.ravel(), 256)
    plt.show()
    equ = cv.equalizeHist(img)
    plt.hist(equ.ravel(), 256)
    plt.show()
    res = np.hstack((img, equ))
    cv_show('res', res)
    clahe = cv.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))#按块均衡
    res_clahe = clahe.apply(img)
    res = np.hstack((img, equ, res_clahe))
    cv_show('res',res)
img = cv.imread('D://cat.png',0)
#cv_hist(img)
#cv_histr()
#cv_mask()
#cv_equ()
cv_equ1()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值