Learn · Developers

The Ken Burns effect: what it is and how to add it with Python

Contents

A photo on a video timeline just sits there. Hold it for five seconds and the video feels like it has stopped.

The Ken Burns effect fixes that with a slow zoom and a slow pan. The frame drifts across the picture, and the photo starts to feel like a shot, with a direction and something it ends on.

This guide explains what the effect is and where the name comes from. Then it builds the effect in Python with Shotstack’s video editing API, first with a one-word motion effect, then with a move you design yourself.

The last script reads a table of photos, gives each one its own move, adds music and renders the result as a wide video and a vertical one.

TL;DR

  • The Ken Burns effect is a slow zoom and pan across a still photo. It’s named after the documentary filmmaker Ken Burns.
  • The quick way is one word: add "effect": "zoomIn" to an image clip. There are six effects, each with a Slow and a Fast version, and they all work around the middle of the photo.
  • To choose where a move starts and ends, give the clip’s scale and offset a tween each. A short Python function works the numbers out from two points on the photo.
  • A second script reads a CSV with one row for each photo and its move, and renders one video with dissolves and music, in 16:9 and in 9:16.

What is the Ken Burns effect?

The Ken Burns effect is a slow zoom, a slow pan, or both, across a still photo. Nothing in the picture moves. The frame does, so the viewer gets the feeling of a camera traveling over the image.

The name comes from Ken Burns, the American documentary filmmaker. Writing about his early films, the National Endowment for the Humanities’ Humanities magazine describes “still photographs (probed by a camera that zoomed and panned, like a roving eye or a reader with a magnifying glass)”.

His 1990 series The Civil War is the famous case. The war ended decades before motion pictures, so its eleven and a half hours lean heavily on photographs. It still drew a mass audience: the same article reports that “Thirty-nine million viewers watched The Civil War during its first week”.

Editing software later put his name on a button. Apple’s iMovie guide says you add the Ken Burns effect “to make the camera appear to zoom in to or out of the clip or photo”, and you set it with “Two frames, labeled Start and End”.

Those two frames are the whole idea. Burns explains why in the Humanities article: “If you tilt down from an innocent young boy’s face to find that he’s packing two pistols, you’ve told a story in the revealing of that moment”.

So a Ken Burns move is three decisions: the framing you start on, the framing you end on, and how long it takes to get from one to the other.

What you need

  • A Shotstack API key. Sign up for free and copy the production key from the dashboard. Production renders use credits (see pricing).
  • Python 3.9 or later. The scripts don’t need any packages.
  • Photos as JPEG files at public URLs. The examples use five listing photos of a house from Shotstack’s sample library, so you can run every script as it is.

Set the key in your terminal before you run anything:

Bash
export SHOTSTACK_API_KEY="your_production_key"

The quick way: a built-in motion effect

A Shotstack edit is a JSON timeline of clips, and an image clip can take an effect. One word gives the photo a move:

JSON
{
  "timeline": {
    "tracks": [
      {
        "clips": [
          {
            "asset": {
              "type": "image",
              "src": "https://shotstack-assets.s3.ap-southeast-2.amazonaws.com/images/realestate5.jpg"
            },
            "start": 0,
            "length": 6,
            "effect": "zoomIn"
          }
        ]
      }
    ]
  },
  "output": {
    "format": "mp4",
    "size": { "width": 1280, "height": 720 },
    "fps": 25
  }
}

Our guide to rendering your first video shows how to send an edit like this one. The result is six seconds of a terrace with a slow push in:

There are six effects: zoomIn, zoomOut, slideLeft, slideRight, slideUp and slideDown. Add Slow or Fast to the name (zoomInSlow, slideLeftFast) to change how far the move goes. Measured on a test image, this is what each one does over the length of the clip:

EffectSize of the photoDistance it slides
zoomInSlowGrows from 1 to 1.1None
zoomInGrows from 1 to 1.3None
zoomInFastGrows from 1 to 1.67None
slideLeftSlowStays at 1.066% of the frame width
slideLeftStays at 1.1616% of the frame width
slideLeftFastStays at 1.2424% of the frame width

