首页 > 解决方案 > 在python中绘制灰度图像直方图的问题

问题描述

我绘制了一个直方图

灰度图像的

使用 matplotlib。但是直方图看起来不像我想要的。

from matplotlib import pyplot as plt 
import numpy as np
from PIL import Image
im=Image.open("lena.pgm")
pxl=list(im.getdata())
print pxl
columnsize,rowsize=im.size

a = np.array(pxl)
plt.hist(a, bins = 255)
plt.title("histogram") 
plt.show()

我想要直方图

标签: imagepython-2.7matplotlibhistogramgrayscale

解决方案


直方图中的间隙是由于 bin 大小选择不当造成的。如果您调用hist(..., bins=255),numpy 将创建从数组的最小值到最大值的 256 个 bin。换句话说,垃圾箱将具有非整数宽度(在我的测试中:)[ 24. , 24.86666667, 25.73333333, 26.6 , ....]

因为您正在处理具有 255 个级别的图像,所以您应该创建 255 个宽度为 1 的 bin:

plt.hist(a, bins=range(256))

我们必须写256,因为我们需要包括 bin 的最右边,否则不会包括值为 255 的点。

至于颜色,请按照评论中链接的问题中的示例进行操作

from PIL import Image
im=Image.open("lena.pgm")
a = np.array(im.getdata())

fig, ax = plt.subplots(figsize=(10,4))
n,bins,patches = ax.hist(a, bins=range(256), edgecolor='none')
ax.set_title("histogram")
ax.set_xlim(0,255)


cm = plt.cm.get_cmap('cool')
norm = matplotlib.colors.Normalize(vmin=bins.min(), vmax=bins.max())
for b,p in zip(bins,patches):
    p.set_facecolor(cm(norm(b)))
plt.show()

在此处输入图像描述


推荐阅读