m_amber
m_amber

Reputation: 757

ValueError: operands could not be broadcast together with shapes (10) (11)

I m trying to make a function for calculating entropy of an image in python using the PIL module using Dejan Noveski's code.

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

It throws the following error

 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) 

I dont understand why its giving broadcast error, because i m not taking any product for that matter, just taking the sum of the matrix. Can somebody help me out.

Thank you in advance

Upvotes: 1

Views: 4412

Answers (1)

unutbu
unutbu

Reputation: 879481

numpy.histogram returns a 2-tuple: the histogram and an array of the bin edges. So

hgram = np.histogram(img)

should be

hgram, bin_edges = np.histogram(img)

If you use hgram = np.histogram(img) then hgram gets assigned to the 2-tuple. Python is quite happy to do that; there is no Exception raised there. But when Python evaluates sum(hist) it tries to sum the two items in hist. One (the histogram values) is an array of length 10, and the other (the bin edges) is an array of length 11. And that is where the ValueError occurs.


np.histogram(img) expects img to be an array. If img is a PIL image, then use the im.histogram method

hgram = img.histogram()

Upvotes: 3

Related Questions