使用opencv 实现图片序列化为视频写入到视频文件中(时序化RGB数据写入为mp4视频文件)——强化学习——使用opencv 记录gym中的mujoco运动视频

使用DeepSeek 生成:



import cv2
import numpy as np

# 初始化视频写入器
fourcc = cv2.VideoWriter_fourcc(*'mp4v')  # 编码器类型
fps = 30                                # 帧率 (需与实际帧率匹配)
width, height = 640, 480                # 视频分辨率
video_path = 'output_video.mp4'         # 输出路径

# 创建 VideoWriter 对象
video = cv2.VideoWriter(
    filename=video_path,
    fourcc=fourcc,
    fps=fps,
    frameSize=(width, height),
    isColor=True  # 彩色视频
)

# 检查是否初始化成功
if not video.isOpened():
    raise RuntimeError("无法创建视频文件,请检查参数或路径权限")

# 模拟生成图像帧(实际应从环境获取)
for _ in range(300):  # 生成 300 帧(10秒@30fps)
    # 创建随机 RGB 图像 (演示用)
    frame = np.random.randint(0, 256, (height, width, 3), dtype=np.uint8)
    
    # 如果从 Gymnasium 获取帧(需要颜色空间转换):
    # frame = cv2.cvtColor(env.render(), cv2.COLOR_RGB2BGR)
    
    # 写入帧
    video.write(frame)

# 释放资源
video.release()
print(f"视频已保存至 {video_path}")


运行后的效果:

image

image



提高篇:

使用opencv 记录gym中的mujoco运动视频:


代码:

import cv2
import numpy as np

# 初始化视频写入器
fourcc = cv2.VideoWriter_fourcc(*'mp4v')  # 编码器类型
fps = 30                                # 帧率 (需与实际帧率匹配)
width, height = 480, 480                # 视频分辨率
video_path = 'output_video.mp4'         # 输出路径

# 创建 VideoWriter 对象
video = cv2.VideoWriter(
    filename=video_path,
    fourcc=fourcc,
    fps=fps,
    frameSize=(width, height),
    isColor=True  # 彩色视频
)

# 检查是否初始化成功
if not video.isOpened():
    raise RuntimeError("无法创建视频文件,请检查参数或路径权限")

"""
# 模拟生成图像帧(实际应从环境获取)
for _ in range(300):  # 生成 300 帧(10秒@30fps)
    # 创建随机 RGB 图像 (演示用)
    frame = np.random.randint(0, 256, (height, width, 3), dtype=np.uint8)
    
    # 如果从 Gymnasium 获取帧(需要颜色空间转换):
    # frame = cv2.cvtColor(env.render(), cv2.COLOR_RGB2BGR)
    
    # 写入帧
    video.write(frame)
"""

import gymnasium as gym

env = gym.make("HalfCheetah-v5", render_mode="rgb_array")
obs, info = env.reset()

for _ in range(1000):
    action = env.action_space.sample()
    obs, reward, terminated, truncated, info = env.step(action)

    frame = env.render()  # 返回 RGB 数组
    print(frame.shape, frame.dtype)
    frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)  # 转换颜色空间

    video.write(frame)

    if terminated or truncated:
        obs, info = env.reset()

env.close()


# 释放资源
video.release()
print(f"视频已保存至 {video_path}")

运行效果:

image


image


image



posted on 2025-03-25 21:48  Angry_Panda  阅读(152)  评论(0)    收藏  举报

导航