Learn · Developers

How to blur or pixelate a video with Python

Contents

Sometimes a video shows something it shouldn’t: a face in the background, a client’s logo, an email address on a shared screen. Blur or pixelate that part, and the rest of the video can still go out.

It’s a common enough job that YouTube has it in its own editor. YouTube Help puts it in one line: “You can blur parts of your video on a computer in YouTube Studio.” That covers one video at a time. When the videos come from an app, a batch or a pipeline, the blur has to happen in code.

Below are two short Python scripts that blur a video with Shotstack’s video editing API. The first blurs or pixelates the whole frame, or one area of it, in a single render. The second works through a list of videos, each with its own area.

TL;DR

  • A clip’s filters list takes a blur filter with a radius from 0 to 100 pixels, or a pixelate filter with a strength from 0 to 1.
  • To hide one area, put a cropped copy of the video, with the filter on it, on a track above the original.
  • The script below blurred two faces in a 10.44 second clip in one render.
  • Pixelate keeps a hard edge, within 5 pixels of the area. Blur fades out up to 25 pixels past it.
  • For a batch, a second script takes a list of videos and areas. Three videos, 50 seconds of footage, took 6 to 8 seconds each to render.

How blur and pixelate work in the Edit API

A Shotstack edit is a JSON timeline of clips. Every clip can carry a filters list, and each filter in the list has a type and its own settings. The API reference lists all of them. Two of them hide detail:

FilterSettingRangeWhat it does
blurvalue0 to 100The blur radius in pixels. x and y set each axis on its own.
pixelatevalue0 to 1The strength of the pixelation. Higher values give bigger blocks.

This clip blurs a whole video:

JSON
{
  "asset": {
    "type": "video",
    "src": "https://example.com/video.mp4"
  },
  "start": 0,
  "length": "auto",
  "filters": [{ "type": "blur", "value": 30 }]
}

The blur radius is measured on the source video, before it’s scaled to the output size. A radius of 30 on a 1920 x 1080 source comes out as 20 pixels in a 1280 x 720 render.

Blur a video with Python

The script hides two people at the back of a 10 second clip of a talk, hosted by Shotstack. The clip is 1920 x 1080, and the script renders it at 1280 x 720 (hd). It builds the edit, sends it to the API, waits for the render and prints the URL of the finished video.

There’s nothing to install: the script runs on plain Python 3. Put the API key from your Shotstack dashboard in SHOTSTACK_API_KEY first. Renders use credits from your plan, at the rates on the pricing page.

SOURCE can be any video URL that Shotstack can reach. A file on your own machine goes through the Ingest API first, which hosts it and returns a URL.

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

API = "https://api.shotstack.io/edit/v1"
ASSETS = "https://shotstack-assets.s3.ap-southeast-2.amazonaws.com"
SOURCE = f"{ASSETS}/footage/podium-speach.mp4"
EFFECT = "blur"  # "blur" or "pixelate"
FILTERS = {
    "blur": {"type": "blur", "value": 30},  # radius in pixels, 0 to 100
    "pixelate": {"type": "pixelate", "value": 0.3},  # strength, 0 to 1
}
# The part of the frame to hide, as fractions of its width and height.
# Set AREA to None to blur or pixelate the whole frame.
AREA = {"left": 0.5, "top": 0.31, "width": 0.28, "height": 0.16}


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 build_edit():
    video = {"type": "video", "src": SOURCE}
    filtered = {
        "asset": video,
        "start": 0,
        "length": "auto",
        "filters": [FILTERS[EFFECT]],
    }
    tracks = [{"clips": [filtered]}]
    if AREA:
        video["volume"] = 0
        video["crop"] = {
            "left": AREA["left"],
            "top": AREA["top"],
            "right": round(1 - AREA["left"] - AREA["width"], 4),
            "bottom": round(1 - AREA["top"] - AREA["height"], 4),
        }
        original = {"type": "video", "src": SOURCE}
        tracks.append({"clips": [{"asset": original, "start": 0, "length": "auto"}]})
    return {
        "timeline": {"tracks": tracks},
        "output": {"format": "mp4", "resolution": "hd"},
    }


