PIXELBANKv9.1.0
Menu

Contour Smoothing via Dynamic Programming (1D)

Problem Statement

Active Contour Models (Snakes) or Dynamic Time Warping techniques often use Dynamic Programming (DP) to minimize an energy function across a sequence of points. This is equivalent to finding the minimum cost path in a chain graph.

Problem Setup

We consider a simplified 1D contour segmentation problem represented by a chain of pixels w1,w2,…,wnw_1, w_2, \ldots, w_n, where wn∈{āˆ’1,0,1}w_n \in \{-1, 0, 1\} represents the relative vertical shift of the contour at position nn.

The total cost SS of a contour assignment ww is:

S(w)=āˆ‘nUn(wn)+āˆ‘nPn,nāˆ’1(wn,wnāˆ’1)S(w) = \sum_n U_n(w_n) + \sum_n P_{n,n-1}(w_n, w_{n-1})

where:

  • UnU_n is the unary cost (e.g., closeness to an edge/data likelihood)
  • Pn,nāˆ’1P_{n,n-1} is the pairwise cost (smoothness)

Your Task

Implement the core recurrence relation of the DP solution (Viterbi algorithm) to find the minimum cumulative cost Sn,kS_{n,k} of reaching pixel nn with label kk:

Sn,k=Un(wn=k)+min⁔l[Snāˆ’1,l+Pn,nāˆ’1(wn=k,wnāˆ’1=l)]S_{n,k} = U_n(w_n = k) + \min_l [S_{n-1,l} + P_{n,n-1}(w_n = k, w_{n-1} = l)]

Given the cumulative costs Snāˆ’1S_{n-1} for the previous column and the costs UnU_n, calculate the minimum cumulative costs SnS_n for the current column.

Pairwise Cost

The smoothness cost Pn,nāˆ’1P_{n,n-1} is defined by the ℓ₁ norm (Manhattan distance) between adjacent labels:

Pn,nāˆ’1(k,l)=∣kāˆ’l∣P_{n,n-1}(k, l) = |k - l|

Example:

Input:
Unary: [2.0, 1.0, 5.0], Cumulative: [3.0, 2.0, 4.0]
Output:
[5.000, 3.000, 8.000]
Reasoning:
  • For each target label k:

  • Sā‚™(-1) = U(-1) + min{S_{n-1}(-1)+0, S_{n-1}(0)+1, S_{n-1}(1)+2}

    • = 2.0 + min{3.0, 3.0, 6.0} = 2.0 + 3.0 = 5.0
  • Sā‚™(0) = U(0) + min{S_{n-1}(-1)+1, S_{n-1}(0)+0, S_{n-1}(1)+1}

    • = 1.0 + min{4.0, 2.0, 5.0} = 1.0 + 2.0 = 3.0
  • Sā‚™(1) = U(1) + min{S_{n-1}(-1)+2, S_{n-1}(0)+1, S_{n-1}(1)+0}

    • = 5.0 + min{5.0, 3.0, 4.0} = 5.0 + 3.0 = 8.0

Constraints:

  • The possible labels are k ∈ {-1, 0, 1}
  • The smoothness cost P_{n,n-1} is defined by |k - l|
  • Uā‚™ and S_{n-1} are provided as lists indexed by [-1, 0, 1]
  • Output costs must be rounded to 3 decimal places
šŸ”’

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Contour Smoothing via Dynamic Programming (1D) - Medium | PixelBank