当前位置:首页>python>LabVIEW+Python 视频合成方法|opencv or ffmpeg

LabVIEW+Python 视频合成方法|opencv or ffmpeg

  • 2026-10-11 08:37:06
LabVIEW+Python 视频合成方法|opencv or ffmpeg
我们都知道视频合成最常用的就是FFmpeg和Opencv了(Labview自带的不太好用)  。今天就给大家分享两种最实用的 Python 视频合成方法
导航目录:测试 & 自动化 & LabVIEW&C#&Python 实战干货合集(持续更新)

一、从本地文件夹加载图片合成视频

1.FFmpeg指令实现

ffmpeg指令如下: 从D:\Frame 文件夹下加载数字序号名称的图片 合成视频 帧率:15 视频编码:yuv20p 视频路径:d:\video\1.mp4

ffmpeg -framerate 15 -i D:\Frame\%d.jpg -s 1280x720 -c:v libx264 -r 15 -pix_fmt yuv420p d:Video\1.mp4

Labview里直接使用System Exec执行即可。

2.Opencv实现 

import cv2import osdef local_images_to_video(    img_dir: str,        # 图片保存的本地文件夹路径    save_path: str,      # 合成视频的保存路径(如:./output.mp4)    fps: int = 15,       # 合成视频帧率(    img_suffix: tuple = ('.jpg', '.png')  # 图片格式):    # 1. 读取本地文件夹内所有图片,按数字顺序排序    img_list = [f for f in os.listdir(img_dir) if f.endswith(img_suffix)]    # 按文件名数字排序,避免画面乱序(关键:适配1.png、2.png...命名)    img_list.sort(key=lambda x: int(os.path.splitext(x)[0]))    if not img_list:        raise FileNotFoundError(f"本地文件夹{img_dir}内未找到{img_suffix}格式图片")    # 2. 读取第一张图片,获取图像尺寸    first_img_path = os.path.join(img_dir, img_list[0])    first_img = cv2.imread(first_img_path)    if first_img is None:        raise ValueError(f"第一张图片{first_img_path}读取失败,请检查图片完整性")    height, width = first_img.shape[:2]    # 3. 初始化视频写入器(MP4格式,兼容所有播放器,避免无法打开)    fourcc = cv2.VideoWriter_fourcc(*'mp4v')    video_writer = cv2.VideoWriter(save_path, fourcc, fps, (width, height))    # 4. 批量加载本地图片,逐帧写入视频    try:        for img_name in img_list:            img_path = os.path.join(img_dir, img_name)            # 读取图片(确保图片已保存完整,避免LabVIEW未写完就读取)            frame = cv2.imread(img_path)            if frame is None:                print(f"图片{img_name}读取失败,跳过该帧")                continue            # 写入视频帧            video_writer.write(frame)        print(f"本地图片合成视频完成,保存路径:{save_path}")    finally:        # 关键:无论是否报错,都释放资源,避免视频损坏(工业级必加)        video_writer.release()if __name__ == "__main__":    labview_local_synth(        img_dir="./labview_imgs",  # LabVIEW图片输出文件夹        save_path="local_output.mp4"  # 合成视频保存路径    )

二、Python实时采集存储视频

Opencv进行实时的图像采集 并保存为视频。

import cv2# 打开本地摄像头cap = cv2.VideoCapture(0)# 获取摄像头实际分辨率width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))fps = 20# 视频编码格式与保存对象fourcc = cv2.VideoWriter_fourcc('m','p','4','v')writer = cv2.VideoWriter("record.mp4", fourcc, fps, (width, height))print("开始录制,按 q 结束录制")whileTrue:    ret, frame = cap.read()    ifnot ret:        break    # 写入视频流    writer.write(frame)    cv2.imshow("live", frame)    # 按下q退出    if cv2.waitKey(1) & 0xFF == ord("q"):        break# 释放资源cap.release()writer.release()cv2.destroyAllWindows()print("录制完成,文件已保存")

三、Labview采集图像Python合成视频

Labview Vision 自带的视频存储只支持avi格式,保存时间较长的视频会特别的大。我们可以采集一段时间后使用ffmpeg指令进行合成。也可以开启采集后调用Python的Opencv方法进行合成。 下面的Python方法可以直接被laview调用,开启采集后调用会监测文件夹图片进行合成。

import cv2import osimport timedef realtime_image_to_video(    img_dir: str,    save_path: str,    expected_fps: int = 15,    check_interval: float = 0.2,    speed_ratio: float = 1,    # 合成速度更慢    idle_stop_sec: float = 2.0   # 2秒没新图 → 自动停止):    processed = set()    fps_delay = 1.0 / expected_fps / speed_ratio      last_file_time = time.time()    # 等待第一张图片    while not os.listdir(img_dir):        time.sleep(0.1)    # 获取尺寸    first_img = None    while first_img is None:        for f in os.listdir(img_dir):            if f.endswith(('jpg', 'png')):                first_img = cv2.imread(os.path.join(img_dir, f))                break        time.sleep(0.1)    h, w = first_img.shape[:2]    fourcc = cv2.VideoWriter_fourcc(*'mp4v')    out = cv2.VideoWriter(save_path, fourcc, expected_fps, (w, h))    print("开始实时合成视频...")    try:        while True:            files = sorted([f for f in os.listdir(img_dir) if f.endswith(('jpg', 'png'))])            has_new = False            for f in files:                if f in processed:                    continue                img_path = os.path.join(img_dir, f)                frame = cv2.imread(img_path)                if frame is None:                    continue                out.write(frame)                processed.add(f)                has_new = True                last_file_time = time.time()                time.sleep(fps_delay)            # 超时判断:多久没新图就结束            if time.time() - last_file_time > idle_stop_sec:                print(f"{idle_stop_sec}秒无新图片,自动结束合成")                break            time.sleep(check_interval)    finally:        out.release()        print(f"视频已保存: {save_path}")#realtime_image_to_video(r'D:/WorkSpace/Video/Frame',r'D:/WorkSpace/Video/1.mp4')

四、总结

以上就是ffmpeg和Opencv视频合成的方法了。 对于Labview采集图像,Opencv合成视频也可以将Labview的Vision数据转Opencv的Mat格式进行视频合成,

 后续会给大家介绍不同图像格式(picture,vision,mat,bitmap)的数据转换。

✨ 感谢点赞收藏评论的每个小伙伴,持续分享Python/C#/Labview / 测试 / 自动化/机械手/视觉定位/PLC实战干货,每周更新,欢迎关注!

最新文章

随机文章