I've been addicted to taichi since yesterday, so I'll try to use it in various ways and share information as needed. This time, I will show you how to output the created graphic as mp4 or gif. See the official Documents for more information. The first article about taichi is here.
Taichi uses ffmpeg when outputting videos, so if you haven't installed it, please install it.
$ sudo apt update
$ sudo apt -y upgrade
$ sudo apt install ffmpeg
This time, I will try to output the execution result of fractal.py in the examples of the repository as a video. I'm adding the block under Add Comment Out to the default code.
fractal.py
import taichi as ti
ti.init(arch=ti.gpu)
n = 320
pixels = ti.field(dtype=float, shape=(n * 2, n))
@ti.func
def complex_sqr(z):
return ti.Vector([z[0]**2 - z[1]**2, z[1] * z[0] * 2])
@ti.kernel
def paint(t: float):
for i, j in pixels: # Parallized over all pixels
c = ti.Vector([-0.8, ti.cos(t) * 0.2])
z = ti.Vector([i / n - 1, j / n - 0.5]) * 2
iterations = 0
while z.norm() < 20 and iterations < 50:
z = complex_sqr(z) + c
iterations += 1
pixels[i, j] = 1 - iterations * 0.02
gui = ti.GUI("Julia Set", res=(n * 2, n))
#Add ↓
result_dir = "./results"
video_manager = ti.VideoManager(output_dir=result_dir, framerate=24, automatic_build=False)
for i in range(100):
paint(i * 0.03)
# gui.set_image(pixels)
# gui.show()
#Add ↓
pixels_img = pixels.to_numpy()
video_manager.write_frame(pixels_img)
print(f'\rFrame {i+1}/100 is recorded', end='')
#Add ↓
video_manager.make_video(gif=True, mp4=True)
print(f'MP4 video is saved to {video_manager.get_output_filename(".mp4")}')
print(f'GIF video is saved to {video_manager.get_output_filename(".gif")}')
By default, gui is displayed, but this time, instead of the gui display process in the for statement, we will use VideoManager to make the frame a video. Running the above program will create mp4 and gif files under the results folder. The gif looks like this.
I don't know what taichi can be used for, but it's interesting so I'll explore it (laughs).
Recommended Posts