Fast IFS using RPN notation
python
c
x86-64
nasm
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

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