OpenCV__Python直方图比较_教程14

#引入opencv模块
import cv2 as cv
#引入numpy模块
import numpy as np
#引入sys模块
import sys


#创建RGB直方图
def create_rgb_hist(img):
    h,w,c = img.shape
    rgbHist = np.zeros([16*16*16,1],np.float32)
    bsize = 256/16
    for row in range(h):
        for col in range(w):
            b = img[row,col,0]
            g = img[row,col,1]
            r = img[row,col,2]
            index = np.int(b/bsize)*16*16 + np.int(g/bsize)*16 + np.int(r/bsize)
            rgbHist[np.int(index),0] = rgbHist[np.int(index),0]+1
    return rgbHist


#直方图比较
def hist_compare(img1,img2):
    hist1 = create_rgb_hist(img1)
    hist2 = create_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 img_test():
    img1 = cv.imread('E:/chenopencvblogimg/lena150W200H.jpg')
    img2 = cv.imread('E:/chenopencvblogimg/chen150W200H.bmp')     
    #判断是否读取成功
    if img1 is None or img2 is None:
        print("Could not read the image,may be path error")
        return
    cv.namedWindow("origin Pic1",cv.WINDOW_NORMAL)
    cv.imshow("origin Pic1",img1)
    cv.namedWindow("origin Pic2",cv.WINDOW_NORMAL)
    cv.imshow("origin Pic2",img2)    
    hist_compare(img1,img2)

    #让显示等待键盘输入维持在那里,否则程序跑完就闪退啦!
    cv.waitKey(0)
    #销毁窗口
    cv.destroyAllWindows()

if __name__ == '__main__':
    sys.exit(img_test() or 0)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值