Python:numpy.histogram plot

时间:2018-02-20 08:04:32

标签: python numpy plot histogram

我想测量16位图像中的像素强度。因此,我做了一个numpy直方图,显示了从0到65535(16位)的灰度值的像素数。我用

做到了
hist= numpy.histogram(grayscaleimage.ravel(), 65536, [0, 65536])

之后我测量了我的图像的整体强度(这意味着总和:像素数*每个像素值):

Intensity = 0
for i in range(len(hist[0])):
    Intensity += hist[0][i]*hist[1][i]
print(Intesity)

现在我想看直方图。虽然我有我需要的值,但我不知道如何绘制hist。有人可以帮我这个吗?

1 个答案:

答案 0 :(得分:1)

您可以直接使用matplotlib

import matplotlib.pyplot as plt
plt.hist(grayscaleimage.ravel(), bins=np.linspace(0, 65536, 1000))
plt.show()   

或者像你已经做的那样使用numpy并绘制条形图。但是,您必须自己正确设置条的宽度,并跳过最后一个bin条目,使其与直方图具有相同的尺寸:

import numpy as np
import matplotlib.pyplot as plt

hist, bin_edges = np.histogram(grayscaleimage.ravel(), bins = np.linspace(0, 65536, 1000))
plt.bar(bin_edges[:-1], hist, width=65536./1000)
plt.show()

我这里只使用了1000个垃圾箱,但您也可以选择更多,具体取决于您的图像尺寸。

PS:如果你想要总强度,你不必迭代所有的箱子。只需总结图像np.sum(grayscaleimage)中的所有像素值,即可获得更准确的结果。

相关问题