如何将Jupyter Notebook视频显示代码转为常规Python脚本?
替代
media.show_video的方案 针对将Colab Notebook中的视频显示功能迁移到普通Python脚本的需求,根据运行环境(本地有GUI/服务器无GUI),可以用以下几种方法实现:
1. 本地有GUI环境:实时显示视频
方法一:使用OpenCV(轻量高效)
OpenCV是计算机视觉常用库,适合快速显示视频:
import cv2 import numpy as np # 确认plot_video为uint8类型(若不是则转换) plot_video = plot_video.astype(np.uint8) fps = 3 # 计算每帧间隔(毫秒) frame_delay = int(1000 / fps) # 循环显示每一帧 for frame in plot_video: # OpenCV默认使用BGR格式,需转换RGB->BGR frame_bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) cv2.imshow('Generated Video', frame_bgr) # 按ESC键可提前退出 if cv2.waitKey(frame_delay) & 0xFF == 27: break # 关闭窗口释放资源 cv2.destroyAllWindows()
方法二:使用Matplotlib(贴合Notebook显示风格)
如果需要更接近Notebook中media.show_video的显示效果,可使用Matplotlib的动画模块:
import matplotlib.pyplot as plt import matplotlib.animation as animation # 确认plot_video为uint8类型 plot_video = plot_video.astype(np.uint8) fps = 3 fig, ax = plt.subplots() # 初始化显示第一帧 img = ax.imshow(plot_video[0]) ax.axis('off') # 隐藏坐标轴 # 更新帧的函数 def update_frame(frame): img.set_data(frame) return [img] # 创建动画并显示 ani = animation.FuncAnimation( fig, update_frame, frames=plot_video, interval=1000/fps, # 帧间隔(毫秒) blit=True ) plt.show()
2. 服务器无GUI环境:保存视频到文件
如果运行环境没有图形界面,无法实时显示,可将视频保存为MP4文件后续查看:
方法一:使用OpenCV保存
import cv2 import numpy as np plot_video = plot_video.astype(np.uint8) fps = 3 height, width = plot_video.shape[1], plot_video.shape[2] # 定义视频编码器和输出对象 fourcc = cv2.VideoWriter_fourcc(*'mp4v') video_writer = cv2.VideoWriter('output_video.mp4', fourcc, fps, (width, height)) # 逐帧写入视频 for frame in plot_video: frame_bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) video_writer.write(frame_bgr) # 释放资源 video_writer.release()
方法二:使用imageio保存(更简洁)
imageio库无需手动转换颜色格式,使用更方便:
import imageio plot_video = plot_video.astype(np.uint8) fps = 3 # 直接保存为MP4 imageio.mimsave('output_video.mp4', plot_video, fps=fps)
注意事项
- 确保
plot_video的 dtype 为uint8(值范围0-255),若为其他类型(如float32),需先转换:plot_video = (plot_video * 255).astype(np.uint8)(如果原数据是0-1的浮点型) - 服务器环境下,建议优先使用保存文件的方式,避免GUI相关报错
内容的提问来源于stack exchange,提问作者Georgia
相关产品推荐
相关产品推荐

