Seam Carving by Dynamic Programming
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.
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:
- How do we measure a pixel's information content? A pixel that barely differs from its neighbors is uninformative. We define energy as the magnitude of the pixel's gradient across color channels—edges, where change is abrupt, are information-rich and are preserved.
- How do we find the cheapest path through the grid efficiently? A brute-force search over paths is exponential. But the cheapest seam has optimal substructure: the cheapest seam through a cell must pass through the cheapest seam through one of the three cells adjacent below it. That is exactly the setting for dynamic programming.
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
- Transpose trick: a horizontal seam is a vertical seam of the transposed matrix, so
find_horizontal_seamis a one-liner delegating to the vertical DP—no duplicated logic. - 4× speedup from one line: adding the
@numba.jitdecorator JIT-compiled the Python loops and cut the energy-matrix time by a factor of four with no algorithmic change. - Vectorized DP: the final seam finder replaces the inner per-column loop with NumPy array ops—padding each row with ∞, comparing the left/center/right shifted copies, and taking a vectorized
argmin—so each DP row is a few fused array operations instead of W Python iterations.
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.jitdecorator, 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.
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.
More Examples
Side-by-side results on other photos—the carver removes the "fat" (uniform sky, water, foliage) while subjects stay sharp.