Images to video

Description

Create a video image sequences.

Added in version 2.7.0.

Parameters

  • images: str, list[list[str]] or dict[str, str]

    Defines the image sequences and the arrangement.

    • "pressure_<instant>.png" — a single sequence.

    • [["pressure_<instant>.png", "density_<instant>.jpg"], ["u_<instant>.png", "v_<instant>.jpg"]] — a grid. The outer list holds rows, the inner lists hold columns; all rows must have the same length.

    • {"p": "pressure_<instant>.png", "u": "u_<instant>.png"} — named panes, positioned by layout. Keys are compared as strings, so 1 and "1" are equivalent.

    If the sequences do not all contain the same number of frames, the video is as long as the longest sequence and shorter sequences are padded with black frames. A warning is logged when this happens.

    Every pattern must contain the tag "<instant>" exactly once, standing for the frame number: see the Patterns section below.

  • output: str

    Output video filename. The extension should be consistent with encoding (see the table below).

  • layout: str, default= None

    Required when images is a dictionary, forbidden otherwise (the layout of a single image or of a grid is already fully determined). Expression describing how the panes are arranged, built from the keys of images and three operators:

    • "|" — place side by side (horizontal split);

    • "/" — stack (vertical split);

    • "(...)" — grouping.

    "|" binds tighter than "/", so "1|2/3" means "(1|2)/3". Use parentheses to override, e.g. "1/(2|3)" puts pane 1 on top and panes 2 and 3 side by side underneath.

    Pane names are arbitrary strings, not just digits: with images={"p": "pressure_<instant>.png", "v": "velocity_<instant>.png"}, the layout "p/v" stacks the pressure panel above the velocity one. Longer names work the same way, e.g. "p_x/(p_y|p_z)". Three constraints apply to the names:

    • they must not contain "(", ")", "|" or "/", which are always read as syntax;

    • they must not contain whitespace: spaces are allowed around the operators, as in "p / (u | v)", but a name split by a space such as "my pane/other" raises a ValueError;

    • names are compared as strings, so 1 and "1" refer to the same pane.

    Each pane must appear exactly once, and the set of leaves in layout must match the set of keys in images exactly; otherwise a ValueError is raised, listing the names found on only one side.

  • fit: str or dict[str, str], default= "pad"

    How each image is fitted into its pane. Either a single value applied to every pane, or a mapping from pane name to value (panes not listed fall back to "pad"). Accepted values:

    • "pad" — preserve the aspect ratio and fill the remaining space with pad_color;

    • "crop" — preserve the aspect ratio and crop the overflow, centred;

    • "stretch" — resize to the pane, ignoring the aspect ratio.

    Images already at the size of their pane are written untouched, so the default only matters for sequences whose images differ in size or in aspect ratio from the first one.

  • pad_color: color or dict[str, color], default= (0, 0, 0)

    Only used by panes whose fit is "pad". Either a single color or a per-pane mapping. A color is an RGB tuple with components in 0-255, or any name/hex string understood by matplotlib ("white", "#204a87"). Requires matplotlib when a string is given.

  • start_idx: int, default= 0

    Index of the first frame to include when loading images from patterns. This index refers to the position in the list of matched images sorted by instant, not to the instant itself. For example, if the files are ["image_00.png", "image_05.png", "image_10.png"], then start_idx=1 selects "image_05.png".

  • end_idx: int, default= None

    Index past the last frame to include, i.e. the sequence is sliced as images[start_idx:end_idx], following the usual Python convention. Also refers to the position in the sorted list of matched images. If None, all images matched by the pattern are used.

  • duration: float, default= None

    Duration of the output video in seconds. If specified, the frame rate is computed automatically. If duration is not None, frame_rate must be None.

  • frame_rate: float, default= None

    Frame rate (frames per second) for the output video. If specified, the duration is inferred from the total number of frames. If frame_rate is not None, duration must be None.

  • encoding: str, default= "avc1"

    Video encoding (FourCC) used by OpenCV. See the table below.

  • progress_bar: bool, default= False

    Display a progress bar while frames are written.

  • progress_bar_label: str, default= "Making video"

    Label shown next to the progress bar.

