图像处理之图像直方图

    技术2024-05-22  72

    直方图绘制

    目的:直方图是对图像像素的统计分布,它统计了每个像素(0到255)的数量。
    函数:cv2.calcHist(images, channels, mask, histSize, ranges)
    参数说明:参数1:待统计图像,需用中括号括起来; 参数2:待计算的通道; 参数3:Mask,这里没有使用,所以用None。 参数4:histSize,表示直方图分成多少份; 参数5:是表示直方图中各个像素的值,[0.0, 256.0]表 示直方图能表示像素值从0.0到256的像素。直方图是 对图像像素的统计分布,它统计了每个像素(0到255) 的数量。

    Python代码实现

    直方图绘制 方法1
    from matplotlib import pyplot as plt import cv2 girl = cv2.imread("girl.jpg") cv2.imshow("girl", girl) # girl.ravel()函数是将图像的三位数组降到一维上去, #256为bins的数目,[0, 256]为范围 plt.hist(girl.ravel(), 256, [0, 256]) plt.show() cv2.waitKey(0) cv2.destroyAllWindows()
    效果展示:
    直方图绘制 方法2
    from matplotlib import pyplot as plt import cv2 import numpy as np img = cv2.imread('girl.jpg') img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) plt.imshow(img_gray, cmap=plt.cm.gray) hist = cv2.calcHist([img], [0], None, [256], [0, 256]) plt.figure() plt.title("Grayscale Histogram") plt.xlabel("Bins") plt.ylabel("# of Pixels") plt.plot(hist) plt.xlim([0, 256]) plt.show()
    效果展示:

    三通道直方图绘制

    Python代码
    from matplotlib import pyplot as plt import cv2 girl = cv2.imread("girl.jpg") cv2.imshow("girl", girl) color = ("b", "g", "r") #使用for循环遍历color列表,enumerate枚举返回索引和值 for i, color in enumerate(color): hist = cv2.calcHist([girl], [i], None, [256], [0, 256]) plt.title("girl") plt.xlabel("Bins") plt.ylabel("num of perlex") plt.plot(hist, color = color) plt.xlim([0, 260]) plt.show() cv2.waitKey(0) cv2.destroyAllWindows()
    效果展示:
    Processed: 0.015, SQL: 9