advent-of-code/2022/python/anim.py

41 lines
1.3 KiB
Python
Raw Normal View History

2022-12-09 22:08:53 +00:00
from matrix import get_size, pmx
import imageio
import matplotlib.pyplot as plt
import numpy as np
class Animate:
def __init__(self, mx, day="CHANGEME"):
2022-12-09 23:03:06 +00:00
self.mx = mx
self.day = day
2022-12-09 22:08:53 +00:00
_size = get_size(mx)
self.height = _size[0]
self.width = _size[1]
2022-12-09 23:03:06 +00:00
self.f_count = -1
2022-12-09 22:08:53 +00:00
def add_frame(self, frame):
2022-12-09 23:03:06 +00:00
self.f_count += 1
self.write_frame(frame)
2022-12-09 22:08:53 +00:00
2022-12-09 23:03:06 +00:00
def write_frame(self, frame):
current = np.zeros_like(self.mx)
for y, row in enumerate(frame):
for x, col in enumerate(row):
current[y][x] = frame[y][x]
fig, ax = plt.subplots()
ax.imshow(current, cmap=plt.cm.gray)
ax.axis("off")
_figpath = (f"gif-{self.day}/{self.f_count:05}.png")
plt.savefig(_figpath)
plt.close()
2022-12-09 22:08:53 +00:00
2022-12-09 23:03:06 +00:00
def animate(self, frameskip=1):
with imageio.get_writer(f"gif-{self.day}/day{self.day}.gif", mode="I") as writer:
names = [f"gif-{self.day}/{x:05}.png" for x in range(0,self.f_count, frameskip)]
print(names)
2022-12-09 22:08:53 +00:00
for filename in names:
try:
image = imageio.imread(filename)
writer.append_data(image)
except FileNotFoundError:
pass