In [1]:
# 定義一個動畫的函數
from IPython.display import display
from ipywidgets import Image as Image_widget
import time
from io import BytesIO
import numpy as np
from PIL import Image
def anim(func, time_length, interval=0.1, width=400):
img = Image_widget(width=width)
display(img)
start_time = time.time()
for t in np.arange(0, time_length, interval):
frame = Image.fromarray((func(t)*255).astype('uint8'))
img.value = frame._repr_png_()
now = time.time()
if now < start_time+t:
time.sleep(start_time+t-now)
In [2]:
# 試試看
from math import pi, sin
def moving_cross(t):
a = np.zeros((400,400,3))
x = int(t*200)%400
y = int(200-150*sin(2*x*pi/400))
a[y,:]=[0,1,0]
a[:, x]=[1,0,0]
a[:, 399-x]=[0,0,1]
a[399-y, :]=[1,0,1]
return a
anim(moving_cross, time_length=20)
In [4]:
from math import pi, sin
a = np.zeros((1080,1920,3))
i_ = np.arange(1,64)
c = np.random.uniform(size=(63,3))
def color_arrows(t):
t_ = (i_*7.15+t)
x1 = (t_/3%1*1920).astype(np.int32)
y1 = (np.sin(t_)*500+500).astype(np.int32)
for i in range(63):
a[y1[i]:y1[i]+80, x1[i]:x1[i]+80] = c[i]
return a
anim(color_arrows, time_length=1, interval=1/60, width=600)
自行創作,可以參考 https://www.dwitter.net/