PIXELBANKv9.1.0
Menu

Patchify an Image into Flattened Vectors

Problem Statement

Turn an image tensor into the flat matrix a patch-embedding Linear expects: one row per patch, each row the patch's pixels flattened in (channel, row, col) order.

Background

A ViT patch embedding is a linear projection applied to each non-overlapping patch. Concretely, an image of shape (C, H, W) split into p x p patches produces (H//p) * (W//p) patches, each flattened to a vector of length C * p * p. Patches are visited in row-major order (left to right, then top to bottom), and within a patch the flatten order is channel-major: all of channel 0's p*p values, then channel 1's, and so on.

Your Task

Implement:

def patchify(image, p):
  • image: nested list of shape (C, H, W).
  • Return a nested list of shape (num_patches, Cpp).

Input Format

  • image: (C, H, W) nested list of numbers; H and W are divisible by p.
  • p (int): patch edge.

Output Format

  • A nested list, num_patches rows in row-major patch order.

Sample

image = [[[1, 2], [3, 4]]]   # C=1, 2x2
print(patchify(image, 1))

Output:

[[1], [2], [3], [4]]

Example:

Input:
image = [[[1, 2], [3, 4]]]
print(patchify(image, 1))
Output:
[[1], [2], [3], [4]]
Reasoning:
  • The input image has shape (C,H,W)=(1,2,2)(C, H, W) = (1, 2, 2) with values [1234]\begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix}, and the patch size is p=1p=1. This divides the image into Hp×Wp=2×2=4\frac{H}{p} \times \frac{W}{p} = 2 \times 2 = 4 non-overlapping patches, each of size 1×11 \times 1.
  • Patches are extracted in row-major order (top-to-bottom, left-to-right). The first patch is at position (0,0)(0,0), containing the single pixel value 11.
  • Since p=1p=1 and C=1C=1, each patch flattens to a vector of length Câ‹…pâ‹…p=1â‹…1â‹…1=1C \cdot p \cdot p = 1 \cdot 1 \cdot 1 = 1. The first patch yields the vector [1][1].
  • The second patch is at position (0,1)(0,1), containing the pixel value 22, which flattens to the vector [2][2].
  • The third patch is at position (1,0)(1,0), containing the pixel value 33, which flattens to the vector [3][3].
  • The fourth and final patch is at position (1,1)(1,1), containing the pixel value 44, which flattens to the vector [4][4].
  • The final output is [[1], [2], [3], [4]]

Constraints:

  • 1 <= C <= 8, H, W divisible by p, up to 64.
  • Patch order is row-major; within a patch, channel-major then row then col.
  • Return ints/floats matching the input values.
🔒

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

0/0
Run code to see test results.
Patchify an Image into Flattened Vectors - Medium | PixelBank