8、OpenCV Python 图像直方图

2023-04-28,,

 __author__ = "WSX"
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt def plot( img):
plt.hist(img.ravel() , 256 ,[0 ,256])
print(img.ravel()) #统计频次
plt.show() def hist( img ):#反应图像的主要特征
color = ("blue" ,"green" , "red")
for i , color in enumerate(color):
hist = cv.calcHist([img] , [i], None ,[256],[0,256]) #参数2:通道数 参数三:mask存在?
plt.plot(hist , color = color)
plt.xlim([0 , 256])
plt.show() #-------------------------------直方图应用-------------------
# 均衡化(调整对比度) 和 比较 # 整体均衡化(基于灰度图) 增强图像的一个手段
def equ_hist( img ):
gray = cv.cvtColor( img , cv.COLOR_BAYER_BG2GRAY)
dst = cv.equalizeHist( gray ) # 均衡化
cv.imshow("equ" ,dst) # 局部均衡化
def equ_hist( img ):
gray = cv.cvtColor( img , cv.COLOR_BAYER_BG2GRAY)
cla = cv.createCLAHE( clipLimit= 2, tileGridSize=(8,8)) # 均衡化
dst = cla.apply(gray)
cv.imshow("equ" ,dst) #直方图比较(多种比较方法)比较图片相似度
def creat_rgb_hist( img ):
h , w ,c = img.shape
rgbhist = np.zeros([16 * 16 * 16 , 1] ,np.float32)
bsize = 256 / 16
pass def hist_compare(img1 , img2): #比较图像的相似性
hist1 = creat_rgb_hist( img1 )
hist2 = creat_rgb_hist( img2 )
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)) #----------------------------直方图反向投影-------------------------- def main():
img = cv.imread("1.JPG")
cv.namedWindow("Show", cv.WINDOW_AUTOSIZE)
cv.imshow("Show", img)
#plot(img)
hist(img)
cv.waitKey(0)
cv.destroyAllWindows() main()

8、OpenCV Python 图像直方图的相关教程结束。

《8、OpenCV Python 图像直方图.doc》

下载本文的Word格式文档,以方便收藏与打印。