Skip to contents

frame_to_img() extracts one or more frames from a saved video file directly into memory as an object of class image (or a named list of image objects if multiple frames are requested).

On Windows, decoding runs with zero disk overhead via high-speed native Media Foundation C++ integration. On other operating systems (or when native reader is unavailable), it seamlessly falls back to av.

Usage

frame_to_img(
  video,
  frames = 1L,
  time = NULL,
  show = FALSE,
  output_dir = NULL,
  verbose = FALSE,
  ...
)

Arguments

video

Character. Path to the video file (e.g., "video.mp4").

frames

Frame index or indices to extract (1-indexed). Can be:

  • A single integer (e.g., 1 for the first frame, 50 for frame 50).

  • A vector of integers (e.g., c(1, 15, 30) or 1:5).

  • "first" for the first frame (1L).

  • "last" for the last frame of the video.

  • "all" for all frames in the video. Defaults to 1L. Mutually exclusive with time.

time

Numeric. Video timestamp(s) in seconds from which to extract frames (e.g., time = 1.5 or c(0.5, 2.0)). Mutually exclusive with frames.

show

Logical. If TRUE, plots the extracted image(s). Default is FALSE.

output_dir

Optional character. Directory where extracted images should be saved to disk. If NULL (default), images are kept in memory only.

verbose

Logical. If TRUE, prints informative messages. Default is FALSE.

...

Additional arguments passed to plot.image() or image_combine() when show = TRUE.

Value

An object of class image (if a single frame is requested) or a named list of image objects (if multiple frames are requested, named "frame_1", "frame_2", etc.).

Author

Tiago Olivoto tiagoolivoto@gmail.com

Examples

if (FALSE) { # interactive()
# Extract the first frame of a video
img <- frame_to_img("my_video.mp4")
plot(img)

# Extract frame at 2.5 seconds
img <- frame_to_img("my_video.mp4", time = 2.5)

# Extract multiple frames as a list of images
imgs <- frame_to_img("my_video.mp4", frames = c(10, 30, 50))
image_combine(imgs)
}