如何在纯 Python 中创建直方图?

How to create histograms in pure Python?

我知道您可以使用 numpy.histogram(),这将为相应的图像创建直方图。我不明白的是,如何在不使用该函数的情况下创建直方图。

每次我尝试使用示例代码时,它都有包问题,尤其是 OpenCV。

是否可以在不使用 OpenCV 或 skimage 的情况下创建直方图,也许使用 imageio 之类的东西?

如果您明确不想将 NumPy 作为某种导入,则需要使用列表、字典或任何其他标准 Python 数据结构来实现直方图计算。对于 image histograms,您基本上需要计算强度出现次数,大多数情况下这些值在 0 ... 255 范围内(处理 8 位图像时)。因此,迭代图像的所有通道,迭代该通道内的所有像素,并为该像素的观察强度值增加相应的“计数器”。

例如,这是一个解决方案:

import imageio

# Read image via imageio; get dimensions (width, height)
img = imageio.imread('path/to/your/image.png')
h, w = img.shape[:2]

# Dictionary (or any other data structure) to store histograms
hist = {
    'R': [0 for i in range(256)],
    'G': [0 for j in range(256)],
    'B': [0 for k in range(256)]
}

# Iterate every pixel and increment corresponding histogram element
for i, c in enumerate(['R', 'G', 'B']):
    for x in range(w):
        for y in range(h):
            hist[c][img[y, x, i]] += 1

我添加了一些 NumPy 代码来测试相等性:

import numpy as np

# Calculate histograms using NumPy
hist_np = {
    'R': list(np.histogram(img[:, :, 0], bins=range(257))[0]),
    'G': list(np.histogram(img[:, :, 1], bins=range(257))[0]),
    'B': list(np.histogram(img[:, :, 2], bins=range(257))[0])
}

# Comparisons
print(hist['R'] == hist_np['R'])
print(hist['G'] == hist_np['G'])
print(hist['B'] == hist_np['B'])

而实际上对应的输出是:

True
True
True
----------------------------------------
System information
----------------------------------------
Platform:      Windows-10-10.0.16299-SP0
Python:        3.9.1
imageio:       2.9.0
NumPy:         1.20.1
----------------------------------------