(编辑:jimmy 日期: 2024/12/31 浏览:2)
本文主要介绍了Opencv图片生成视频,分享给大家,具体如下:
生成视频
import random as rd import cv2 as cv import numpy as np # 保存视频 class RecordMovie(object): def __init__(self, img_width, img_height): self.video_writer = None # 视频对象 self.is_end = False # 结束保存视频 self.img_width = img_width # 宽度 self.img_height = img_height # 高度 # 创建 视频写入对象 def start(self, file_name, freq): # 创建视频格式 four_cc = cv.VideoWriter_fourcc(*'mp4v') img_size = (self.img_width, self.img_height) # 视频尺寸 # 创建视频写入对象 self.video_writer = cv.VideoWriter() self.video_writer.open(file_name, four_cc, freq, img_size, True) # 写入图片帧 def record(self, img): if self.is_end is False: self.video_writer.write(img) # 完成视频 释放资源 def end(self): self.is_end = True self.video_writer.release() def move_image(img_src): img_height, img_width = img_src.shape[:2] # 随机 xy平移方向与大小设置 x_size = rd.randint(-3, 3) y_size = rd.randint(-3, 3) # 自定义转换矩阵 transform_matrix = np.float32([[1, 0, x_size], [0, 1, y_size]]) # 执行平移 return cv.warpAffine(img_src, transform_matrix, (img_width, img_height)) def main(): # 1.读取图片 img_org = cv.imread("img.png", cv.IMREAD_GRAYSCALE) # 2.显示图片 cv.imshow("org", img_org) cv.namedWindow("shift") # 3.视频文件生成 height, width = img_org.shape[:2] print(height, width) rm = RecordMovie(width, height) # 设置视频文件名称 频率 rm.start("test.mp4", 20) # 4.图片写入视频 for i in range(300): # 图片微调调整 img_move = move_image(img_org) img_move = cv.cvtColor(img_move, cv.COLOR_GRAY2RGB) rm.record(img_move) cv.imshow("shift", img_move) key = cv.waitKey(10) if key == 27: # esc 按键 break # 5.关闭视频文件 rm.end() if __name__ == '__main__': main()