Guest User

Untitled

a guest
May 24th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. from __future__ import print_function
  4. import os
  5. import sys
  6. import numpy as np
  7. from scipy import signal
  8. import cv2
  9.  
  10. mask = np.ones((3, 3), dtype=int)
  11.  
  12. def init_state(width, height, init_alive_prob=0.5):
  13. N = width*height
  14. v = np.array(np.random.rand(N) + init_alive_prob, dtype=int)
  15. return v.reshape(height, width)
  16.  
  17. def count_neighbor(F):
  18. return signal.correlate2d(F, mask, mode="same", boundary="wrap")
  19.  
  20. def next_generation(F):
  21. N = count_neighbor(F)
  22. G = (N == 3) + F*(N == 4)
  23. return G
  24.  
  25. def print_for_gnuplot(F):
  26. np.savetxt(sys.stdout, F, fmt="%d")
  27. print()
  28. print()
  29.  
  30. def to_image(F, scale=3.0):
  31. img = np.array(F, dtype=np.uint8)*180 + 20
  32. W = int(F.shape[1]*scale)
  33. H = int(F.shape[0]*scale)
  34. img = cv2.resize(img, (W, H), interpolation=cv2.INTER_NEAREST)
  35. return img
  36.  
  37. def main():
  38. p = 0.08
  39. F = init_state(100, 100, init_alive_prob=p)
  40. ret = 0
  41. wait = 10
  42. while True:
  43. img = to_image(F, scale=5.0)
  44. cv2.imshow("test", img)
  45. ret = cv2.waitKey(wait)
  46. F = next_generation(F)
  47. if ret == ord('r'):
  48. F = init_state(100, 100, init_alive_prob=p)
  49. if ret == ord('s'):
  50. wait = min(wait*2, 1000)
  51. if ret == ord('f'):
  52. wait = max(wait//2, 10)
  53. if ret == ord('q') or ret == 27:
  54. break
  55. if ret == ord('w'):
  56. np.savetxt("save.txt", F, "%d")
  57. if ret == ord('l'):
  58. if os.path.exists("save.txt"):
  59. F = np.loadtxt("save.txt")
  60.  
  61. cv2.destroyAllWindows()
  62.  
  63.  
  64. if __name__ == "__main__":
  65. main()
Add Comment
Please, Sign In to add comment