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
image = [[[1, 2], [3, 4]]] print(patchify(image, 1))
[[1], [2], [3], [4]]
- The input image has shape with values , and the patch size is . This divides the image into non-overlapping patches, each of size .
- Patches are extracted in row-major order (top-to-bottom, left-to-right). The first patch is at position , containing the single pixel value .
- Since and , each patch flattens to a vector of length . The first patch yields the vector .
- The second patch is at position , containing the pixel value , which flattens to the vector .
- The third patch is at position , containing the pixel value , which flattens to the vector .
- The fourth and final patch is at position , containing the pixel value , which flattens to the vector .
- The final output is
[[1], [2], [3], [4]]
Constraints
1 <= C <= 8,H, Wdivisible byp, up to 64.- Patch order is row-major; within a patch, channel-major then row then col.
- Return ints/floats matching the input values.