Flip an Image Horizontally or Vertically

Easy
Computer Vision

Task: Image Flipping

Image flipping is a fundamental operation in computer vision, commonly used for data augmentation in deep learning. In this task, you will implement a function flip_image(image, direction) that flips an image either horizontally (left-right) or vertically (top-bottom).

Input:

  • image: A 2D list/array (grayscale) or 3D list/array (RGB/color) representing an image
  • direction: A string specifying the flip direction - either 'horizontal' or 'vertical'

Output:

  • Return the flipped image as a nested list
  • Return -1 for invalid inputs

Edge Cases to Handle:

  • Input is not a valid 2D or 3D array
  • Empty image dimensions
  • Invalid direction string (anything other than 'horizontal' or 'vertical')

Examples

Example 1:
Input: image = [[1, 2, 3], [4, 5, 6]] print(flip_image(image, 'horizontal'))
Output: [[3, 2, 1], [6, 5, 4]]
Explanation: For a horizontal flip, each row is reversed. The original image has two rows: [1, 2, 3] and [4, 5, 6]. After horizontal flipping, each row is reversed to [3, 2, 1] and [6, 5, 4] respectively.

Starter Code

import numpy as np

def flip_image(image, direction):
    """
    Flip an image horizontally or vertically.
    
    Args:
        image: 2D or 3D list/array representing a grayscale or RGB image
        direction: string, either 'horizontal' or 'vertical'
    
    Returns:
        Flipped image as a nested list, or -1 if input is invalid
    """
    # Your code here
    pass
Lines: 1Characters: 0
Ready
The AI Interview - Master AI/ML Interviews