entropy.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. from numpy import unique
  2. from scipy.stats import entropy as scipy_entropy
  3. def shannon_entropy(image, base=2):
  4. """Calculate the Shannon entropy of an image.
  5. The Shannon entropy is defined as S = -sum(pk * log(pk)),
  6. where pk are frequency/probability of pixels of value k.
  7. Parameters
  8. ----------
  9. image : (M, N) ndarray
  10. Grayscale input image.
  11. base : float, optional
  12. The logarithmic base to use.
  13. Returns
  14. -------
  15. entropy : float
  16. Notes
  17. -----
  18. The returned value is measured in bits or shannon (Sh) for base=2, natural
  19. unit (nat) for base=np.e and hartley (Hart) for base=10.
  20. References
  21. ----------
  22. .. [1] `https://en.wikipedia.org/wiki/Entropy_(information_theory) <https://en.wikipedia.org/wiki/Entropy_(information_theory)>`_
  23. .. [2] https://en.wiktionary.org/wiki/Shannon_entropy
  24. Examples
  25. --------
  26. >>> from skimage import data
  27. >>> from skimage.measure import shannon_entropy
  28. >>> shannon_entropy(data.camera())
  29. 7.231695011055706
  30. """
  31. _, counts = unique(image, return_counts=True)
  32. return scipy_entropy(counts, base=base)