如果您明确不希望将 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
----------------------------------------