#133Flatten an image into a feature vectorEasy

Flatten an image into a feature vector

Background

The simplest (if crude) way to feed an image to a dense MLP is to flatten it into a 1-D vector. A 28×28 grayscale image becomes 784 features; an (H, W, C) image becomes HWCH\cdot W\cdot C features, read in row-major order.

Problem statement

Implement flatten_image(img) returning the image as a 1-D np.ndarray.

Input

  • img — array-like of shape (H, W) or (H, W, C).

Output

Returns a 1-D np.ndarray of length equal to the number of values in img.

Examples

Example 1 — grayscale

Input:  img = [[1, 2], [3, 4]]
Output: [1 2 3 4]

Example 2 — RGB pixel order (row-major)

Input:  img = [[[1, 2, 3], [4, 5, 6]]]
Output: [1 2 3 4 5 6]

Constraints

  • Flatten in row-major (C) order — the NumPy default.
  • Return a 1-D array.

Notes

  • This is the input a plain MLP would see. It works, but it throws away the 2-D layout, so the model has no built-in notion that neighbouring pixels are related — a key motivation for CNNs.
Python
Loading...

▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.

  • example grayscale 2x2
  • reference rgb row-major
  • sample 3x1 column