0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

MuJoCoシミュレーションをGIFアニメーション出力する

0
Posted at

MuJoCoシミュレーション結果をGIF出力するPythonスクリプト例

ヒューマノイドロボット花盛り.
動かしてみたい.でも,いきなりモデルを1から作るのは大変です.
まずは,MuJoCoのサンプルファイルを見てみましょう.
そして,その結果をGIFアニメーションファイルとして出力して
今後,自分が実施したいことの構想を練りましょう.

MuJoCoをインストールすると,Modelフォルダにたくさんのサンプルがあります.
そのシミュレーション結果をGIFファイルとしてアニメーション生成するスクリプト例を下記に示します.

<出力されたGIFアニメーション>
simulation.gif

rcreate_gif.py
import mujoco
from PIL import Image

# 1. モデルとデータの読み込み(例: xmlファイルを指定)
model = mujoco.MjModel.from_xml_path("/mujoco/model/humanoid/humanoid.xml")
data = mujoco.MjData(model)

# 2. レンダラーの初期化(幅と高さを指定可能)
width, height = 640, 480
frames = []

# シミュレーション時間やフレームレートの設定
fps = 24
duration_sec = 3.0  # 記録するシミュレーション時間(秒)
interval = 1.0 / fps

with mujoco.Renderer(model, height, width) as renderer:
    mujoco.mj_resetData(model, data)
    
    while data.time < duration_sec:
        mujoco.mj_step(model, data)
        
        # 指定したフレームレートのタイミングで画面をキャプチャして保存
        if len(frames) < data.time * fps:
            renderer.update_scene(data) # 必要に応じて camera="fixed" などを指定
            pixels = renderer.render()   # RGBのNumPy配列を取得 (height, width, 3)
            
            # NumPy配列をPillowの画像オブジェクトに変換してリストに追加
            frames.append(Image.fromarray(pixels))

# 3. リストに入れた画像をGIFとして保存
output_filename = "simulation.gif"
if frames:
    frames[0].save(
        output_filename,
        save_all=True,
        append_images=frames[1:],
        duration=int(1000 / fps), # 各フレームの表示時間(ミリ秒)
        loop=0                    # 0で無限ループ
    )
    print(f"GIF saved as {output_filename}")
else:
    print("No frames captured.")
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?