美文网首页
50. 彩色直方图源码

50. 彩色直方图源码

作者: 十里江城 | 来源:发表于2019-11-13 08:52 被阅读0次

    彩色直方图绘制步骤:

    • 读取图片信息
    • 各通道值计数与归一化
    • 设置横纵坐标
    • 绘制蓝绿红直方图
    • 显示所有直方图
    import cv2
    import numpy as np
    import matplotlib.pyplot as plt
    
    # 1 读取图片信息
    img = cv2.imread('2.jpg', 1)
    imgInfo = img.shape
    height = imgInfo[0]
    width = imgInfo[1]
    
    # 2 各通道值计数
    count_b = np.zeros(256, np.float)
    count_g = np.zeros(256, np.float)
    count_r = np.zeros(256, np.float)
    for i in range(0, height):
        for j in range(0, width):
            (b, g, r) = img[i, j]
            index_b = int(b)
            index_g = int(g)
            index_r = int(r)
            count_b[index_b] =  count_b[index_b] + 1
            count_g[index_g] =  count_g[index_g] + 1
            count_r[index_r] =  count_r[index_r] + 1
    
    # 分别进行归一化处理
    for i in range(0, 255):
        count_b[i] = count_b[i] / (height * width)
        count_g[i] = count_g[i] / (height * width)
        count_r[i] = count_r[i] / (height * width)
        
    # 3 设置横纵坐标    
    x = np.linspace(0, 255, 256)
    y1 = count_b
    y2 = count_g
    y3 = count_r
    
    # 4 绘制蓝绿红直方图
    # 绘制蓝色直方图
    # 创建画板
    plt.figure()
    plt.bar(x, y1, 0.9, alpha = 1, color = 'b')
    
    # 绘制绿色直方图
    plt.figure()
    plt.bar(x, y2, 0.9, alpha = 1, color = 'g')
    
    # 绘制红色直方图
    plt.figure()
    plt.bar(x, y3, 0.9, alpha = 1, color = 'r')
    
    # 5 显示所有直方图
    plt.show()
    cv2.waitKey(0)
    
    

    彩色直方图结果如下:


    image.png

    相关文章

      网友评论

          本文标题:50. 彩色直方图源码

          本文链接:https://www.haomeiwen.com/subject/zixcictx.html