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()
使用cv2和matplotlib做视频
于 2024-01-13 22:49:45 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)