Flipping an Image in OpenCV

Flipping an image is a simple task in image processing, and OpenCV makes it easy to achieve. This guide will walk you through the basic steps to flip an image using OpenCV.

Installation

First, ensure you have OpenCV installed. You can install it using pip:

pip install opencv-python 

Loading an Image

To flip an image, you first need to load it. Use the cv2.imread function to read the image from a file.

import cv2 
# Load the image 
image = cv2.imread('path_to_your_image.jpg') 

Flipping the Image

OpenCV provides a function called cv2.flip to flip images. You can flip an image in three ways:

  • Vertically
  • Horizontally
  • Both vertically and horizontally
Vertical Flip

To flip the image vertically, use cv2.flip with the flip code 0.

# Flip the image vertically 
flipped_image_vertical = cv2.flip(image, 0) 
Horizontal Flip

To flip the image horizontally, use cv2.flip with the flip code 1.

# Flip the image horizontally 
flipped_image_horizontal = cv2.flip(image, 1) 
Both Vertical and Horizontal Flip

To flip the image both vertically and horizontally, use cv2.flip with the flip code -1.

# Flip the image both vertically and horizontally 
flipped_image_both = cv2.flip(image, -1) 

Displaying the Images

You can display the original and flipped images using cv2.imshow. This helps you see the result.

# Display the original image 
cv2.imshow('Original Image', image) 
# Display the vertically flipped image 
cv2.imshow('Vertically Flipped Image', flipped_image_vertical) 
# Display the horizontally flipped image 
cv2.imshow('Horizontally Flipped Image', flipped_image_horizontal) 
# Display the both flipped image cv2.imshow('Both Flipped Image', flipped_image_both) 
# Wait for a key press and close the windows 
cv2.waitKey(0) 
cv2.destroyAllWindows() 

Complete Code Example

Here’s the complete code to flip an image using OpenCV:

import cv2 
# Load the image 
image = cv2.imread('path_to_your_image.jpg') 
# Flip the image vertically 
flipped_image_vertical = cv2.flip(image, 0) 
# Flip the image horizontally 
flipped_image_horizontal = cv2.flip(image, 1) 
# Flip the image both vertically and horizontally 
flipped_image_both = cv2.flip(image, -1) 
# Display the original image 
cv2.imshow('Original Image', image) 
# Display the vertically flipped image 
cv2.imshow('Vertically Flipped Image', flipped_image_vertical) 
# Display the horizontally flipped image 
cv2.imshow('Horizontally Flipped Image', flipped_image_horizontal) 
# Display the both flipped image 
cv2.imshow('Both Flipped Image', flipped_image_both) 
# Wait for a key press and close the windows 
cv2.waitKey(0) 
cv2.destroyAllWindows() 

Leave a comment

Your email address will not be published. Required fields are marked *