【问题标题】:only size-1 arrays can be converted to Python scalars只有 size-1 的数组可以转换为 Python 标量
【发布时间】:2019-03-20 19:43:14
【问题描述】:

我正在尝试练习python图像像素颜色直方图

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


img = cv2.imread('image.jpg')


gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)


hist = cv2.calcHist([gray], [0], None, [256], [0, 256])


plt.bar(range(1,257), hist)
plt.show()

它给出了一个错误

Traceback (most recent call last):
  File "C:/Users/jmu/Desktop/123.py", line 15, in <module>
    plt.bar(range(1,257), hist)
  File "C:\Users\jmu\AppData\Local\Programs\Python\Python37-32\lib\site-packages\matplotlib\pyplot.py", line 2457, in bar
    **({"data": data} if data is not None else {}), **kwargs)
  File "C:\Users\jmu\AppData\Local\Programs\Python\Python37-32\lib\site-packages\matplotlib\__init__.py", line 1810, in inner
    return func(ax, *args, **kwargs)
  File "C:\Users\jmu\AppData\Local\Programs\Python\Python37-32\lib\site-packages\matplotlib\axes\_axes.py", line 2296, in bar
    label='_nolegend_',
  File "C:\Users\jmu\AppData\Local\Programs\Python\Python37-32\lib\site-packages\matplotlib\patches.py", line 658, in __init__
    Patch.__init__(self, **kwargs)
  File "C:\Users\jmu\AppData\Local\Programs\Python\Python37-32\lib\site-packages\matplotlib\patches.py", line 87, in __init__
    self.set_linewidth(linewidth)
  File "C:\Users\jmu\AppData\Local\Programs\Python\Python37-32\lib\site-packages\matplotlib\patches.py", line 348, in set_linewidth
    self._linewidth = float(w)
TypeError: only size-1 arrays can be converted to Python scalars

我该如何解决它

【问题讨论】:

    标签: python python-3.x numpy matplotlib opencv3.0


    【解决方案1】:
    plt.bar(range(1,257), hist.reshape(256))
    

    或者如果你想避免硬编码数字

    plt.bar(range(len(hist)), hist.reshape(-1))
    

    bar的签名是

    matplotlib.pyplot.bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs)

    height : scalar or sequence of scalars

    https://matplotlib.org/api/_as_gen/matplotlib.pyplot.bar.html

    所以将你的身高重新塑造成一个序列。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 2021-12-24
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 2020-11-03
      • 1970-01-01
      相关资源
      最近更新 更多