v9.1.1
Menu

Intensity Coherence Segmentation

mediumPROGraphsGraphs, Matrix, DFS/BFSCV - DSA

A key challenge in low-level image processing is grouping pixels that are "locally coherent" based on their intensity values. This technique forms the basis of early segmentation methods like superpixels.

You are given a grayscale image represented by an M×NM \times N matrix where each cell contains a non-negative integer intensity value. Two pixels (r1,c1)(r_1, c_1) and (r2,c2)(r_2, c_2) are considered coherently connected if they are 4-directionally adjacent (horizontally or vertically) AND the absolute difference between their intensities is less than or equal to a threshold TT.

Your task is, given a starting pixel (r,c)(r, c), to find the size (total number of pixels) of the coherently connected region it belongs to. You should treat the image grid as an undirected graph where pixels are nodes and coherence defines the edges.

Implement Solution.coherenceSize(image, r_start, c_start, T): image is the M×NM \times N grid, the starting pixel is given as row r_start and column c_start (0-indexed), and T is the threshold. Return the region size as an integer.

Constraints:

  • The grid dimensions M×NM \times N are at most 50×5050 \times 50.
  • Intensity values ∈[0,255]\in [0, 255].
  • Threshold T∈[0,255]T \in [0, 255].

About Topic: This implementation models a simplified approach to bottom-up segmentation, where pixels are recursively grouped based on local similarity constraints (similarity/proximity) to form larger, meaningful regions, often preceding full object recognition.

Example

Input
image = [[6,7,8],[5,5,9],[1,2,3]]
start = (1, 1)
threshold = 3
Output
9
Reasoning
  • image is a 3×33 \times 3 intensity grid; the start (row 1, column 1, 0-indexed) has intensity 55, and T=3T = 3.
  • Neighbours of the start passing ∣Ia−Ib∣≤3|I_a - I_b| \le 3: up 77 (diff 22), left 55 (00), down 22 (33, on the threshold, so it counts). Right 99 fails: ∣5−9∣=4|5-9| = 4.
  • Growing from those: 7→67 \to 6, 7→87 \to 8, 2→12 \to 1, 2→32 \to 3 (each diff 11).
  • The 99 that the start rejected now joins through 88: ∣8−9∣=1≤3|8-9| = 1 \le 3.
  • Every one of the 3×3=93 \times 3 = 9 pixels is in the region, so the output is 9.
  • Notice coherence compares adjacent pixels, never the start: the region spans intensities 11 to 99 (range 8>T8 > T) because each step is small. With T=0T = 0 only the two 55s connect, giving 22.

More from CV - DSA

PRO

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

Sign in to run your code against the test cases.