python - 值错误: operands could not be broadcast together with shapes (10) (11)

标签 python image python-imaging-library

我正在尝试使用 Dejan Noveski 的代码使用 PIL 模块创建一个在 python 中计算图像熵的函数。

def image_entropy(img):
hgram = np.histogram(img)
histogram_length = sum(hgram)

samples_probability = [float(h) / histogram_length for h in hgram]

return -sum([p * math.log(p, 2) for p in samples_probability if p != 0])

它抛出以下错误

 File "test.py", line 45, in <module>
I_e=image_entropy(I)
File "test.py", line 11, in image_entropy
histogram_length = sum(hgram)
File "/usr/lib/python2.7/dist-packages/numpy/core/fromnumeric.py", line 1510, in sum
out=out, keepdims=keepdims)
File "/usr/lib/python2.7/dist-packages/numpy/core/_methods.py", line 18, in _sum
out=out, keepdims=keepdims)
ValueError: operands could not be broadcast together with shapes (10) (11) 

我不明白为什么它给出广播错误,因为我没有采取任何产品,只是采取矩阵的总和。有人可以帮我吗?

提前谢谢

最佳答案

numpy.histogram返回一个 2 元组:直方图和 bin 边缘数组。所以

hgram = np.histogram(img)

应该是

hgram, bin_edges = np.histogram(img)

如果您使用hgram = np.histogram(img),则hgram将被分配给2元组。 Python 很乐意这样做;那里没有引发异常。但是,当 Python 计算 sum(hist) 时,它会尝试对 hist 中的两项求和。一个(直方图值)是一个长度为 10 的数组,另一个(bin 边缘)是一个长度为 11 的数组。这就是 ValueError 发生的地方。

<小时/>

np.histogram(img) 期望 img 是一个数组。如果 img 是 PIL 图像,则使用 im.histogram method

hgram = img.histogram()

关于python - 值错误: operands could not be broadcast together with shapes (10) (11),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21355119/

相关文章:

python PIL 保存图像不同大小的原始图像

python + Nose : make assertions about logged text?

python - 如何将redis管道用于嵌套方法

python - 刷新 matplotlib 中的所有当前图形

python - 同时运行多个 python 文件并在一个完成时终止所有文件

android - 将图像存储在 android 的内部存储器中

python - 在 Python 中显示图像大小的正确方法是什么?

image - IE9 - 11 SVG 背景模糊

python - 在 Image 模块 Python 中淡出

python - 如何使用 Python PIL 设置 TIFF 图像分辨率