-1
from numpy import * 
from pylab import * 
from scipy import * 
from scipy.signal import * 
from scipy.stats import * 


testimg = imread('path')  

hist = hist(testimg.flatten(), 256, range=[0.0,1.0])[0]
hist = hist + 0.000001
prob = hist/sum(hist)


entropia = -1.0*sum(prob*log(prob))#here is error
print 'Entropia: ', entropia

I have this code and I do not know what could be the problem, thanks for any help

gabra
  • 9,484
  • 4
  • 29
  • 45
Maciej
  • 47
  • 1
  • 9

1 Answers1

4

This is an example of why you should never use from module import *. You lose sight of where functions come from. When you use multiple from module import * calls, one module's namespace may clobber another module's namespace. Indeed, based on the error message, that appears to be what is happening here.

Notice that when log refers to numpy.log, then -1.0*sum(prob*np.log(prob)) can be computed without error:

In [43]: -1.0*sum(prob*np.log(prob))
Out[43]: 4.4058820963782122

but when log refers to math.log, then a TypeError is raised:

In [44]: -1.0*sum(prob*math.log(prob))
TypeError: only length-1 arrays can be converted to Python scalars

The fix is to use explicit module imports and explicit references to functions from the module's namespace:

import numpy as np
import matplotlib.pyplot as plt

testimg = np.random.random((10,10))

hist = plt.hist(testimg.flatten(), 256, range=[0.0,1.0])[0]
hist = hist + 0.000001
prob = hist/sum(hist)

# entropia = -1.0*sum(prob*np.log(prob))
entropia = -1.0*(prob*np.log(prob)).sum()
print 'Entropia: ', entropia
# prints something like:  Entropia:  4.33996609845

The code you posted does not produce the error, but somewhere in your actual code log must be getting bound to math.log instead of numpy.log. Using import module and referencing functions with module.function will help you avoid this kind of error in the future.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677