【问题标题】:How to create histograms in pure Python?如何在纯 Python 中创建直方图?
【发布时间】:2021-05-15 18:12:43
【问题描述】:

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

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

有没有在不使用 OpenCV 或 skimage 的情况下创建直方图,也许使用类似 imageio 的东西?

【问题讨论】:

  • 欢迎您!我首先推荐taking the tour。您可能想重新表述一下您的问题。目前尚不清楚“在不使用它的情况下创建它”是什么意思。 (您的意思是不使用图像,而是使用不同的数据源?)其他人无法猜测您使用 opencv 遇到了什么问题。您应该发布一个最小的尝试示例,并清楚地说明您希望代码如何工作以及它的实际行为方式(实际问题是什么)。您是否尝试过使用 Python OpenCV / numpy histograms 的现有指南?这里有几个例子......

标签: numpy opencv image-processing histogram python-imageio


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2017-07-27
    • 2012-03-30
    • 2011-06-21
    • 2018-04-16
    相关资源
    最近更新 更多