v9.1.1
Menu

SAD Block Matching Cost

mediumPROStereo MatchingStereoCV: Depth Estimation

Compute the Sum of Absolute Differences (SAD) between two image blocks.

SAD is a simple and efficient matching cost used in stereo correspondence:

SAD=∑i,j∣L(i,j)−R(i,j)∣SAD = \sum_{i,j} |L(i,j) - R(i,j)|

where LL and RR are corresponding blocks from the left and right images.

Properties of SAD:

  • Fast to compute (no multiplications)
  • Robust to small intensity differences
  • Lower values indicate better matches
  • Often used with block sizes like 5×5, 7×7, or 9×9

SAD is the simplest block matching metric. SSD (sum of squared differences) and NCC (normalized cross-correlation) are more robust alternatives.

Example

Input
sad([[1,2],[3,4]], [[1,2],[3,4]])
Output
0
Reasoning
  • Inputs: block_left and block_right are two 2×22 \times 2 patches of pixel intensities, one from each image of a stereo pair. Pixel (i,j)(i, j) of one is compared with pixel (i,j)(i, j) of the other.
  • Left block: L=[1234]L = \begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix}. Right block: R=[1234]R = \begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix}.
  • Per-pixel differences: ∣1−1∣=0|1-1| = 0, ∣2−2∣=0|2-2| = 0, ∣3−3∣=0|3-3| = 0, ∣4−4∣=0|4-4| = 0. The absolute value makes too dark and too bright cost the same.
  • Sum: SAD=0+0+0+0=0SAD = 0 + 0 + 0 + 0 = 0, so the output is 0.
  • Output: a single integer, the total mismatch over all four pixels. Zero is the minimum: a perfect match.
  • Notice that the cost counts every unit of disagreement: if every right pixel were 1 brighter than its left partner (say left 10,20,30,4010, 20, 30, 40 and right 11,21,31,4111, 21, 31, 41), SAD would be 1+1+1+1=41+1+1+1 = 4 even though the patterns look alike.

Constraints

  • block_left: 2D array representing a patch from the left image
  • block_right: 2D array of same size from the right image
  • Return the SAD value (integer)

Learn this in

More from CV: Depth Estimation

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.