Preconditions

  • Exactly one of duration or frame_rate must be provided. If both or neither are set, the treatment raises a ValueError.

  • layout must be given if and only if images is a dictionary.

Postconditions

  • A video file is written at output, with one frame per index of the longest input sequence.

  • The pane grid is sized from the first image of the first pane — the only pane for a single sequence, the top-left one for a grid, the leftmost leaf of the tree for an explicit layout. Every pane is that size, so a grid of M×N sequences produces a video of N × width by M × height.

  • Images are fitted into their pane according to fit, so the frame size is constant for the whole video whatever the size of the individual images.

  • Frames that cannot be read, and frames missing from a short sequence, are written as black rectangles.

Patterns

A pattern is a file path in which the tag <instant> marks the frame number, for instance pressure_<instant>.png, <instant>_pressure.png or run_3/slice_<instant>.jpg. The tag is mandatory and must appear exactly once; it makes the frame number explicit instead of guessing which number in a filename is the index.

Files are collected by replacing the tag with * and globbing, then ordered by the integer read at the tag position. The number may be zero-padded or not, so p_0002.png and p_2.png are read as instant 2. Ordinary glob wildcards (*, ?, [...]) may still be used elsewhere in the pattern, but they never provide the ordering.

The following raise a ValueError:

  • a pattern without the tag, or with more than one;

  • a file matched by the pattern that has no number at the tag position, e.g. pressure_final.png matched by pressure_<instant>.png;

  • two files resolving to the same instant, which would make the order of that frame ambiguous.

Video Encodings

The following table lists common video encodings (FourCC codes) supported by OpenCV.

Encoding

Description

Recommended Container

Notes

avc1

H.264 codec (standard tag)

.mp4

Recommended default. Plays everywhere: browsers, players, mobile, slide decks. Requires an OpenCV build with H.264 support.

mp4v

MPEG-4 Part 2 codec

.mp4

Available in every OpenCV build, but will not play in any web browser and embeds poorly. Fine for local viewing in VLC/QuickTime.

X264

H.264 codec (x264 encoder)

.mp4, .mkv

Equivalent to avc1; FFmpeg remaps the tag and prints a notice. Prefer avc1 to avoid the noise.

H264

H.264 codec (alt tag)

.mkv, .mp4

Same codec, non-standard tag for MP4. Prefer avc1.

MJPG

Motion JPEG codec

.avi

Every frame independently JPEG- compressed. Very large files, but fast to write and frame-accurate to seek. Useful for analysis, not for distribution.

XVID

Xvid MPEG-4 codec

.avi

Legacy. Desktop players only; not web-compatible.

DIVX

DivX MPEG-4 codec

.avi

Legacy. Same caveats as XVID.

Note that OpenCV silently produces an empty file when the codec and the container are incompatible; this treatment detects that case and raises a RuntimeError instead.

Example 1: Single pane video

The following example shows how to make a video from a single series of images

import os
import antares

DATA_FOLDER = os.path.join("..", "data", "FWH", "Monopole")
OUTPUT_FOLDER = os.path.join("OUTPUT", "ImagesToVideo")

os.makedirs(OUTPUT_FOLDER, exist_ok=True)

base = antares.io.Read(
    filename = os.path.join(DATA_FOLDER, 'monopole_<instant>.plt'),
    format = 'bin_tp',
)

# Make the individual figures
antares.treatment.PlotBases(
    bases = [base],
    color_by = 'pressure',
    colorbar_title = 'Pressure [Pa]',
    show = False,
    output_file = os.path.join(OUTPUT_FOLDER, 'fwh_{figindex}.jpeg'),
)

# Make a video out of the individual images
antares.treatment.ImagesToVideo(
    images = os.path.join(OUTPUT_FOLDER, 'fwh_<instant>.jpeg'),
    output = os.path.join(OUTPUT_FOLDER, 'video.mp4'),
    duration = 10,
    progress_bar=True,
)

Example 2: Grid layout video

The following example shows how to make a video from 4 series of images arranged in a 2x2 grid

import antares
import os

output_folder = os.path.join('.', 'OUTPUT', 'imagestovideo')
os.makedirs(output_folder, exist_ok=True)

# Read base
filename =  os.path.join('..', 'data', 'FWH', 'Monopole', 'monopole_<instant>.plt')
base = antares.io.Read(filename=filename, format='bin_tp')

