1 __author__ = "WSX" 2 import cv2 as cv 3 import numpy as np 4 from matplotlib import pyplot as plt 5 6 def plot( img): 7 plt.hist(img.ravel() , 256 ,[0 ,256]) 8 print(img.ravel()) #统计频次 9 plt.show() 10 11 def hist( img ):#反应图像的主要特征 12 color = ("blue" ,"green" , "red") 13 for i , color in enumerate(color): 14 hist = cv.calcHist([img] , [i], None ,[256],[0,256]) #参数2:通道数 参数三:mask存在? 15 plt.plot(hist , color = color) 16 plt.xlim([0 , 256]) 17 plt.show() 18 19 #-------------------------------直方图应用------------------- 20 # 均衡化(调整对比度) 和 比较 21 22 # 整体均衡化(基于灰度图) 增强图像的一个手段 23 def equ_hist( img ): 24 gray = cv.cvtColor( img , cv.COLOR_BAYER_BG2GRAY) 25 dst = cv.equalizeHist( gray ) # 均衡化 26 cv.imshow("equ" ,dst) 27 28 # 局部均衡化 29 def equ_hist( img ): 30 gray = cv.cvtColor( img , cv.COLOR_BAYER_BG2GRAY) 31 cla = cv.createCLAHE( clipLimit= 2, tileGridSize=(8,8)) # 均衡化 32 dst = cla.apply(gray) 33 cv.imshow("equ" ,dst) 34 35 #直方图比较(多种比较方法)比较图片相似度 36 def creat_rgb_hist( img ): 37 h , w ,c = img.shape 38 rgbhist = np.zeros([16 * 16 * 16 , 1] ,np.float32) 39 bsize = 256 / 16 40 pass 41 42 43 def hist_compare(img1 , img2): #比较图像的相似性 44 hist1 = creat_rgb_hist( img1 ) 45 hist2 = creat_rgb_hist( img2 ) 46 match1 = cv.compareHist( hist1 , hist2, cv.HISTCMP_BHATTACHARYYA ) #第三个参数 是 比较的方式 47 match2 = cv.compareHist(hist1, hist2, cv.HISTCMP_CORREL) 48 match3 = cv.compareHist(hist1, hist2, cv.HISTCMP_CHISQR) 49 print("""巴氏:%s 50 相关性:%s 51 卡方:%s 52 """ %(match1 , match2 ,match3)) 53 54 #----------------------------直方图反向投影-------------------------- 55 56 57 def main(): 58 img = cv.imread("1.JPG") 59 cv.namedWindow("Show", cv.WINDOW_AUTOSIZE) 60 cv.imshow("Show", img) 61 #plot(img) 62 hist(img) 63 cv.waitKey(0) 64 cv.destroyAllWindows() 65 66 main()