我正在尝试使用 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/