Images as Linear AlgebraMedium
Extract Sliding Patches (im2col)
~18 mincode completion
Implement im2col(image, kernel_h, kernel_w) returning a 2D array of shape (out_h * out_w, kernel_h * kernel_w).
Examples
3x3 image, 2x2 windows: four rows in reading order
- Input
- im2col([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 2, 2)
- Output
- [[1, 2, 4, 5], [2, 3, 5, 6], [4, 5, 7, 8], [5, 6, 8, 9]]
Full-image 3x3 window is one flattened row
- Input
- im2col([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3, 3)
- Output
- [[1, 2, 3, 4, 5, 6, 7, 8, 9]]
Hints
Hint 1
Build the result up as you go, then return it.
Hint 2
Watch for this: flattened windows column major.
Requirements
image: (H, W) arraykernel_h: window heightkernel_w: window width
Constraints
Allowed library: NumPy only
Time limit: 200 ms, Memory: 64 MB
Where this shows up
~18 min
••••••••••••••••
8 employers weight this skill
4 autonomy companies, 1 defense company, 1 health and bio company, 1 enterprise vendor, 1 AI product company. Top match scores 92.
Python
import numpy as np
def im2col(image, kernel_h, kernel_w):
"""
Stack every valid kernel_h x kernel_w window as a row.
Args:
image: (H, W) array
kernel_h: window height
kernel_w: window width
Returns:
(out_h * out_w, kernel_h * kernel_w) array, windows in
row-major order, each window flattened row-major.
"""
# YOUR CODE HERE
pass