# Helper function to quickly to plot a base
def quickplotbases(base, variable, title, outputfile):
    antares.treatment.PlotBases(
        bases = base,
        color_by=variable,
        colorbar_title=title,
        colorbar_nb_labels=4,
        colorbar_labelformat="%.2f",
        camera_direction=[-1, -1, 1],
        show = False,
        output_file=os.path.join(output_folder, outputfile),
        progress_bar=True,
        progress_bar_label=f'Plotting {variable}',
        figsize=[800, 600],
    )


# Make the individual images of pressure, density and velocity components
quickplotbases(base, 'pressure', r'$p$ $\left[Pa\right]$', 'pressure_{figindex}.jpeg')
quickplotbases(base, 'rho', r'$\rho$ $\left[kg \cdot s^{{-1}}\right]$', 'rho_{figindex}.jpeg')
quickplotbases(base, 'u', r'$u$ $\left[m \cdot s^{{-1}}\right]$', 'u_{figindex}.jpeg')
quickplotbases(base, 'v', r'$v$ $\left[m \cdot s^{{-1}}\right]$', 'v_{figindex}.jpeg')

rho_images = os.path.join(output_folder, 'rho_<instant>.jpeg')
pressure_images = os.path.join(output_folder, 'pressure_<instant>.jpeg')
u_images = os.path.join(output_folder, 'u_<instant>.jpeg')
v_images = os.path.join(output_folder, 'v_<instant>.jpeg')

# Create a 2x2 grid 10 seconds video:
#
# |  density     pressure  |
# |     u            v     |
antares.treatment.ImagesToVideo(
    images = [[rho_images, pressure_images],
              [u_images, v_images]],
    duration=10,
    progress_bar=True,
    encoding='avc1',
    output=os.path.join(output_folder, 'video_grid.mp4'),
)

Example 3: Custom layout video

The following example shows how to make a video from 3 series of images arranged in a custom layout with a single image on top and 2 images at the bottom.

import antares
import os

output_folder = os.path.join('.', 'OUTPUT', 'imagestovideo')
os.makedirs(output_folder, exist_ok=True)

# Read base
filename =  os.path.join('..', 'data', 'FWH', 'Monopole', 'monopole_<instant>.plt')
base = antares.io.Read(filename=filename, format='bin_tp')

# Helper function to quickly to plot a base
def quickplotbases(base, variable, title, outputfile):
    antares.treatment.PlotBases(
        bases = base,
        color_by=variable,
        colorbar_title=title,
        colorbar_nb_labels=4,
        colorbar_labelformat="%.2f",
        camera_direction=[-1, -1, 1],
        show = False,
        output_file=os.path.join(output_folder, outputfile),
        progress_bar=True,
        progress_bar_label=f'Plotting {variable}',
        figsize=[800, 600],
    )

# Make the individual images for pressure, and velocity components
quickplotbases(base, 'pressure', r'$p$ $\left[Pa\right]$', 'pressure_{figindex}.jpeg')
quickplotbases(base, 'u', r'$u$ $\left[m \cdot s^{{-1}}\right]$', 'u_{figindex}.jpeg')
quickplotbases(base, 'v', r'$v$ $\left[m \cdot s^{{-1}}\right]$', 'v_{figindex}.jpeg')

pressure_images = os.path.join(output_folder, 'pressure_<instant>.jpeg')
u_images = os.path.join(output_folder, 'u_<instant>.jpeg')
v_images = os.path.join(output_folder, 'v_<instant>.jpeg')

# Create a video with the following layout
# |        pressure        |
# |     u            v     |
antares.treatment.ImagesToVideo(
    images = {'p': pressure_images, 'u': u_images, 'v': v_images},
    layout='p/(u|v)', # Custom layout with pressure on top and velocity components at the bottom
    fit = {'p': 'pad', 'u': 'stretch', 'v': 'stretch'}, # Different fit per pane
    pad_color={'p': 'white'}, # pad the pressure image with a white background. Otherwise we will see a black one around the image
    duration=10,
    progress_bar=True,
    encoding='avc1',
    output=os.path.join(output_folder, 'video_multipane.mp4'),
)