Python - 计算图像的直方图

标签 python opencv numpy histogram

我正在自学计算机图像处理的基础知识,同时自学 Python。

给定尺寸为 2048x1354 且具有 3 个 channel 的图像 x,高效地计算像素强度的直方图。

import numpy as np, cv2 as cv

img = cv.imread("image.jpg")
bins = np.zeros(256, np.int32)

for i in range(0, img.shape[0]):
    for j in range(0, img.shape[1]):

        intensity = 0
        for k in range(0, len(img[i][j])):
            intensity += img[i][j][k]

        bins[intensity/3] += 1

print bins

我的问题是这段代码运行得非常慢,大约需要 30 秒。我怎样才能加快速度并变得更 Pythonic?

最佳答案

您可以使用较新的 OpenCV python 接口(interface),该接口(interface)本身使用 numpy 数组,并使用 matplotlib hist 绘制像素强度的直方图。在我的电脑上用时不到一秒钟。

import matplotlib.pyplot as plt
import cv2

im = cv2.imread('image.jpg')
# calculate mean value from RGB channels and flatten to 1D array
vals = im.mean(axis=2).flatten()
# plot histogram with 255 bins
b, bins, patches = plt.hist(vals, 255)
plt.xlim([0,255])
plt.show()

enter image description here

更新: 上面指定数量的 bin 并不总是提供所需的结果,因为最小值和最大值是根据实际值计算的。此外,值 254 和 255 的计数在最后一个 bin 中求和。这是更新的代码,它总是正确地绘制直方图,条形图以值 0..255 为中心

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

# read image
im = cv2.imread('image.jpg')
# calculate mean value from RGB channels and flatten to 1D array
vals = im.mean(axis=2).flatten()
# calculate histogram
counts, bins = np.histogram(vals, range(257))
# plot histogram centered on values 0..255
plt.bar(bins[:-1] - 0.5, counts, width=1, edgecolor='none')
plt.xlim([-0.5, 255.5])
plt.show()

enter image description here

关于Python - 计算图像的直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22159160/

相关文章:

图像减法的OpenCv问题?

python - Pandas:删除重复的日期但保留最后一个

opencv - 使用立体声SGBM的非常差的视差图

python - 从 OpenCV 到 PIL 的转换不准确

python - 常规与使用 For 循环时的 Numpy 数组乘法差异

numpy - ValueError 在 SciPy 中取两个稀疏矩阵的点积

python - 平均颜色有点错误。 (np.mean())

python - 如何从 python 中的 os.system 中删除 0 表单?

python - 使用 Python 多处理无法将 LDAP 对象共享给子进程

python - OpenGL - 从不同角度渲染同一场景,无需重绘所有内容