if __name__ == "__main__":
    if not os.environ.get("SHOTSTACK_API_KEY"):
        sys.exit("Set SHOTSTACK_API_KEY first.")
    where = "one area" if AREA else "the whole frame"
    print(f"Effect: {EFFECT} {FILTERS[EFFECT]['value']} on {where}")
    render_id = call(f"{API}/render", build_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":
            break
        if status["status"] == "failed":
            sys.exit(f"Render failed: {status.get('error')}")
    print(f"Video: {status['duration']} s")
    print(status["url"])

Run python blur_video.py. It prints the effect, the render ID, the length of the video and its URL:

Text
Effect: blur 30 on one area
Render queued: b2c97104-3067-4a7d-ac05-0d5d502012e7
Video: 10.44 s
https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/m4x7q2k9tz/b2c97104-3067-4a7d-ac05-0d5d502012e7.mp4

This video shows the original clip next to three results: blur on one area, pixelate on one area, and blur on the whole frame.

How the script works

  • FILTERS holds one ready-made filter for each effect, and EFFECT picks the one to use.
  • build_edit() puts the video on a clip with that filter. "length": "auto" makes the clip as long as the video.
  • When AREA is set, the function crops that clip down to the area and adds the full video on a track below it. The top track covers the bottom one, so only the area changes.
  • The cropped copy is muted, so the video’s sound plays once.
  • The last block sends the edit and asks for its status every 5 seconds until it is done, then prints the video’s length and URL.

Hide one area of the frame

AREA describes a rectangle with four fractions of the frame: where it starts from the left and from the top, and how wide and tall it is. The values in the script cover the two people at the table:

SettingValueIn a 1920 x 1080 frame
left0.5Starts 960 pixels from the left
top0.31Starts 335 pixels from the top
width0.28538 pixels wide
height0.16173 pixels tall

To find the values for your own video, open a frame in an image editor and read the pixel position of the rectangle. Then divide each number by the frame’s width or height. left plus width, and top plus height, must not go past 1.

The two effects treat the edge of the area differently. These numbers come from the 1280 x 720 render:

EffectEdge of the hidden area
pixelate at 0.3A hard edge. The changed pixels stay within 5 pixels of the area.
blur at 30A soft edge. The blur fades out up to 25 pixels past the area.

A radius of 30 on this 173 pixel tall area, about a sixth of its height, hides both faces. To hide more, make the area bigger or switch EFFECT to "pixelate", and leave the radius where it is: a bigger radius softens the whole patch, not only its edge.

The area stays in place for the whole clip. That suits anything that holds its position in the frame: people filmed by a fixed camera, a screen recording, a logo in a corner.

Blur or pixelate the whole frame

Set AREA = None and the script sends a single clip with the filter on it. Nothing is cropped, and there’s no second track.

A fully blurred video makes a good background. Put a title, or a smaller copy of the same video, on a track above it. Our guide on how to blur the sides of a vertical video builds that second layout.

A clip also has a filter setting with a blur preset. That preset matches a blur filter with a value of 10, so use the filters list when you want to choose the strength.

Bring a blurred video into focus

Every filter value can change over time. Give value a list of tweens instead of a number, and each tween moves it from one value to another:

JSON
{
  "type": "blur",
  "value": [{ "from": 40, "to": 0, "start": 0, "length": 2 }]
}

With this filter the clip starts blurred and is fully sharp 2 seconds in, like a camera finding focus. The animations guide covers tweens and easing.

Blur videos at scale

A privacy job rarely stops at one video. It’s a folder of recordings, or every clip your users upload, and each one has its own thing to hide.

The batch script below imports the first one, so save that as blur_video.py next to it. Each job in its list is a video and the area to hide, or None for the whole frame:

Python
import os
import sys
import time

import blur_video

FOOTAGE = f"{blur_video.ASSETS}/footage"
# One job for each video: its URL and the area to hide (None for the whole frame).
JOBS = [
    (blur_video.SOURCE, {"left": 0.5, "top": 0.31, "width": 0.28, "height": 0.16}),
    (
        f"{FOOTAGE}/scott-ko.mp4",
        {"left": 0.08, "top": 0.06, "width": 0.23, "height": 0.5},
    ),
    (f"{FOOTAGE}/skier.mp4", None),
]

if not os.environ.get("SHOTSTACK_API_KEY"):
    sys.exit("Set SHOTSTACK_API_KEY first.")
began = time.time()
renders = {}
for source, area in JOBS:
    blur_video.SOURCE, blur_video.AREA = source, area
    edit = blur_video.build_edit()
    response = blur_video.call(f"{blur_video.API}/render", edit)
    renders[response["response"]["id"]] = source.rsplit("/", 1)[-1]
print(f"Queued {len(renders)} renders")
while renders:
    time.sleep(5)
    for render_id in list(renders):
        url = f"{blur_video.API}/render/{render_id}"
        status = blur_video.call(url)["response"]
        if status["status"] in ("done", "failed"):
            name = renders.pop(render_id)
            result = status.get("url") or status.get("error")
            print(f"{time.time() - began:3.0f} s  {name}: {status['status']}  {result}")

Run python blur_many.py. It sends all three render requests first. Then it checks them every 5 seconds and prints each video’s name once it is done:

Text
Queued 3 renders
 12 s  podium-speach.mp4: done  https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/m4x7q2k9tz/8d9d40ec-b032-4b9e-a23a-2370e8258297.mp4
 21 s  scott-ko.mp4: done  https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/m4x7q2k9tz/c3c8b832-4e41-4bc7-a100-6dfdf809850a.mp4
 25 s  skier.mp4: done  https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/m4x7q2k9tz/8a26f4fe-9672-4643-a73b-c262dfdf51a5.mp4

That’s 50 seconds of footage in three videos: the 10.44 second talk with two faces blurred, a 25.87 second interview with a monitor in the shot blurred, and a 14.12 second ski clip blurred whole.

Each render took between 6 and 8 seconds, and the script had collected all three 25 seconds after it started. Every job uses the effect set in EFFECT. Here they are side by side:

The areas don’t have to be typed in. A review screen where someone drags a box over each video gives you a left, top, width and height in pixels. Divide them by the frame size and add the job to the list.

Hide faces, logos and screens with Shotstack

Hiding one area comes down to a cropped copy of the video with a filter on it, placed over the original. A blur radius of 30 or a pixelate strength of 0.3 hides both faces in the sample clip, and a list of videos takes one more loop. Put your own video URLs and areas in JOBS to try it.

Sign up for a free Shotstack account, copy your API key and run the first script.

Frequently asked questions (FAQs)

Can I hide more than one area?

Yes. Add one cropped copy for each area, each on its own track above the original and each with its volume at 0. Every copy carries its own filter, so one render can pixelate a face and blur a sign.

Why does the same radius look weaker on a 4K video?

The radius counts pixels of the source video. On a 3840 x 2160 source, 30 pixels reach half as far across the picture as they do at 1920 x 1080. Double the radius when the source is twice as wide, and the result looks the same.

Can I combine blur with other filters?

Yes. Filters run in the order they appear in the list. A blur filter followed by a saturation filter with a value of 0 gives a blurred, black and white video, which makes a calm background for text.

Can I blur a video with FFmpeg instead?

Yes, on your own machine. Our guide on how to blur a video with FFmpeg has the commands for Gaussian, box and directional blur, and for blurring part of the frame.

Keep reading

Start free

  • Unlimited developer sandbox
  • No credit card required