Each effect covers a set distance over the whole clip. A 5 second clip and a 10 second clip with zoomIn both end at 1.3 times the size, so a longer clip gives you a slower move.

A built-in effect always works around the middle of the photo. In the terrace photo the middle is a roof post, and the pool, the reason you’d show this photo at all, stays off to the right.

When the middle of each photo is the right place to look, these effects are all you need. Our guide to turning images into a slideshow video with Python builds a full slideshow with them.

Design the move: choose where it starts and ends

Two properties of a clip do the work. scale sets the size of the photo, where 1 fills the frame and 1.5 is one and a half times that. offset slides the photo left, right, up or down.

Both take a list of tweens in place of a number. A tween moves a value from one number to another over a length of time. This is the clip the next script builds for the terrace photo:

JSON
{
  "asset": {
    "type": "image",
    "src": "https://shotstack-assets.s3.ap-southeast-2.amazonaws.com/images/realestate5.jpg"
  },
  "start": 0,
  "length": 6,
  "fit": "crop",
  "scale": [
    {
      "from": 1.0,
      "to": 1.5,
      "start": 0,
      "length": 6,
      "interpolation": "bezier",
      "easing": "easeInOutSine"
    }
  ],
  "offset": {
    "x": [
      {
        "from": 0.0,
        "to": -0.25,
        "start": 0,
        "length": 6,
        "interpolation": "bezier",
        "easing": "easeInOutSine"
      }
    ],
    "y": [
      {
        "from": 0.0,
        "to": 0.1779,
        "start": 0,
        "length": 6,
        "interpolation": "bezier",
        "easing": "easeInOutSine"
      }
    ]
  }
}

The photo grows to 1.5 times its size while it slides a quarter of the frame to the left and a little up. On screen, that reads as a camera pushing in toward the pool.

You could write those numbers by hand, but nobody thinks in offsets. You think “start on the whole terrace, end on the pool”. So the script takes two points on the photo and works out the tweens.

Save it as ken_burns.py:

Python
import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request

API = "https://api.shotstack.io/edit/v1"
PHOTO = (
    "https://shotstack-assets.s3.ap-southeast-2.amazonaws.com/images/realestate5.jpg"
)
START = (0.5, 0.5, 1.0)  # x, y, zoom: the middle of the photo, all of it in view
END = (0.78, 0.6, 1.5)  # the pool, 1.5 times closer
SECONDS = 6
EASING = "easeInOutSine"  # None moves at a constant speed
WIDTH, HEIGHT = 1280, 720
FPS = 25


def call(url, body=None):
    data = json.dumps(body).encode() if body is not None else None
    headers = {
        "x-api-key": os.environ["SHOTSTACK_API_KEY"],
        "Content-Type": "application/json",
    }
    try:
        request = urllib.request.Request(url, data, headers)
        with urllib.request.urlopen(request) as response:
            return json.load(response)
    except urllib.error.HTTPError as error:
        sys.exit(f"HTTP {error.code}: {' '.join(error.read().decode().split())[:300]}")


def photo_size(url):
    """Width and height of the photo in pixels, read with the probe endpoint."""
    probe = call(f"{API}/probe/{urllib.parse.quote(url, safe='')}")
    streams = probe["response"]["metadata"]["streams"]
    stream = next((s for s in streams if s.get("width")), None)
    if not stream:
        sys.exit(f"Could not read the size of {url}")
    return stream["width"], stream["height"]


def placement(point, cover):
    """Clip offsets that put a point of the photo in the middle of the frame."""
    x, y, zoom = point
    offsets = []
    for distance, size in ((0.5 - x, cover[0]), (y - 0.5, cover[1])):
        limit = max((size * zoom - 1) / 2, 0)  # past this, the frame leaves the photo
        offsets.append(round(max(-limit, min(limit, distance * size * zoom)), 4) + 0.0)
    return offsets


