import matplotlib as mpl
mpl.use('TkAgg')
from matplotlib import pyplot as plt
import cv2 as cv
import numpy as np
print(mpl.get_backend())
def plotDemo(image):#直方图
plt.hist(image.ravel(),256,[0,256])#ravrl()函数是将多维数组降为一维数组;bin指定bins的个数;range表示箱子的上限和下限,即横坐标的显示范围,超出范围就会被舍弃
plt.show("BarChat")
def imageHist(image):#3通道图像直方图
color=('blue','green','red')
for i,color in enumerate(color):# enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据下标和数据,一般用在 for 循环当中。
hist=cv.calcHist([image],[i],None,[256],[0,256])
'''
images参数表示输入图像,传入时应该用中括号[ ]括起来
channels参数表示传入图像的通道,如果是灰度图像,那就不用说了,只有一个通道,值为0,如果是彩色图像(有3个通道),那么值为0,1,2,中选择一个,对应着BGR各个通道。这个值也得用[ ]传入。
mask参数表示掩膜图像。如果统计整幅图,那么为None。主要是如果要统计部分图的直方图,就得构造相应的掩膜来计算。
histSize参数表示灰度级的个数,需要中括号,比如[256]
ranges参数表示像素值的范围,通常[0,256]。此外,假如channels为[0,1],ranges为[0,256,0,180],则代表0通道范围是0-256,1通道范围0-180。
hist参数表示计算出来的直方图。
'''
plt.plot(hist,color=color)
plt.xlim([0,256])
plt.show("LineChart")
def equalHistDemo(image):#直方图均衡化作用:增强图像的对比度,黑色背景大米的例子----自适应均衡化
gray=cv.cvtColor(image,cv.COLOR_BGR2GRAY)#直方图均衡化必须是针对灰度级的图像的,因此需转化图像的色彩空间
dst=cv.equalizeHist(gray)
cv.imshow("equalize",dst)
def claheDemo(image):#直方图部分均衡化,即对均衡化的参数可调节----自定义均衡化
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
clahe=cv.createCLAHE(clipLimit=3.0,tileGridSize=(8,8))#clipLimit该参数控制均衡化的程度
dst=clahe.apply(gray)
cv.imshow("clahe",dst)
def createRGBhist(image):#RGB直方图
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*16+np.int(r/bsize)*16*16#必须全部转化为int类型
rgbHist[np.int(index),0]=rgbHist[np.int(index),0]+1
return rgbHist
def histCompare(image1,image2):#直方图比较
hist1=createRGBhist(image1)
hist2 = createRGBhist(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".foramt(match1,match2,match3))
#巴氏距离:越小越相似;相关性:越接近1越相似;卡方:越小越相似
src=cv.imread("E:\OpenCVTests\IMG_4482.JPG")
cv.namedWindow("input image",cv.WINDOW_AUTOSIZE)
cv.imshow("input image",src)
#plotDemo(src)
#imageHist(src)
#equalHistDemo(src)
#claheDemo(src)
#直方图比较
src1=cv.imread("E:\opencv-4.0.1-vc14_vc15\opencv-4.1.0-vc14_vc15\opencv\sources\samples\data\LinuxLogo.jpg")
src2=cv.imread("E:\opencv-4.0.1-vc14_vc15\opencv-4.1.0-vc14_vc15\opencv\sources\samples\data\WindowsLogo.jpg")
histCompare(src1,src2)
cv.waitKey(0)
cv.destroyAllWindows()
OpenCV学习Day04图像直方图、3通道直方图、直方图均衡化(2种)、直方图比较
最新推荐文章于 2023-02-03 20:37:59 发布