使用basler相机和python时保存视频而不是保存图像

2024-04-07

我正在使用 Basler 相机和 python 来录制一些视频。我可以成功捕获单个帧,但我不知道如何录制视频。

以下是我的代码:

import os
import pypylon
from imageio import imwrite
import time
start=time.time()

print('Sampling rate (Hz):')
fsamp = input()
fsamp = float(fsamp)

time_exposure = 1000000*(1/fsamp)

available_cameras = pypylon.factory.find_devices()
cam = pypylon.factory.create_device(available_cameras[0])
cam.open()

#cam.properties['AcquisitionFrameRateEnable'] = True
#cam.properties['AcquisitionFrameRate'] = 1000
cam.properties['ExposureTime'] = time_exposure

buffer = tuple(cam.grab_images(2000))
for count, image in enumerate(buffer):
    filename = str('I:/Example/{}.png'.format(count))
    imwrite(filename, image)
del buffer

我还没有找到使用录制视频的方法pypylon;它似乎是 Pylon 周围的一个非常轻的包装。但是,我找到了一种使用保存视频的方法imageio:

from imageio import get_writer
with get_writer('I:/output-filename.mp4', fps=fps) as writer:
    # Some stuff with the frames

以上可以与.mov, .avi, .mpg, .mpeg, .mp4, .mkv or .wmv,只要 FFmpeg 程序可用。如何安装该程序取决于您的操作系统。请参阅此链接有关您可以使用的参数的详细信息 https://imageio.readthedocs.io/en/stable/format_ffmpeg.html#parameters-for-saving.

然后,只需将调用替换为imwrite with:

writer.append_data(image)

确保这发生在with block.

一个示例实现:

import os
import pypylon
from imageio import get_writer

while True:
    try:
        fsamp = float(input('Sampling rate (Hz): '))
        break
    except ValueError:
        print('Invalid input.')

time_exposure = 1000000 / fsamp

available_cameras = pypylon.factory.find_devices()
cam = pypylon.factory.create_device(available_cameras[0])
cam.open()

cam.properties['ExposureTime'] = time_exposure

buffer = tuple(cam.grab_images(2000))
with get_writer(
       'I:/output-filename.mkv',  # mkv players often support H.264
        fps=fsamp,  # FPS is in units Hz; should be real-time.
        codec='libx264',  # When used properly, this is basically
                          # "PNG for video" (i.e. lossless)
        quality=None,  # disables variable compression
        pixelformat='rgb24',  # keep it as RGB colours
        ffmpeg_params=[  # compatibility with older library versions
            '-preset',  # set to faster, veryfast, superfast, ultrafast
            'fast',     # for higher speed but worse compression
            '-crf',  # quality; set to 0 for lossless, but keep in mind
            '11'     # that the camera probably adds static anyway
        ]
) as writer:
    for image in buffer:
        writer.append_data(image)
del buffer
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用basler相机和python时保存视频而不是保存图像 的相关文章

随机推荐