def tween(start, end, seconds):
    step = {"from": start, "to": end, "start": 0, "length": seconds}
    if EASING:
        step.update(interpolation="bezier", easing=EASING)
    return [step]


def move_clip(photo, start, end, seconds, at=0):
    """An image clip that moves from one framing of the photo to another."""
    width, height = photo_size(photo)
    shape = (width / height) / (WIDTH / HEIGHT)
    cover = (max(shape, 1), max(1 / shape, 1))  # photo size in frames at zoom 1
    (x0, y0), (x1, y1) = placement(start, cover), placement(end, cover)
    return {
        "asset": {"type": "image", "src": photo},
        "start": at,
        "length": seconds,
        "fit": "crop",
        "scale": tween(start[2], end[2], seconds),
        "offset": {"x": tween(x0, x1, seconds), "y": tween(y0, y1, seconds)},
    }


def render(edit):
    render_id = call(f"{API}/render", edit)["response"]["id"]
    print("Render queued:", render_id)
    while True:
        time.sleep(5)
        status = call(f"{API}/render/{render_id}")["response"]
        if status["status"] == "done":
            return status
        if status["status"] == "failed":
            sys.exit(f"Render failed: {status.get('error')}")


if __name__ == "__main__":
    if not os.environ.get("SHOTSTACK_API_KEY"):
        sys.exit("Set SHOTSTACK_API_KEY first.")
    clip = move_clip(PHOTO, START, END, SECONDS)
    moves = {"scale": clip["scale"], "offset x": clip["offset"]["x"]}
    moves["offset y"] = clip["offset"]["y"]
    for name, (step,) in moves.items():
        print(f"{name}: {step['from']} to {step['to']}")
    edit = {
        "timeline": {"tracks": [{"clips": [clip]}]},
        "output": {
            "format": "mp4",
            "size": {"width": WIDTH, "height": HEIGHT},
            "fps": FPS,
        },
    }
    status = render(edit)
    print(f"MP4: {status['duration']} s")
    print(status["url"])

Run it:

Bash
python ken_burns.py

The script prints the tweens it worked out, then the link to the MP4:

Text
scale: 1.0 to 1.5
offset x: 0.0 to -0.25
offset y: 0.0 to 0.1779
Render queued: 69e33443-41d0-421b-aa45-4cdf221ce90b
MP4: 6 s
https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/m4x7q2k9tz/69e33443-41d0-421b-aa45-4cdf221ce90b.mp4

Here is the MP4 from that run. It starts on the whole terrace and ends on the pool:

How the script works

  • The two framings. START and END each hold x, y and a zoom. x and y are a point on the photo as fractions, from 0, 0 at the top left to 1, 1 at the bottom right. A zoom of 1 means the photo fills the frame.
  • The photo’s size. photo_size asks the probe endpoint for the width and height of the photo. The script needs them to know how much of the photo the frame can see.
  • The offsets. placement turns a point into the offset that brings it to the middle of the frame. An offset of 1 is one frame width or one frame height, and a positive y moves the photo up. The positioning guide has the details.
  • The edge of the photo. The frame can’t leave the picture. At a zoom of 1.5 this photo can slide a quarter of a frame sideways at most, so placement stops there. The pool sits near the right edge, and the move ends as close to it as the zoom allows.
  • The timing. All three tweens share one start, one length and one easing, so the zoom and the slide stay in step. A tween’s start counts from the start of its clip.

Change the move

Swap START and END and the same move runs backwards: it starts close on the pool and pulls back to show the whole terrace.

Give both framings the same zoom, above 1, and a different x, and you get a pan with no zoom change at all.

SECONDS sets the speed. EASING sets how the move starts and stops: easeInOutSine starts and ends gently, and None moves at a constant speed. The animations guide lists every easing you can use.

Give every photo its own move

