Skip to contents

Sample a video into a numbered image sequence. Sample at a fixed rate (fps) or at a fixed interval (interval, seconds between frames). This is the first step for per-frame coding and for computer-vision feature pipelines. Provide exactly one of fps or interval.

Usage

sample_frames(
  infile,
  outdir,
  fps = NULL,
  interval = NULL,
  format = "png",
  prefix = NULL,
  run = TRUE
)

Arguments

infile

A string containing the path to a video file.

outdir

A string naming the directory to write the image sequence to. The function creates it (recursively) if it does not exist.

fps

The sampling rate, in frames per second: either a positive number or an FFmpeg framerate expression string (for example "30000/1001"). Provide exactly one of fps or interval.

interval

The number of seconds between sampled frames (a positive number). The function uses the reciprocal as the frame rate. Provide exactly one of fps or interval.

format

A string giving the output image file extension (one of "png", "jpg", "jpeg", "bmp", "tif", "tiff", "webp"). (default = "png")

prefix

A string used as the basename stem of each image, or NULL to derive it from infile's basename. (default = NULL)

run

A logical: run the command through FFmpeg (TRUE, default) or return the compiled command without running it (FALSE).

Value

The compiled FFmpeg command (invisibly when run = TRUE).

Details

extract_frame saves one frame, and extract_frame_batch saves a set of frames that you list. This function is different. It builds a single FFmpeg command whose output is a printf-style file name pattern. FFmpeg's image2 muxer fills the pattern. FFmpeg decides the frame count when it decodes the video, and you do not list the frames. The function writes frames to outdir as <prefix>_<n>.<format>, where <n> is a zero-padded integer starting at 1. The glossary in vignette("tidymedia") explains media terms such as frame rate.

Examples

video <- system.file("extdata", "sample.mp4", package = "tidymedia")
# run = FALSE returns the reproducible command instead of executing it
sample_frames(video, tempdir(), fps = 2, run = FALSE)
#> [1] "-y -i \"/home/runner/work/_temp/Library/tidymedia/extdata/sample.mp4\" -vf \"fps=2\" -qscale:v 2 \"/tmp/RtmpTo1HDT/sample_%06d.png\""