OpenCV-Day-017:图像直方图

代码

import cv2 as cv
import matplotlib.pyplot as plt
import numpy as np


# 自己编写程序实现灰度图像直方图的统计
def custom_hist(gray):
    h, w = gray.shape
    hist = np.zeros([256], dtype=np.int32)
    for row in range(h):
        for col in range(w):
            pv = gray[row, col]
            hist[pv] += 1
    y_pos = np.arange(0, 256, 1, dtype=np.int32)
    plt.bar(y_pos, hist, align='center', color='r', alpha=0.5)
    plt.xticks(y_pos, y_pos)
    plt.ylabel('Frequency')
    plt.title('Histogram')


# 调用函数cv.calcHist实现图像直方图的统计
def image_hist(image):
    cv.imshow('input', image)
    color = ('blue', 'green', 'red')
    for i, color in enumerate(color):
        hist = cv.calcHist([image], [i], None, [256], [0, 256])
        plt.plot(hist, color=color)
        plt.xlim([0, 256])


src = cv.imread('./erweima.png', cv.IMREAD_COLOR)
cv.namedWindow('input', cv.WINDOW_AUTOSIZE)
gray = cv.cvtColor(src, cv.COLOR_RGB2GRAY)
cv.imshow('input', gray)
custom_hist(gray)
image_hist(src)
plt.show()
cv.waitKey(0)
cv.destroyAllWindows()

实验效果

在这里插入图片描述

发布了197 篇原创文章 · 获赞 35 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/PoGeN1/article/details/91049921