One photo with a designed move is a shot. A set of them is a sequence, and each photo needs a different move: you push in on the house, pan across the bedroom, pull back from a detail in the kitchen.

That is a table, with one row for each photo. Save this one as moves.csv, next to ken_burns.py:

Text
photo,seconds,from_x,from_y,from_zoom,to_x,to_y,to_zoom
https://shotstack-assets.s3.ap-southeast-2.amazonaws.com/images/realestate1.jpg,5,0.5,0.5,1,0.4,0.68,1.4
https://shotstack-assets.s3.ap-southeast-2.amazonaws.com/images/realestate2.jpg,5,0.2,0.6,1.35,0.6,0.68,1.35
https://shotstack-assets.s3.ap-southeast-2.amazonaws.com/images/realestate3.jpg,5,0.15,0.66,1.5,0.5,0.5,1
https://shotstack-assets.s3.ap-southeast-2.amazonaws.com/images/realestate4.jpg,5,0.5,0.42,1.5,0.5,0.68,1.5
https://shotstack-assets.s3.ap-southeast-2.amazonaws.com/images/realestate5.jpg,6,0.5,0.5,1,0.78,0.6,1.5

Each row holds a photo, the seconds it stays on screen, and the two framings. These are the five moves:

PhotoMoveWhat you see
The housePush inStarts on the whole house and moves in toward the entrance
The bedroomPanSlides from the window to the bed at the same zoom
The kitchenPull backStarts close on a vase and opens up to the whole room
The living roomTilt downStarts on the painting and moves down to the sofa
The terracePush inThe move from the first script, ending on the pool

Save this script as ken_burns_reel.py, in the same folder:

Python
"""Turn a table of photos and moves into one Ken Burns video with music, wide and vertical."""

import csv
import os
import sys

import ken_burns

TABLE = "moves.csv"
MUSIC = "https://shotstack-assets.s3.ap-southeast-2.amazonaws.com/music/unminus/palmtrees.mp3"
DISSOLVE = 1  # seconds each photo takes to fade in over the one before
SHAPES = {"wide": (1280, 720), "vertical": (720, 1280)}

if not os.environ.get("SHOTSTACK_API_KEY"):
    sys.exit("Set SHOTSTACK_API_KEY first.")
with open(TABLE, newline="", encoding="utf-8") as table:
    rows = list(csv.DictReader(table))
for name, (width, height) in SHAPES.items():
    ken_burns.WIDTH, ken_burns.HEIGHT = width, height
    tracks, at = [], 0
    for row in rows:
        seconds = float(row["seconds"])
        start = [float(row[key]) for key in ("from_x", "from_y", "from_zoom")]
        end = [float(row[key]) for key in ("to_x", "to_y", "to_zoom")]
        clip = ken_burns.move_clip(row["photo"], start, end, seconds, at)
        if tracks:
            clip["transition"] = {"in": "fade"}
        tracks.insert(0, {"clips": [clip]})  # each new photo goes on top
        at += seconds - DISSOLVE
    edit = {
        "timeline": {
            "soundtrack": {"src": MUSIC, "effect": "fadeOut"},
            "tracks": tracks,
        },
        "output": {
            "format": "mp4",
            "size": {"width": width, "height": height},
            "fps": ken_burns.FPS,
        },
    }
    status = ken_burns.render(edit)
    print(f"{name}: {len(rows)} photos, {status['duration']} s")
    print(status["url"])

Run it with python ken_burns_reel.py. It renders the two videos one after the other:

Text
Render queued: 0ac29283-abea-4770-abc6-861d4677e42c
wide: 5 photos, 22 s
https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/m4x7q2k9tz/0ac29283-abea-4770-abc6-861d4677e42c.mp4
Render queued: 27f2111d-21dc-4f1e-ac65-eeff73d89538
vertical: 5 photos, 22 s
https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/m4x7q2k9tz/27f2111d-21dc-4f1e-ac65-eeff73d89538.mp4

