PIXELBANKv9.1.0
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 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

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:
[[2.5, 2.5, 2.5, 2.5],
 [2.5, 2.5, 2.5, 2.5],
 [2.5, 2.5, 2.5, 2.5],
 [2.5, 2.5, 2.5, 2.5]]
Reasoning:

Step 1: Extract 2Γ—2 patches From 3Γ—3 image, we get 4 overlapping patches:

  • Patch 1 (top-left): [[1,2],[4,5]] β†’ flattened: [1,2,4,5]
  • Patch 2 (top-right): [[2,3],[5,6]] β†’ flattened: [2,3,5,6]
  • Patch 3 (bottom-left): [[4,5],[7,8]] β†’ flattened: [4,5,7,8]
  • Patch 4 (bottom-right): [[5,6],[8,9]] β†’ flattened: [5,6,8,9]

Step 2: Create data matrix X (4Γ—4) X=(1245235645785689)X = \begin{pmatrix} 1 & 2 & 4 & 5 \\ 2 & 3 & 5 & 6 \\ 4 & 5 & 7 & 8 \\ 5 & 6 & 8 & 9 \end{pmatrix}

Step 3: Compute mean and center Mean vector: [3, 4, 6, 7] Xc=Xβˆ’meanX_c = X - \text{mean}

Step 4: Compute covariance Ξ£=13XcTXc\Sigma = \frac{1}{3} X_c^T X_c

All entries are 2.5 due to the regular structure of this simple example.

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
solution.py

Test Results

0/0
Run code to see test results.
Covariance Matrix from Image Patches - Hard | PixelBank