v9.1.1
Menu

Covariance Matrix from Image Patches

Compute the covariance matrix of image patches for PCA-based texture analysis.

Given an image and patch size, extract all overlapping patches, flatten them to vectors, and compute the covariance matrix. This is a fundamental step in texture analysis and eigenface computation.

Algorithm:

  1. Extract all overlapping patches of size p×pp \times p from the image
  2. Flatten each patch (row by row) into a vector of length p2p^2
  3. Stack vectors as rows of data matrix XX (shape: n_patches × p²)
  4. Center the data: Xc=X−XˉX_c = X - \bar{X} (subtract mean vector)
  5. Compute covariance: Σ=1n−1XcTXc\Sigma = \frac{1}{n-1} X_c^T X_c

If there is only one patch (n=1n = 1), return a p2×p2p^2 \times p^2 matrix of zeros.

The covariance matrix Σ\Sigma captures correlations between pixel positions within patches.

Applications:

  • PCA for dimensionality reduction
  • Eigenface/Fisherface recognition
  • Texture synthesis and analysis

Example

Input
image = [[1, 2, 3],
         [4, 5, 6],
         [7, 8, 9]]
patch_size = 2
Output
[[3.3333, 3.3333, 3.3333, 3.3333],
 [3.3333, 3.3333, 3.3333, 3.3333],
 [3.3333, 3.3333, 3.3333, 3.3333],
 [3.3333, 3.3333, 3.3333, 3.3333]]
Reasoning
  • Input: a 3×33 \times 3 grayscale image and p=2p = 2. A 2×22 \times 2 window fits in 3−2+1=23 - 2 + 1 = 2 positions down and 2 across, so there are n=4n = 4 overlapping patches.
  • Patches as vectors: reading each window row by row gives (1,2,4,5)(1,2,4,5), (2,3,5,6)(2,3,5,6), (4,5,7,8)(4,5,7,8) and (5,6,8,9)(5,6,8,9). These are the 4 rows of XX, which is 4×44 \times 4 because p2=4p^2 = 4.
  • Centering: the mean of each column (pixel position) is (3,4,6,7)(3, 4, 6, 7). Subtracting it, every column of XcX_c becomes (−2,−1,1,2)T(-2, -1, 1, 2)^T.
  • Covariance: entry Σij\Sigma_{ij} is the dot product of centred columns ii and jj, divided by n−1=3n - 1 = 3: (−2)2+(−1)2+12+223=103≈3.3333\frac{(-2)^2 + (-1)^2 + 1^2 + 2^2}{3} = \frac{10}{3} \approx 3.3333 for every i,ji, j.
  • Output: a p2×p2=4×4p^2 \times p^2 = 4 \times 4 symmetric matrix, rounded to 4 decimal places. Notice it is constant: in this linear ramp all four pixel positions rise and fall together, so every variance equals every covariance.

Constraints

  • image: 2D numpy array (grayscale)
  • patch_size: integer p (patches are p×p)
  • Return: covariance matrix of shape (p², p²)
  • Round to 4 decimal places

Learn this in

More from CV: Mathematical Foundations

solution.py

Test results

Sign in to run your code against the test cases.