使用cv2和matplotlib做视频

本文介绍了一个名为MakeVidio的类,它使用OpenCV和matplotlib库创建视频,并演示如何从文件、Numpy数组和Matplotlib图表中添加帧。示例代码展示了如何生成一个动态散点图并将之插入视频中。
摘要由CSDN通过智能技术生成
import cv2
import numpy as np
import matplotlib.pyplot as plt
import PIL.Image as Image
from matplotlib.backends.backend_agg import FigureCanvasAgg


class MakeVidio:
    def __init__(self, video_path, fps, h, w):
        self.fps = fps
        self.h = h
        self.w = w
        self.size = (w, h)
        fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
        self.video = cv2.VideoWriter(video_path, fourcc, fps, self.size, isColor=True)

    def add_img_from_file(self, file_path):
        image = cv2.imdecode(np.fromfile(file_path, dtype=np.uint8), -1)
        self.add_img_from_np(image)
        return

    def add_img_from_np(self, image_np):
        image_np = cv2.resize(image_np, self.size)
        self.video.write(image_np)  # 将图像写入视频
        return

    def add_img_from_plt(self, plt_fig):
        img_bgr = MakeVidio.pltfig2np(plt_fig)
        self.add_img_from_np(img_bgr)
        return

    def release_video(self):
        self.video.release()
        return

    @staticmethod
    def pltfig2np(fig):
        canvas = FigureCanvasAgg(fig)
        canvas.draw()
        w, h = canvas.get_width_height()
        buf = np.frombuffer(canvas.tostring_argb(), dtype=np.uint8)
        buf.shape = (w, h, 4)
        # 转换为 RGBA
        buf = np.roll(buf, 3, axis=2)
        # 得到 Image RGBA图像对象 (需要Image对象的同学到此为止就可以了)
        image = Image.frombytes("RGBA", (w, h), buf.tobytes())
        # 转换为numpy array rgba四通道数组
        image = np.asarray(image)
        rgb_image = image[:, :, :3]
        r, g, b = cv2.split(rgb_image)
        img_bgr = cv2.merge([b, g, r])
        return img_bgr


if __name__ == '__main__':
    mkvideo = MakeVidio("your_video_name.mp4", 6, 800, 800)
    x = np.arange(0, 10, 1)
    y = np.random.normal(0, 1, 10)
    fig = plt.figure(figsize=(10, 10), dpi=80)
    axs = fig.subplots(nrows=1, ncols=1)
    axs.set_ylim(0, 120)
    axs.set_xlim(0, 120)
    for ii in range(120): 
        print(ii)
        x = np.array([ii])
        y = x
        axs.scatter(x, y, color = 'r')
        mkvideo.add_img_from_plt(fig)
    plt.close(fig)
    plt.clf()
    mkvideo.release_video()

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值