Cut an image into flattened patches for a vision transformer
A vision transformer treats an image as a sequence of tokens. Step one is to cut it into non-overlapping P x P squares and flatten each square into a vector.
Write patchify(img, P). img has shape (H, W, C) and H and W are multiples of P. Return an array of shape (H/P * W/P, P*P*C):
- patches are ordered row by row across the image (left to right, then down),
- inside a patch, values are flattened in (row, column, channel) order.
def patchify(img, P)Example
a 4x4x1 image np.arange(16).reshape(4, 4, 1) with P = 2 gives first patch [0, 1, 4, 5] and second patch [2, 3, 6, 7].
Understand the idea
A vision transformer reads an image like a sentence, where each word is a small square patch. You cut the image into a grid of non-overlapping P x P squares and flatten each square into one vector. The tricky part is ordering: patches go left to right, then top to bottom, and values inside a patch go row, then column, then channel. Worked example: a 4x4 single channel image holding 0 to 15 in raster order, P = 2. The grid is 2x2 patches. Patch 0 (top left) is [0, 1, 4, 5], patch 1 (top right) is [2, 3, 6, 7], patch 2 (bottom left) is [8, 9, 12, 13], patch 3 is [10, 11, 14, 15]. With 2 channels each pixel contributes its 2 values back to back. Rule: view (H, W, C) as (H/P, P, W/P, P, C), move the two grid axes to the front, then flatten to (num_patches, P * P * C). A plain reshape of the raster order gives strips of one row, not squares. This is the first step of every ViT and of CLIP's image encoder.