v9.1.1
Menu

Sparse Matrix Operations for Images

mediumFREENotationData StructuresCV: Introduction to Computer Vision

Implement sparse matrix operations for efficient image processing, in plain Python.

Many image operations produce sparse results (few non-zero values). Sparse representation saves memory and speeds up computation.

Sparse format (COO - Coordinate format):

  • Store only (row, col, value) for non-zero entries
  • Memory: O(nnz) instead of O(m×n)

Common sparse operations:

  • Conversion: dense ↔ sparse
  • Matrix-vector multiplication
  • Element access and modification

Output format (what the tests check):

  • to_sparse returns a tuple of three Python lists (rows, cols, values), with entries listed in row-major order (row by row, left to right within a row)
  • from_sparse returns a list of lists of size shape; positions not in the sparse lists hold the integer 0
  • sparse_multiply returns a Python list of length shape[0]

Applications in CV:

  • Graph-based segmentation (sparse affinity matrices)
  • Optical flow (sparse motion fields)
  • Feature matching (sparse correspondence matrices)

Example

Input
matrix = [[0, 0, 3],
          [0, 2, 0],
          [1, 0, 0]]
Output
rows=[0,1,2], cols=[2,1,0], values=[3,2,1]
Reasoning
  • Input: matrix is a 3×33 \times 3 grid, a tiny mostly-black image: 9 entries, only 3 non-zero.
  • Row by row, left to right: row 0 has a 33 in column 2, row 1 a 22 in column 1, row 2 a 11 in column 0. Each becomes a triple (r,c,v)(r, c, v): (0,2,3)(0,2,3), (1,1,2)(1,1,2), (2,0,1)(2,0,1).
  • Output: the triples split into three parallel lists, rows=[0,1,2], cols=[2,1,0], values=[3,2,1]; position kk in each list describes the same entry. Storage is 3⋅nnz3 \cdot \text{nnz} numbers instead of m×nm \times n, a big saving for large, mostly-zero images.
  • Going back: with shape (3,3)(3, 3), start from all zeros and put each vv at row rr, column cc; the original grid reappears.
  • Times a vector: yr=∑v xcy_r = \sum v \, x_c over the triples in row rr. With x=[1,2,3]x = [1, 2, 3]: y0=3⋅3=9y_0 = 3 \cdot 3 = 9, y1=2⋅2=4y_1 = 2 \cdot 2 = 4, y2=1⋅1=1y_2 = 1 \cdot 1 = 1, so y=[9,4,1]y = [9, 4, 1]. Notice that zeros never contribute, so only stored entries matter.

Constraints

  • Implement: to_sparse(), from_sparse(), sparse_multiply()
  • to_sparse: Returns (rows, cols, values) for non-zero entries
  • from_sparse: Reconstructs dense matrix from sparse format
  • sparse_multiply: Sparse matrix × dense vector

More from CV: Introduction to Computer Vision

solution.py

Test results

Sign in to run your code against the test cases.