turing.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #!/usr/bin/env python
  2. '''
  3. Multiscale Turing Patterns generator
  4. ====================================
  5. Inspired by http://www.jonathanmccabe.com/Cyclic_Symmetric_Multi-Scale_Turing_Patterns.pdf
  6. '''
  7. # Python 2/3 compatibility
  8. from __future__ import print_function
  9. import sys
  10. PY3 = sys.version_info[0] == 3
  11. if PY3:
  12. xrange = range
  13. import numpy as np
  14. import cv2 as cv
  15. from common import draw_str
  16. import getopt, sys
  17. from itertools import count
  18. help_message = '''
  19. USAGE: turing.py [-o <output.avi>]
  20. Press ESC to stop.
  21. '''
  22. def main():
  23. print(help_message)
  24. w, h = 512, 512
  25. args, _args_list = getopt.getopt(sys.argv[1:], 'o:', [])
  26. args = dict(args)
  27. out = None
  28. if '-o' in args:
  29. fn = args['-o']
  30. out = cv.VideoWriter(args['-o'], cv.VideoWriter_fourcc(*'DIB '), 30.0, (w, h), False)
  31. print('writing %s ...' % fn)
  32. a = np.zeros((h, w), np.float32)
  33. cv.randu(a, np.array([0]), np.array([1]))
  34. def process_scale(a_lods, lod):
  35. d = a_lods[lod] - cv.pyrUp(a_lods[lod+1])
  36. for _i in xrange(lod):
  37. d = cv.pyrUp(d)
  38. v = cv.GaussianBlur(d*d, (3, 3), 0)
  39. return np.sign(d), v
  40. scale_num = 6
  41. for frame_i in count():
  42. a_lods = [a]
  43. for i in xrange(scale_num):
  44. a_lods.append(cv.pyrDown(a_lods[-1]))
  45. ms, vs = [], []
  46. for i in xrange(1, scale_num):
  47. m, v = process_scale(a_lods, i)
  48. ms.append(m)
  49. vs.append(v)
  50. mi = np.argmin(vs, 0)
  51. a += np.choose(mi, ms) * 0.025
  52. a = (a-a.min()) / a.ptp()
  53. if out:
  54. out.write(a)
  55. vis = a.copy()
  56. draw_str(vis, (20, 20), 'frame %d' % frame_i)
  57. cv.imshow('a', vis)
  58. if cv.waitKey(5) == 27:
  59. break
  60. print('Done')
  61. if __name__ == '__main__':
  62. print(__doc__)
  63. main()
  64. cv.destroyAllWindows()