如何使用python绘制每个波段的直方图,但不使用cv2.calcHist()或np.histogram()之类的预定义函数

时间:2019-03-28 03:37:01

标签: python-3.x opencv image-processing

我必须在python中绘制直方图,而无需使用cv2.calcHist()或np.histogram()之类的预定义函数。我已将所有图像像素读入矢量,但是需要如何编写直方图函数的帮助?

2 个答案:

答案 0 :(得分:0)

import numpy as np
import cv2

data = [1, 5, 3, 9 ,4] # fill in your data

size = 200, 300, 3
hist = np.zeros(size, dtype=np.uint8) + 255

interval = hist.shape[1] / (len(data) + 1)
width = interval * 0.7
max_height = hist.shape[0] * 0.9
max_data = max(data)

interval_count = 1
for value in data:
    height = max_height / max_data * value
    pt1 = (int(interval_count * interval - width / 2), int(hist.shape[0] - height))
    pt2 = (int(interval_count * interval + width / 2), int(hist.shape[0]))
    cv2.rectangle(hist, pt1, pt2, (255, 0, 0), -1)
    interval_count += 1

cv2.imwrite("hist.jpg", hist)

enter image description here

答案 1 :(得分:0)

以下是示例:

def cal_hist(gray_img):
    hist = np.zeros(shape=(256))
    (h,w) = gray_img.shape
    for i in range(w):
        for j in range(h):
            hist[gray_img[j,i]] += 1
    return hist

img = cv2.imread("1.jpg",0)

plt.plot(cal_hist(img))
plt.show()

enter image description here