← back

Flip an Image Horizontally or Vertically

#238 · Computer Vision · Easy

⊣ Solve on deep-ml.com

Problem

Flip an image either horizontally (left-right mirror) or vertically (top-bottom mirror).

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def flip_image(
    image: list[list[list[int]]],
    direction: str = "horizontal",
) -> list[list[list[int]]]:
    """
    image: [H, W, C]
    direction: 'horizontal' or 'vertical'
    """
    H = len(image)
    W = len(image[0])

    if direction == "horizontal":
        return [row[::-1] for row in image]
    elif direction == "vertical":
        return image[::-1]
    else:
        return [row[:] for row in image]

Explanation

  1. Horizontal flip: Reverse each row, mirroring the image left to right.
  2. Vertical flip: Reverse the order of rows, mirroring the image top to bottom.
  3. The operation preserves the number of channels (works for RGB, grayscale, or any channel count).

Complexity

  • Time: O(H * W) where H and W are image dimensions
  • Space: O(H * W) for the flipped image