Seam Carving by Dynamic Programming

Python NumPy Numba JIT Dynamic Programming Image Processing

Goal

A content-aware image resizing engine that shrinks photos by one-pixel-wide "seams" at a time—removing the least informative content first—using an O(H·W) dynamic-programming shortest-path search per seam, with horizontal and vertical resizing and animated visualizations of the carving process.

Gyeongbokgung palace before and after vertical seam carving
Gyeongbokgung palace in Seoul: the original (left) versus the image after repeated vertical seam carving (right). Sky, mountains, and trees—large areas of low-gradient "filler" content—compress while the pavilion and bridge stay intact.

The Problem

Images are easy to bloat with pixels that carry very little information—regions of nearly uniform color like sky, water, or foliage. Naive uniform scaling distorts everything, and cropping throws away whole regions. The goal is to reduce an image's size without manual intervention, retaining the salient content.

Seam carving (also called "liquid rescaling") meets this by repeatedly excising a one-pixel-wide, top-to-bottom (or left-to-right) path of minimal information. The two key questions are:

Methodology

The pipeline has four stages: compute the energy matrix, find the minimum-energy seam by bottom-up DP tabulation, carve it out and stitch the image back together, and repeat. Horizontal carving reuses the vertical algorithm via a matrix transpose.

1. Energy Matrix

Each pixel's energy is the square root of the summed squared channel differences between its horizontal and vertical neighbors (a central-difference gradient magnitude). Boundary pixels are assigned a high energy (1000) so seams never run along the image border—the "frame" of the photo is always kept:

@timing
@numba.jit
def compute_energy(image: np.ndarray) -> np.ndarray:
    height, width, channels = image.shape
    energy = np.zeros((height, width))

    for r in range(height):
        for c in range(width):
            on_edge = (r == 0) or (r == height - 1) or (c == 0) or (c == width - 1)
            if on_edge:
                energy[r, c] = 1000.0   # boundary pixels: never carved
            else:
                sum_dy = 0.0  # squared diff along the row (y) axis
                sum_dx = 0.0  # squared diff along the column (x) axis
                for ch in range(channels):
                    sum_dy += (image[r-1, c, ch] - image[r+1, c, ch]) ** 2
                    sum_dx += (image[r, c-1, ch] - image[r, c+1, ch]) ** 2
                energy[r, c] = (sum_dx + sum_dy) ** 0.5

    return energy

2. Seam Finding by Bottom-Up DP Tabulation

Viewing pixels as vertices of a directed grid graph, the least-cumulative-energy (LCE) seam is a shortest path. We build two H×W tables from the bottom row upward: an LCE matrix (cheapest seam cost reaching each cell from the destination) and a predecessor Π matrix (which column the cost came from). Each cell takes the minimum of its three neighbors below, so every row is filled in one O(W) sweep. The seam is then traced out in O(H) by following Π back down from the minimum of the top row:

@numba.jit
def _find_vertical_seam_dp(energy: np.ndarray):
    height, width = energy.shape
    # lce[i, j]  = least cumulative energy of any seam reaching (i, j),
    #              built row by row from the top edge down
    # backtrack[i, j] = the column in row i-1 the optimal path to (i, j) came from
    lce = energy.copy()
    backtrack = np.zeros((height, width), dtype=np.int64)

    for i in range(1, height):
        for j in range(width):
            best, bi = lce[i-1, j], j                    # parent directly above
            if j > 0 and lce[i-1, j-1] <= best:          # above-left (<=: leftmost wins ties)
                best, bi = lce[i-1, j-1], j-1
            if j < width-1 and lce[i-1, j+1] < best:     # above-right
                best, bi = lce[i-1, j+1], j+1
            backtrack[i, j] = bi
            lce[i, j] = energy[i, j] + best

    # the optimal seam ends at the cheapest bottom-row column (leftmost on ties)
    j = 0
    for c in range(1, width):
        if lce[height-1, c] < lce[height-1, j]:
            j = c

    # walk the predecessor pointers back up to the top edge
    seam = np.empty(height, dtype=np.int64)
    seam[height-1] = j
    for r in range(height-1, 0, -1):
        j = backtrack[r, j]
        seam[r-1] = j
    return seam

A top-down recursive formulation with memoization works too, but carries needless call overhead; the bottom-up tabular form is the natural fit.

3. Carving, Stitching & Adaptive Stopping

Each found seam is masked out of the pixel array and the remaining rows are reassembled, producing an image exactly one column narrower (the animation below marks each seam in red before it is cut). A naive fixed seam count distorts images that simply lack removable content, so the carver adds an adaptive stopping rule: it computes each seam's mean energy relative to the image's mean energy, and stops once the next seam is no longer "low information" relative to the rest of the picture—protecting salient content even when many seams are requested.

4. Horizontal Carving & Vectorization

Complexity

Energy computation, the LCE/Π tabulation, and seam tracing are each O(H·W) or less, so one seam costs O(H·W) and carving n seams costs O(n·H·W)—linear in image size per pass, versus exponential for exhaustive path search.

Results

  • 4× faster energy computation with the single-line @numba.jit decorator, plus fully vectorized DP rows.
  • Generalizes well: the carver was exercised on 10+ diverse photos (palaces, coastlines, campus scenery, portraits, AI art), where it consistently compresses low-gradient backgrounds—sky, water, foliage—while keeping salient objects standing. Examples below.

Vertical seam carving on the Gyeongbokgung photo, one seam at a time. Each pass marks the minimum-energy seam in red, then stitches the image closed. Across 199 passes the photo narrows from 800px to 601px—sky, mountains, and foliage compress while the pavilion stays sharp.

Seam Carving in Action

The full pipeline on the Durdle Door coastline photo: the original, its energy map (bright = information-rich—the rock arch and headland light up while sea, sky, and beach go dark), and the results of carving 58 vertical seams and 92 horizontal seams.

Original Durdle Door image Energy matrix visualization After vertical seam carving After horizontal seam carving
Top row: original · energy matrix. Bottom row: after vertical carving (narrower, sky and sea compressed) · after horizontal carving (shorter, foreground compressed).

More Examples

Side-by-side results on other photos—the carver removes the "fat" (uniform sky, water, foliage) while subjects stay sharp.

Sunset photo before and after vertical seam carving
Sunset over water: the sky compresses while the horizon and foreground survive.
UMass Amherst campus photo before and after vertical seam carving
UMass Amherst campus in autumn: sky, street, and leaf scatter compress while the stone building, lamp post, and pedestrians hold their shape.
AI-generated scene before and after vertical and horizontal seam carving
AI-generated scene: combined vertical and horizontal carving resizes both dimensions at once, tightening the composition around the figures and the portal.