Cellular Automata: game of life

Cellular automata is an automaton composed of cells, cell states, and state update rules. The most famous cellular automaton is the game of life proposed by the British mathematician John in 1970. Its rules are as follows:

  • When the surrounding cells are 0 or 1, its state becomes dead;
  • When there are 2 surviving cells, keep it as it is;
  • When there are 3 surviving cells around, its state becomes alive;
  • When there are 4 surviving cells around, its state becomes dead.

A simple example:

In the cell shown in the figure below, the color of each cell indicates a different state (yellow is alive, the others are dead).
Insert picture description here
After an iteration, it becomes (this is a standardized QR code, you can trace it to see what it is):
Insert picture description here

The above procedure is as follows:

import cv2
img = cv2.imread("/home/toby/Pictures/gol.png",cv2.IMREAD_GRAYSCALE)
ret,thresh1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
rimg = cv2.resize(thresh1, (27,27))

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

nimg = np.array(rimg/255)

def round_sum(i,j):
    start_i = max(0, i-1)
    end_i = min(27, i+2)
    start_j = max(0, j-1)
    end_j = min(27, j+2)
    s = np.sum(nimg[start_i:end_i,start_j:end_j]) - nimg[i,j]
    return s

plt.imshow(nimg)
plt.show()
temp_nimg = np.zeros((27,27))
for i in range(27):
    for j in range(27):
        s = round_sum(i,j)
        if s >= 4:
            temp_nimg[i,j] = 0
        if s == 3:
            temp_nimg[i,j] = 1
        if s == 2:
            temp_nimg[i,j] = nimg[i,j]
        if s < 2:
            temp_nimg[i,j] = 0
plt.imshow(temp_nimg)
plt.show()

Guess you like

Origin blog.csdn.net/u013468614/article/details/104118486