Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 37 ยท Projects and Practice

Project: Image Filter Studio

Build an image filter app: brightness, contrast, threshold, blur and flip on pixel grids, a pipeline of steps, ASCII preview and the Gradio layout with sliders, with runnable pixel code.

Filters make a great second project, because they combine an image input, several controls and instant feedback. You will write the filters as small functions on a grid of pixels, chain them in a pipeline, and then wire sliders and a dropdown to it in Gradio.

Real Gradio, NumPy images and a browser are not available here, so the Gradio code is read-only. To run the filters we use a grayscale image as a list of rows of numbers from 0 (black) to 255 (white), with plain Python, and print it as ASCII art. In the real app the same math applies to a NumPy array, where it is one line per filter.

The pipeline idea

flowchart LR
    I["Uploaded image"] --> G["Grayscale (optional)"]
    G --> B["Brightness"]
    B --> C["Contrast"]
    C --> T["Threshold (optional)"]
    T --> F["Flip / rotate"]
    F --> O["Output image"]

Each filter takes an image and returns an image, so they can be chained in any order.

Because every filter has the same shape (image in, image out) the app only needs a list of steps, which is also why adding a filter is easy.

Step 1: filters on a pixel grid

Python Brightness, contrast, threshold

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The original is a left-to-right gradient from dark to light. Brightness shifts everything lighter and clips at 255 (the clamp). Contrast stretches values away from mid-gray, so dark gets darker and light gets lighter, and threshold turns the picture into two tones, a left half of spaces and a right half of @ signs. With NumPy these are np.clip(img + 60, 0, 255), np.clip((img - 128) * 2 + 128, 0, 255) and np.where(img >= 128, 255, 0).

Step 2: neighbours, blur and flips

A blur replaces each pixel by the average of itself and its neighbours. This is a convolution, and the same idea powers sharpening and edge detection.

Python Box blur, flip and edge strength

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The sharp boundary (0 to 255) turns into a smooth ramp when blurred, and the edge filter lights up only where the jump occurs (the value 255 at one position). A larger blur averages a bigger window; a Gaussian blur weights the center more.

Step 3: the pipeline function

The app function receives the image and the control values and applies the chosen steps. Notice how it stays independent of Gradio:

Python Apply a list of steps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The three calls print [[50, 150, 250]], [[55, 155, 255]] and [[0, 52, 235]]. In the second, invert gives [255, 155, 55] and mirror reverses it. In the third, contrast 2 gives [0, 72, 255] (both ends clipped) and subtracting 20 gives [0, 52, 235]. Order matters, which is the main thing to understand about pipelines.

Step 4: the Gradio app

With NumPy and Pillow the real filters are short. The app function applies them to the uploaded image:

Python
import gradio as gr
import numpy as np
from PIL import ImageFilter, Image

def apply(img, brightness, contrast, blur_radius, grayscale, flip):
    if img is None:
        raise gr.Error("Please upload an image first.")
    pil = Image.fromarray(img)
    if grayscale:
        pil = pil.convert("L").convert("RGB")
    if blur_radius > 0:
        pil = pil.filter(ImageFilter.GaussianBlur(blur_radius))
    arr = np.asarray(pil, dtype="float32")
    arr = (arr - 128) * contrast + 128 + brightness
    arr = np.clip(arr, 0, 255).astype("uint8")
    if flip:
        arr = arr[:, ::-1]
    return arr

with gr.Blocks(title="Image filter studio") as demo:
    gr.Markdown("# Image filter studio")
    with gr.Row():
        with gr.Column():
            src = gr.Image(label="Upload", type="numpy", image_mode="RGB")
            bright = gr.Slider(-100, 100, value=0, label="Brightness")
            cont = gr.Slider(0.5, 2.5, value=1.0, step=0.05, label="Contrast")
            blur = gr.Slider(0, 10, value=0, step=0.5, label="Blur radius")
            gray = gr.Checkbox(label="Grayscale")
            flip = gr.Checkbox(label="Mirror")
        out = gr.Image(label="Result")
    controls = [src, bright, cont, blur, gray, flip]
    for c in controls:
        c.change(apply, controls, out, show_progress="hidden")
    gr.Examples(["examples/cat.jpg"], src)

demo.launch()

After launch, the page shows controls on the left and the result on the right. Moving a slider updates the output at once, because .change is attached to every control and receives all of them as inputs. show_progress="hidden" avoids a flashing spinner on fast operations. Upload a large photo and the demo may feel slow; resize big images to about 1,000 pixels on the long side at the start of apply.

Step 5: polish

  • Add gr.Dropdown(["none", "sepia", "edges"]) for preset looks, using a dictionary of functions like STEPS above.
  • Add a download of the result, with gr.Image(format="png", show_download_button=True).
  • Use gr.State to keep the original so a Reset button can restore it, see the chat project for state patterns.
  • Test each filter on a 2 by 2 array with known results, as in testing.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why clamp pixel values?

    Arithmetic can push values out of the valid range, so clamp them.
  2. 2. What does a box blur compute for each pixel?

    Averaging a small window smooths sharp changes.
  3. 3. Why does filter order matter in a pipeline?

    Brighten then threshold gives a different result than threshold then brighten.
  4. 4. How can one event handler read many controls?

    The inputs list maps components to the function's parameters in order.

Summary

  • Filters are functions from image to image, so a pipeline is a loop over steps.
  • Clamp after arithmetic; neighbour-based filters (blur, edges) read nearby pixels.
  • One .change handler with all controls as inputs makes a live preview.
  • Resize large uploads and validate for None.

Next: Project: Chat Assistant with Memory