【问题标题】:Problem plotting a histogram of grayscale image in python在python中绘制灰度图像直方图的问题
【发布时间】:2019-06-01 06:07:00
【问题描述】:

我已经绘制了一个直方图

灰度图像

使用 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()

我想要这样的直方图

【问题讨论】:

  • 您到底在追求什么功能?箱子的数量?颜色?
  • @MadPhysicist 生成的直方图中有一个空白竖条。我不想要这个。并且竖条的颜色应该和上一张图一样
  • 查看这个 SO 答案,stackoverflow.com/a/23062183/4902099。基本上,您需要将一系列颜色映射到您的数据,以生成您想要的直方图。

标签: image python-2.7 matplotlib histogram grayscale


【解决方案1】:

直方图中的空白是由于 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 的点。

颜色参照问题linked in the comments中的例子

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()

【讨论】:

    【解决方案2】:

    您可以像这样使用plt.hist() 方法:

    import cv2
    import matplotlib.pyplot as plt
    
    img = cv2.imread('lena.png', 0)
    plt.hist(img.ravel(), 256, (0, 256))
    plt.show()
    

    输出:

    【讨论】:

      猜你喜欢
      • 2013-10-12
      • 1970-01-01
      • 1970-01-01
      • 2021-06-01
      • 1970-01-01
      • 2013-03-24
      • 2019-04-02
      • 1970-01-01
      • 2011-08-21
      相关资源
      最近更新 更多