【问题标题】:bins must increase monotonically垃圾箱必须单调增加
【发布时间】:2017-10-25 07:01:39
【问题描述】:

我只想从 skimage.exposure 中绘制 Matplotlib 直方图,但我得到了 ValueError: bins must increase monotonically. 原始图像来自 here,这里是我的代码:

from skimage import io, exposure
import matplotlib.pyplot as plt

img = io.imread('img/coins_black_small.jpg', as_grey=True)
hist,bins=exposure.histogram(img)

plt.hist(bins,hist)

ValueError: bins 必须单调增加。

但是当我对 bin 值进行排序时会出现同样的错误:

import numpy as np
sorted_bins = np.sort(bins)
plt.hist(sorted_bins,hist)

ValueError: bins 必须单调增加。

我终于尝试检查 bin 值,但在我看来它们似乎已排序(对于此类测试的任何建议也将不胜感激):

if any(bins[:-1] >= bins[1:]):
    print "bim"

没有输出。

有什么建议吗?
我正在努力学习 Python,所以请放纵一下。这是我的安装(在 Linux Mint 上):

  • Python 2.7.13 :: Anaconda 4.3.1(64 位)
  • Jupyter 4.2.1

【问题讨论】:

  • 当数组中有 NaN 时,我经常看到这种情况。 any(np.isnan(img)) 返回什么?
  • @bnaecker > ValueError:具有多个元素的数组的真值不明确。使用 a.any() 或 a.all()

标签: python matplotlib scikit-image


【解决方案1】:

Matplotlib hist 接受数据作为第一个参数,尚未分类计数。使用 matplotlib bar 绘制它。请注意,与 numpy histogram 不同,skimage exposure.histogram 返回 bin 的中心。

width = bins[1] - bins[0]
plt.bar(bins, hist, align='center', width=width)
plt.show()

【讨论】:

    【解决方案2】:

    正确的解决方法是:

    所有 bin 值必须是整数,不能是小数!您可以使用 round() 功能。

    【讨论】:

      【解决方案3】:

      plt.hist 的签名是plt.hist(data, bins, ...)。因此,您试图将已计算的直方图作为 bin 插入 matplotlib hist 函数。直方图当然没有排序,因此“箱必须单调增加” - 错误被抛出。

      虽然您当然可以使用plt.hist(hist, bins),但对直方图进行直方图绘制是否有用仍值得怀疑。我猜你想简单地绘制第一个直方图的结果。

      为此目的使用条形图是有意义的:

      hist,bins=numpy.histogram(img)
      plt.bar(bins[:-1], hist, width=(bins[-1]-bins[-2]), align="edge")
      

      【讨论】:

      • 该死的,确实。并感谢您对 plt.histplt.bar 的使用的评论。
      • 但是你确定plt.bar(bins[:-1],...) 吗? (它在 > 不兼容的尺寸上返回错误:参数“高度”必须是长度 255 或标量)不应该是 plt.bar(bins,...) 吗?
      • 你当然可以试一试。我敢肯定,如果您使用hist, bins = numpy.histogram,则需要使用plt.bar(bins[:-1],...),因为bins 表示边缘,因此比hist 大一。现在,我不知道skimage.exposure.histogram 是否与此不同。当您收到错误时,似乎是这样。我更新了使用 numpy 的答案。
      猜你喜欢
      • 1970-01-01
      • 2016-05-22
      • 2019-09-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-02
      • 1970-01-01
      • 1970-01-01
      • 2019-03-15
      相关资源
      最近更新 更多