Skip to content

Instantly share code, notes, and snippets.

@mathigatti
Created June 7, 2019 16:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mathigatti/439a0e81556f2698c7db4f41189d201f to your computer and use it in GitHub Desktop.
Save mathigatti/439a0e81556f2698c7db4f41189d201f to your computer and use it in GitHub Desktop.
Convert an input number into a pattern (The number is interpreted as the rules for a 2D Grid Cellular automata with Von Neumann neighbourhood)
import numpy as np
import cv2
ON = 255
OFF = 0
N = 200
def rule(neighbours,rules):
if neighbours in rules:
return ON
else:
return OFF
def update(grid,rules):
newGrid = grid.copy()
for i in range(1,N-1):
for j in range(1,N-1):
newGrid[i,j] = rule((grid[i-1,j],grid[i,j+1],grid[i+1,j],grid[i,j-1]),rules)
return newGrid
def toTupla(n):
neighbours = []
n = "{0:b}".format(n).zfill(4)
for c in n:
if c == "0":
neighbours.append(OFF)
else:
neighbours.append(ON)
return tuple(neighbours)
def toNumber(tupla):
n = ''
for t in tupla:
if t == ON:
n += "1"
else:
n += "0"
return int(n,2)
def generate(n):
tuplas = []
i = 0
for c in n[::-1]:
if c == "1":
tuplas.append(toTupla(i))
i+=1
return tuplas
def numberToAutomata(number, steps):
grid = np.random.choice([ON, OFF], N*N, p=[0.5, 0.5]).reshape(N, N)
index = "{0:b}".format(number).zfill(256)
rules = generate(index)
for step_index in range(steps):
grid = update(grid,rules)
cv2.imwrite('images/'+str(number)+'.jpg', grid)
cv2.imwrite('images/'+str(number)+'.tiff', grid)
cv2.imwrite('images/'+str(number)+'.png', grid)
import sys
# Usage example
# python number2pattern.py 108780 30
numberToAutomata(int(sys.argv[1]),int(sys.argv[2]))
@mathigatti
Copy link
Author

mathigatti commented Jun 7, 2019

Pattern for number 108780 with 30 iterations
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment