v9.1.1
Menu

Merge Similar Pixels

mediumPROUnion-FindUnion-Find, SimilarityCV - DSA

Problem Statement

In image segmentation, adjacent pixels with similar intensities are often merged into the same region.

Given a list of pixel values and a list of edges (i, j) indicating which pixels are adjacent, merge pixels into groups where the absolute intensity difference is at most threshold.

Return the number of distinct groups after merging.

Applications

  • Region-based segmentation
  • Color quantization
  • Superpixel generation

Constraints

  • 1≤len(pixels)≤10001 \leq len(pixels) \leq 1000
  • 0≤pixels[i]≤2550 \leq pixels[i] \leq 255
  • 0≤threshold≤2550 \leq threshold \leq 255

Example

Input
pixels = [10, 12, 50, 52], edges = [[0,1], [1,2], [2,3]], threshold = 5
Output
2
Reasoning
  • Inputs: pixels holds 4 intensities, p=(10,12,50,52)p = (10, 12, 50, 52), indexed 0 to 3. edges lists which pixels touch: 0–1, 1–2 and 2–3, a simple chain. threshold =5= 5 is the largest intensity gap that still counts as "similar".
  • Which edges qualify: an edge (i,j)(i, j) merges its pixels only when ∣pi−pj∣≤5|p_i - p_j| \le 5.
    • 0–1: ∣10−12∣=2≤5|10 - 12| = 2 \le 5, merge.
    • 1–2: ∣12−50∣=38>5|12 - 50| = 38 > 5, no merge, even though the pixels are adjacent.
    • 2–3: ∣50−52∣=2≤5|50 - 52| = 2 \le 5, merge.
  • Resulting groups: {0,1}\{0, 1\} (the dark region) and {2,3}\{2, 3\} (the brighter region), so the output is 2.
  • Notice that merging is transitive along qualifying edges: with intensities 10,12,1410, 12, 14 chained by edges and a threshold of 22, all three pixels form one group, even though ∣10−14∣=4|10 - 14| = 4. A pixel with no qualifying edge stays a group of its own.

Learn this in

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.