Python – Save videos instead of images when using Basler cameras and python

Save videos instead of images when using Basler cameras and python… here is a solution to the problem.

Save videos instead of images when using Basler cameras and python

I’m recording some videos using Basler camera and python. I can successfully capture a single frame, but I don’t know how to record video.

Here is my code:

import os
import pypylon
from imageio import imwrite
import 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])['AcquisitionFrameRateEnable'] = True['AcquisitionFrameRate'] = 1000['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


I haven’t found a way to record video with pypylon; It appears to be a very light wrapper for Pylon. However, I found a way to save videos using imageio :

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

The above can be .mov, .avi, .mpg, .mpeg, .mp4, .mkv or .wmv, as long as there is an FFmpeg program. How you will install this program depends on your operating system. Check out this link for details on the parameters you can use .

Then, simply replace the call to imwrite with:


Make sure this happens in a with block.

Example implementation:

import os
import pypylon
from imageio import get_writer

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

time_exposure = 1000000 / fsamp

available_cameras = pypylon.factory.find_devices()
cam = pypylon.factory.create_device(available_cameras[0])['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:
del buffer

Related Problems and Solutions