This is the wide video from that run:

And this is the vertical one, from the same five rows:

Three things in the script are worth a closer look.

The dissolves. Each photo goes on its own track, above the one before it, and starts one second before the previous photo ends. A fade transition brings it in while the two overlap. Both photos keep moving as they cross, so the sequence never comes to a stop.

Our guide to fades and dissolves covers the transition itself.

The music. soundtrack plays one track under the whole video, and fadeOut brings it down at the end.

The two shapes. The points in the table are fractions of the photo, not of the frame, so the same rows work for any output size. A vertical frame shows a little over a third of the width of these photos. The moves head for the same points, and the pans travel farther across the picture.

For a handful of photos, you pick the points by eye. For a catalog, look at what your image library already stores. If it keeps a focal point for each photo, that point is the to_x and to_y of the row, and a new listing is five new rows.

If your listings live in a spreadsheet, our guide to making real estate videos with n8n shows a way to send each new row to a render without code.

Can FFmpeg do the Ken Burns effect?

Yes, with the zoompan filter. The FFmpeg documentation describes it as “Apply Zoom & Pan effect”, and you write the zoom and the position as expressions that FFmpeg works out again for every frame.

This command makes the terrace move from the first script, at a constant speed, with FFmpeg 8.1:

Bash
ffmpeg -i realestate5.jpg -vf "crop=iw:iw*9/16,scale=7680:-2,zoompan=z='1+0.5*on/149':x='iw*(0.5+0.1667*on/149)-iw/zoom/2':y='ih*(0.5+0.1186*on/149)-ih/zoom/2':d=150:s=1280x720:fps=25" -c:v libx264 -pix_fmt yuv420p terrace.mp4

on is the number of the frame, and d=150 is the length, which the documentation calls “the duration expression in number of frames”. At 25 fps, 150 frames is 6 seconds. x and y are the top left corner of the part of the photo that is in view.

The scale=7680:-2 step makes the photo four times wider before the move, and it’s there for a reason. I tracked a marker through a zoom that should move it 0.86 pixels in every frame. Without the step, it moved between 0.03 and 1.79 pixels a frame. With it, between 0.24 and 1.65.

FFmpeg is a good fit for one photo on your own computer. Every new move is a new set of expressions, though, and an ease is more math on top. Our guide to converting images to video with FFmpeg covers the rest of the photo-to-video job.

Put your photos in motion with Shotstack

A Ken Burns move is two framings and a length of time, and that is all the first script asks for. The second one reads a table of photos and returns a finished sequence with dissolves and music, in two shapes at once.

The moves live in a CSV file, so changing a shot means changing a number, and nobody has to open a video editor.

Sign up for a free Shotstack API key and give your first photo a move.

Frequently asked questions (FAQs)

How large do my photos need to be?

Large enough to fill the frame at your closest zoom. Multiply the output width by the largest zoom: a 1280 pixel wide video at a zoom of 1.5 uses 1920 pixels of photo, which is the width of the sample photos.

The same goes for the height. The sample photos are about 1280 pixels tall, so the 720 x 1280 vertical video enlarges them when it zooms. For vertical video, start from taller photos.

Can I use photos that are on my computer?

Yes. Upload each photo with the Ingest API first, then put the link of the uploaded file in the photo column. The API gives you a signed URL to send the file to. The docs show the requests under upload files directly.

Can the photo come to rest before the next one fades in?

Yes. Make the tweens shorter than the clip. With a 6 second clip and tweens that are 3 seconds long, the photo moves for 3 seconds and holds its end framing for the other 3.

In ken_burns.py, that is a change to one line in tween: use a shorter length than seconds.

Does the same move work on a video clip?

Yes. scale and offset belong to the clip, so they don’t care what the asset is. Change the asset’s type to video and the same tweens push in on moving footage. The probe endpoint reads the size of a video the same way it reads a photo’s.

Keep reading

Start free

  • Unlimited developer sandbox
  • No credit card required