DEV Community

Cover image for Extract frames from a video URL in Python without downloading the file
PIC DEV
PIC DEV

Posted on

Extract frames from a video URL in Python without downloading the file

The usual way to get thumbnails from a video is to download it and run ffmpeg -i video.mp4 -vf fps=1/10 out_%03d.jpg. That decodes every frame of the file to keep one in three hundred. For ten thumbnails from an hour-long recording sitting on S3, it is a lot of bandwidth and CPU for nothing.

PyAV binds the FFmpeg libraries directly, so you can do what a video player does when you drag the seek bar: jump near the moment you want and decode only from there. It also opens https:// URLs itself and reads them with HTTP range requests, so the file never lands on your disk. The wheels ship their own FFmpeg, so there is no ffmpeg binary to install.

Evenly spaced frames

pip install av pillow numpy

import av


def open_video(url):
    container = av.open(url)
    stream = container.streams.video[0]
    stream.thread_type = "AUTO"  # frame and slice threading: several times faster on 1080p
    start = float(stream.start_time * stream.time_base) if stream.start_time else 0.0
    duration = float(stream.duration * stream.time_base) if stream.duration else container.duration / 1e6
    return container, stream, start, duration


def frames_at(url, times):
    """Yield (seconds, PIL image) for each requested time. The file is not downloaded."""
    container, stream, start, _ = open_video(url)
    with container:
        for t in times:
            container.seek(int((t + start) / stream.time_base), stream=stream, backward=True)
            for frame in container.decode(stream):
                if frame.pts is None:
                    continue
                now = float(frame.pts * stream.time_base) - start
                if now >= t:
                    yield now, frame.to_image()
                    break


def evenly_spaced(url, n):
    container, _, _, duration = open_video(url)
    container.close()
    step = duration / n
    return [step * (i + 0.5) for i in range(n)]


url = "https://media.w3.org/2010/05/sintel/trailer.mp4"
for t, image in frames_at(url, evenly_spaced(url, 5)):
    image.save(f"thumb_{t:06.2f}.jpg", quality=85)
    print(f"thumb  {t:6.2f} s  {image.width}x{image.height}")
Enter fullscreen mode Exit fullscreen mode
thumb    5.25 s  854x480
thumb   15.67 s  854x480
thumb   26.12 s  854x480
thumb   36.58 s  854x480
thumb   47.00 s  854x480
Enter fullscreen mode Exit fullscreen mode

evenly_spaced takes the middle of each equal slice instead of the slice boundaries. That one choice removes the two worst thumbnails in most videos: the black first frame and the end credits.

Why the inner loop is there

container.seek() does not land on the time you ask for. A compressed video stores a full picture only at keyframes, and everything between them is a difference from the previous frame. Seek puts you on the keyframe at or before your target, and you have to decode forward from there.

How far forward depends on the encoder. In the 10-minute test file I used, the first keyframes sit at 0.0, 10.4, 11.9, 15.8, 23.0 and 33.5 seconds. Skip the loop and a request for the frame at 32 seconds hands you the one from 23.

Three more details in that function are easy to get wrong:

  • Seek takes stream ticks, not seconds. Divide by stream.time_base. Passing seconds gives you the start of the file every time, with no error.
  • start_time is not always zero. Some files start their timestamps at 1.4 seconds or at an hour. Subtract it, or every frame is off by that much.
  • frame.pts can be None on broken or raw streams. Skip those frames instead of crashing on the multiplication.

One frame per scene

Scene detection cannot seek, because a cut can be anywhere. It has to decode everything, so the trick is to make the comparison cheap: shrink each frame to 64 by 36 gray pixels and take the mean absolute difference from the previous one.

import numpy as np


def scene_cuts(url, threshold=0.075, min_gap=1.0):
    """Yield (seconds, score, PIL image) for the first frame after each cut."""
    container, stream, start, _ = open_video(url)
    previous, last = None, -min_gap
    with container:
        for frame in container.decode(stream):
            if frame.pts is None:
                continue
            now = float(frame.pts * stream.time_base) - start
            small = frame.reformat(width=64, height=36, format="gray").to_ndarray().astype(np.int16)
            if previous is not None:
                score = float(np.abs(small - previous).mean()) / 255
                if score >= threshold and now - last >= min_gap:
                    last = now
                    yield now, score, frame.to_image()
            previous = small
Enter fullscreen mode Exit fullscreen mode
scene   16.50 s  score 0.49
scene   17.50 s  score 0.21
scene   23.79 s  score 0.17
scene   25.88 s  score 0.37
scene   27.42 s  score 0.24
scene   29.92 s  score 0.11
scene   30.92 s  score 0.10
Enter fullscreen mode Exit fullscreen mode

Compare each frame with the one right before it, not with a frame from a fifth of a second earlier. My first version sampled five frames per second to save time, and every fast camera move scored like a cut, because 200 milliseconds of motion changes most of the picture. Consecutive frames differ a little during motion and a lot at a cut.

Cast to int16 before subtracting. The frames arrive as uint8, and uint8 subtraction wraps around: 10 minus 12 is 254.

What this does not catch is a dissolve. Two shots blending over a second never produce one large jump. A fade through black is detectable with one extra rule: treat a run of near-black frames as a boundary and report the first lit frame after it.

Speed, measured

On one shared cloud CPU core:

Job Time
299 frames, one every 2 seconds, from a 10-minute 720p MP4 58 s
Scene scan of the same 10 minutes, every frame decoded 45 s
10 evenly spaced frames from a 52-second trailer about 2 s

Network matters more than CPU for the seek modes. Each seek is a new range request, and a slow file host makes every frame cost a second or more.

Things that will bite you

  • Rate limits on range requests. One host I tested answered 429 Too Many Requests after about eight seeks. Nothing is raised at the point of failure: the decode loop simply ends early and you get 7 frames instead of 20. Compare what you got with what you asked for, and reopen the container after a pause when the stream ends long before your target time.
  • Servers without range support. Seeking then means reading from the start of the file. It works, slowly.
  • Rotation. A phone video is often stored sideways with a rotation flag in the metadata. to_image() gives you the stored pixels, so apply the rotation yourself if your input comes from phones.
  • HLS playlists. .m3u8 URLs open the same way, but seeking is slower: a few seconds per frame on a long stream.
  • Memory. to_image() on 4K gives a 25 MB bitmap. Encode and release each frame as you go rather than collecting a list.

If you do not want to run it yourself

I host this as an Apify Actor, Video Frame Extractor: you send direct video URLs and get image links back as JSON, with five modes (count, interval, scenes, keyframes, timestamps), JPG, PNG or WEBP output, a contact sheet and an optional ZIP per video. It costs $0.001 per frame, and videos that fail are not charged. I built it and I earn from it. Python, Node and curl examples are in this repository.

curl -s -X POST \
  "https://api.apify.com/v2/acts/picdev~video-frame-extractor-mp4-to-jpg/run-sync-get-dataset-items" \
  -H "Authorization: Bearer $APIFY_TOKEN" -H "Content-Type: application/json" \
  -d '{"videoUrls": ["https://media.w3.org/2010/05/sintel/trailer.mp4"], "mode": "scenes"}'
Enter fullscreen mode Exit fullscreen mode

For a handful of videos on your own machine, the two functions above are all you need.

Top comments (0)