Genetic Turmit Evolver
python
c
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

fractdim.py 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import sys
  2. import numpy as np
  3. import scipy
  4. import scipy.misc
  5. def rgb2gray(rgb):
  6. r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2]
  7. gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
  8. return gray
  9. def fractal_dimension(Z, threshold=None):
  10. ''' @return Minkowski–Bouligand dimension (computed) '''
  11. # Only for 2d image
  12. assert(len(Z.shape) == 2)
  13. # From https://github.com/rougier/numpy-100 (#87)
  14. def boxcount(Z, k):
  15. S = np.add.reduceat(
  16. np.add.reduceat(Z, np.arange(0, Z.shape[0], k), axis=0),
  17. np.arange(0, Z.shape[1], k), axis=1)
  18. # We count non-empty (0) and non-full boxes (k*k)
  19. return len(np.where((S > 0) & (S < k*k))[0])
  20. if threshold is None:
  21. threshold = np.mean(Z)
  22. if threshold < 0.2:
  23. threshold = 0.2
  24. # Transform Z into a binary array
  25. Z = (Z < threshold)
  26. # Minimal dimension of image
  27. p = min(Z.shape)
  28. # Greatest power of 2 less than or equal to p
  29. n = 2**np.floor(np.log(p)/np.log(2))
  30. # Extract the exponent
  31. n = int(np.log(n)/np.log(2))
  32. # Build successive box sizes (from 2**n down to 2**1)
  33. sizes = 2**np.arange(n, 1, -1)
  34. # Actual box counting with decreasing size
  35. counts = []
  36. for size in sizes:
  37. counts.append(boxcount(Z, size))
  38. # Fit the successive log(sizes) with log (counts)
  39. coeffs = np.polyfit(np.log(sizes), np.log(counts), 1)
  40. return -coeffs[0]
  41. if __name__ == '__main__':
  42. I = rgb2gray(scipy.misc.imread(sys.argv[1]))
  43. print(I)
  44. print("%f:%s" % (fractal_dimension(I), sys.argv[1]))