開発環境
- macOS Mojave - Apple (OS)
- Emacs (Text Editor)
- Windows 10 Pro (OS)
- Visual Studio Code (Text Editor)
- Python 3.7 (プログラミング言語)
-
パッケージ
- NumPy
- scikit-image
- Matplotlib
- PIL(Python Image Library, Pillow)
エレガントなSciPy (Juan Nunez-Iglesias (著)、Stéfan van der Walt(著)、Harriet Dashnow(著)、山崎 邦子(翻訳)、山崎 康宏(翻訳)、オライリージャパン)の3章(ndimageを使った画像領域のネットワーク)、3.4(汎用フィルタ: 近傍データの任意の関数)、3.4.1(演習: Conwayのライフゲーム)の解答を求めてみる。
コード
Python 3
#!/usr/bin/env python3
import numpy as np
from scipy import ndimage
import matplotlib.pyplot as plt
from PIL import Image
import io
def conway_filter(cells):
cell = cells[len(cells) // 2]
neibors = np.sum(cells) - cell
if cell == 1:
if neibors <= 1:
return 0
elif 2 <= neibors <= 3:
return 1
else:
return 0
if cell == 0:
if neibors == 3:
return 1
else:
return 0
def next_generation(array: np.array) -> np.array:
return ndimage.generic_filter(array, conway_filter, size=3)
if __name__ == '__main__':
for i in range(3):
print(f'conway_{i}.gif')
array = np.random.randint(2, size=(100, 100))
plt.imsave(f'conway_{i}.png', array)
n = 3 * 60 * 2
buffers = [io.BytesIO() for _ in range(n)]
for j in range(n):
array = next_generation(array)
plt.imsave(buffers[j], array)
im = Image.open(f'conway_{i}.png')
im.save(f'conway_{i}.gif', save_all=True,
append_images=[Image.open(buffers[i]) for i in range(n)],
duration=500)
入出力結果(cmd(コマンドプロンプト)、Terminal、Jupyter(IPython))
$ python3 sample2.py conway_0.gif conway_1.gif conway_2.gif $






0 コメント:
コメントを投稿