The Wayback Machine - https://web.archive.org/web/20241119065301/https://www.geeksforgeeks.org/creating-hybrid-images-using-opencv-library-python/
Open In App

Creating Hybrid Images Using OpenCV Library | Python

Last Updated : 18 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Hybrid image, or "multi-scale image", is an exciting concept in computer vision. They are created by blending one image's high-frequency components with another's low-frequency components. The result is an image that appears as one when viewed from a distance but shows a different image when viewed up close.

The following are the steps for creating a hybrid image of two photos using OpenCV library in python:

  1. Find the fourier transformation of both the images and apply zero component center shifting.
  2. Extract the low frequency component and high frequency component from images.
  3. Get the image of low frequency and high frequency component using Inverse Fourier transformation.
  4. Combine the spatial domain of the low-pass filtered image and high-pass filtered image by adding their magnitudes elementwise.

Consider two images as shown below for the implementation:

cat
Cat.png


panda
Panda.png

Implementation: Creating Hybrid Images Using OpenCV Library

Import the necessary libraries

The code imports libraries for image processing including OpenCV (cv2), PIL (Image), NumPy, and matplotlib. It also imports the square root (sqrt) and exponential (exp) functions from the math module.

Python3
import cv2
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from math import sqrt, exp


Custom Function for Plotting Image

The code defines two custom functions:

  1. plot_figure: Plots a grid of images with corresponding titles, allowing customization of the figure size, number of rows, and columns.
  2. distance: Calculates the Euclidean distance between two points given as tuples of (x, y) coordinates.
Python3
#Custom Function for Image Plotting
def plot_figure(images: list, titles: list, rows: int, columns: int, fig_width=15, fig_height=7):
    fig = plt.figure(figsize=(fig_width, fig_height))
    count = 1
    for image, title in zip(images, titles):
        fig.add_subplot(rows, columns, count)
        count += 1
        plt.imshow(image, 'gray')
        plt.axis('off')
        plt.title(title)
 

#Custom Function to get Euclidean Distance
def distance(point1, point2):
    return sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2)


Extracting Low Frequency Component

The function creates a Gaussian low-pass filter to extract low-frequency components. The `D0` parameter determines the cutoff frequency of the filter, controlling which frequencies are considered low. It iterates over each pixel and calculates its value based on its distance from the center of the filter and the cutoff frequency `D0`. Pixels closer to the center and with lower frequencies will have higher values, emphasizing low-frequency content.

Python3
#Function to get low frequency component
#D0 is cutoff frequency
def gaussianLP(D0, imgShape):
    base = np.zeros(imgShape[:2])
    rows, cols = imgShape[:2]
    center = (rows/2, cols/2)
    for i in range(rows):
        for j in range(cols):
            base[i, j] = np.exp(-distance((i, j), center)**2 / (2 * D0**2))
    return base


Extracting High Frequency Component

The function creates a Gaussian high-pass filter to extract high-frequency components. The `D0` parameter determines the cutoff frequency of the filter, controlling which frequencies are considered high. It iterates over each pixel and calculates its value based on its distance from the center of the filter and the cutoff frequency `D0`. Pixels farther from the center and with higher frequencies will have higher values, emphasizing high-frequency content.

Python3
#Function to get high frequency component
#D0 is cutoff frequency
def gaussianHP(D0, imgShape):
    base = np.zeros(imgShape[:2])
    rows, cols = imgShape[:2]
    center = (rows/2, cols/2)
    for i in range(rows):
        for j in range(cols):
            base[i, j] = 1 - np.exp(-distance((i, j), center)**2 / (2 * D0**2))
    return base


Hybrid Image Function

The function returns a hybrid image from two input images. It separates the high and low-frequency components of each image using Fourier transforms and Gaussian filters. The low-frequency components of one image are combined with the high-frequency components of the other image. The `D0` parameter controls the amount of high-frequency information retained, affecting the clarity of the close-up image.

Python3
#Function to generate hybrid image
#D0 is cutoff frequency
def hybrid_images(image1, image2, D0 = 50):
    original1 = np.fft.fft2(image1)                          #Get the fourier of image1
    center1 = np.fft.fftshift(original1)                     #Apply Centre shifting
    LowPassCenter = center1 * gaussianLP(D0, image1.shape)   #Extract low frequency component
    LowPass = np.fft.ifftshift(LowPassCenter)                 
    inv_LowPass = np.fft.ifft2(LowPass)                         #Get image using Inverse FFT

    original2 = np.fft.fft2(image2)
    center2 = np.fft.fftshift(original2)
    HighPassCenter = center2 * gaussianHP(D0, image2.shape)  #Extract high frequency component
    HighPass = np.fft.ifftshift(HighPassCenter)
    inv_HighPass = np.fft.ifft2(HighPass)
    hybrid = np.abs(inv_LowPass) + np.abs(inv_HighPass)      #Generate the hybrid image
    return hybrid


Main Function

Python3
# Load images
# Make sure to choose the same image format for both images (Ex- .png)
A = cv2.imread('/content/cat.png',cv2.IMREAD_COLOR) # high picture
B = cv2.imread('/content/panda.png',cv2.IMREAD_COLOR) # low picture

# Convert both images to Grayscale to avoid any Color Channel Issue
A_grayscale = cv2.cvtColor(A, cv2.COLOR_BGR2GRAY)
B_grayscale = cv2.cvtColor(B, cv2.COLOR_BGR2GRAY)

# Resize both images to 128x128 to avoid different image size issue
A_resized = cv2.resize(A_grayscale, (128, 128))
B_resized = cv2.resize(B_grayscale, (128, 128))

result = hybrid_images(A_resized,B_resized,1)

plot_figure([A,B,result], ['A','B','Hybrid Image'],1,3)


Output:

Image_gfg-(1)




Similar Reads

Arithmetic Operations on Images using OpenCV | Set-2 (Bitwise Operations on Binary Images)
Prerequisite: Arithmetic Operations on Images | Set-1Bitwise operations are used in image manipulation and used for extracting essential parts in the image. In this article, Bitwise operations used are : ANDORXORNOT Also, Bitwise operations helps in image masking. Image creation can be enabled with the help of these operations. These operations can
4 min read
Top Books for Learning OpenCV: Computer Vision with OpenCV Library
OpenCV or Open Source Computer Vision Library, is an open-source computer vision and machine learning software library. It's extensively used for real-time computer vision tasks such as object detection, face recognition, image processing, etc. Whether you're a beginner or an experienced developer looking to deepen your understanding of OpenCV, her
5 min read
Python | Create video using multiple images using OpenCV
Creating videos from multiple images is a great way for creating time-lapse videos. In this tutorial, we’ll explore how to create a video from multiple images using Python and OpenCV. Creating a video from images involves combining multiple image frames, each captured at a specific moment in time, into a single video file. This process requires: St
5 min read
Addition and Blending of images using OpenCV in Python
When we talk about images, we know its all about the matrix either binary image(0, 1), gray scale image(0-255) or RGB image(255 255 255). So additions of the image is adding the numbers of two matrices. In OpenCV, we have a command cv2.add() to add the images. Below is code for Addition of two images using OpenCV : # Python program for adding # ima
2 min read
Python | Denoising of colored images using opencv
Denoising of an image refers to the process of reconstruction of a signal from noisy images. Denoising is done to remove unwanted noise from image to analyze it in better form. It refers to one of the major pre-processing steps. There are four functions in opencv which is used for denoising of different images. Syntax: cv2.fastNlMeansDenoisingColor
1 min read
How to Detect Shapes in Images in Python using OpenCV?
Prerequisites: OpenCV OpenCV is an open source library used mainly for processing images and videos to identify shapes, objects, text etc. It is mostly used with python. In this article we are going to see how to detect shapes in image. For this we need cv2.findContours() function of OpenCV, and also we are going to use cv2.drawContours() function
3 min read
How to subtract two images using Python-OpenCV ?
In this article, we are going to see how to subtract two images using OpenCV in Python. Now, before getting into the topic we shall discuss some of the use cases of Arithmetic operations. Arithmetic operations like addition and subtraction can help us to make images brighter or darker. Specifically, subtraction of two images has a lot of purposes i
3 min read
Drawing with Mouse on Images using Python-OpenCV
OpenCV is a huge open-source library for computer vision, machine learning, and image processing. OpenCV supports a wide variety of programming languages like Python, C++, Java, etc. It can process images and videos to identify objects, faces, or even the handwriting of a human. In this article, we will try to draw on images with the help of the mo
3 min read
Measure similarity between images using Python-OpenCV
Prerequisites: Python OpenCVSuppose we have two data images and a test image. Let's find out which data image is more similar to the test image using python and OpenCV library in Python.Let's first load the image and find out the histogram of images.Importing library import cv2 Importing image data image = cv2.imread('test.jpg') Converting to gray
2 min read
How to Display Multiple Images in One Window using OpenCV Python?
Prerequisites: Opencv In this article, we will show how to display Multiple Images In One window using OpenCV in Python. Approach Import moduleLoad the Multiple images using cv2.imread()Concatenate the images using concatenate(), with axis value provided as per orientation requirementDisplay all the images using cv2.imshow()Wait for keyboard button
1 min read
Concatenate images using OpenCV in Python
To concatenate images vertically and horizontally with Python, cv2 library comes with two functions as: hconcat(): It is used as cv2.hconcat() to concatenate images horizontally. Here h means horizontal.vconcat(): It is used as cv2.vconcat() to concatenate images vertically. Here v means vertical.Implementation using hconcat() and vconcat() on Arra
3 min read
Adding borders to the images using Python - OpenCV
Image processing is an interesting field in today's era of Artificial Intelligence and Machine Learning. We can see the applications of image processing in our day-to-day life, like whenever we apply filter over any image (selfie) or when we want to apply some effect like blurring the image, etc. In this article, we will discuss how to add borders
1 min read
Cropping Faces from Images using OpenCV - Python
Opencv is a python library mainly used for image processing and computer vision. In this article first, we detect faces after that we crop the face from the image. Face detection is the branch of image processing that uses to detect faces. We will use a pre-trained Haar Cascade model to detect faces from the image. A haar cascade is the object dete
3 min read
How to Blur Faces in Images using OpenCV in Python?
Prerequisite: OpenCV OpenCV is a huge open-source library for computer vision, machine learning, and image processing. It can process images and videos to identify objects, faces, or even the handwriting of a human. When it is integrated with various libraries, such as Numpy which is a highly optimized library for numerical operations, then the num
2 min read
Color Identification in Images using Python - OpenCV
An open-source library in Python, OpenCV is basically used for image and video processing. Not only supported by any system, such as Windows, Linux, Mac, etc. but also it can be run in any programming language like Python, C++, Java, etc. OpenCV also allows you to identify color in images. Don’t you know how to find these colors in images? Color Re
3 min read
Resize Multiple Images using OpenCV-Python
In this article, we are going to write a python script using the OpenCV library to Resize Multiple Images and save them as an image file. Resizing the image refers to the growth of the images. Measurement works best in the use of multiple images and in machine learning applications. It helps to reduce the number of pixels from an image and that has
2 min read
Dividing Images Into Equal Parts Using OpenCV In Python
In this article, we are going to see how to divide images into equal parts using OpenCV in Python. We are familiar with python lists and list slicing in one dimension. But here in the case of images, we will be using 2D list comprehension since images are a 2D matrix of pixel intensity. Image Used: C/C++ Code import cv2 img = cv2.imread('img.jpg')
3 min read
Python - Process images of a video using OpenCV
Processing a video means, performing operations on the video frame by frame. Frames are nothing but just the particular instance of the video in a single point of time. We may have multiple frames even in a single second. Frames can be treated as similar to an image.So, whatever operations we can perform on images can be performed on frames as well
4 min read
Python | Grayscaling of Images using OpenCV
Grayscaling is the process of converting an image from other color spaces e.g. RGB, CMYK, HSV, etc. to shades of gray. It varies between complete black and complete white. Importance of grayscaling Dimension reduction: For example, In RGB images there are three color channels and three dimensions while grayscale images are single-dimensional.Reduce
5 min read
Creating a Finger Counter Using Computer Vision and OpenCv in Python
In this article, we are going to create a finger counter using Computer Vision, OpenCv in Python Required Libraries:OpenCV: OpenCV is a widely used library for image processing.cvzone: It is a computer vision package that makes it easy to run Image processing and AI functions To install the Cvzone, run this command into terminal: pip install cvzone
4 min read
OpenCV - Facial Landmarks and Face Detection using dlib and OpenCV
Content has been removed on Author's request.
1 min read
Automatic Document Scanner using OpenCV (OpenCV Document Scanner)
An automatic document scanner using OpenCV is a computer vision application that automatically detects and extracts documents from images. This type of scanner can be useful in various scenarios, such as digitizing paper documents, processing scanned documents, or automating document recognition tasks. In this article, we will see how we can build
6 min read
Draw geometric shapes on images using OpenCV
OpenCV provides many drawing functions to draw geometric shapes and write text on images. Let's see some of the drawing functions and draw geometric shapes on images using OpenCV. Some of the drawing functions are : cv2.line() : Used to draw line on an image. cv2.rectangle() : Used to draw rectangle on an image. cv2.circle() : Used to draw circle o
3 min read
Arithmetic Operations on Images using OpenCV | Set-1 (Addition and Subtraction)
Arithmetic Operations like Addition, Subtraction, and Bitwise Operations(AND, OR, NOT, XOR) can be applied to the input images. These operations can be helpful in enhancing the properties of the input images. The Image arithmetics are important for analyzing the input image properties. The operated images can be further used as an enhanced input im
3 min read
Python OpenCV - Depth map from Stereo Images
OpenCV is the huge open-source library for the computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems.Note: For more information, refer to Introduction to OpenCV Depth Map : A depth map is a picture where every pixel has depth information(rather than RG
2 min read
Watermarking images with OpenCV and Python
In this article, we are going to see how to make watermarking images using OpenCV in Python. Watermark is intentionally left Text/Logo onto the image. Watermarks are generally used by artists to protect the copyright of the image. Using watermarks we can ensure that the owner of the image is the person who imprinted the watermark on the image. Let'
4 min read
Detecting low contrast images with OpenCV, scikit-image, and Python
In this article, we are going to see how to detect low contrast images with OpenCV, scikit-image using Python A low contrast image has the minimal distinction between light and dark parts, making it difficult to tell where an object's boundary begins and the scene's background begins. For example The left one is low contrast and the right one is a
2 min read
Creating Instagram Filters With OpenCV and Python
Social and Photography apps such as Instagram, Canva, Snapchat, Picsart, etc. provide a bunch of filters to apply to our portraits and allow us to stylize them according to our choices and needs. An Image filter is a process of modifying an existing image by changing color, hue, sharpness, shade, and other characteristics according to our choice. I
6 min read
NLP Primitives Library: A Powerful Python Library for Natural Language Processing
Natural Language Processing (NLP) is a rapidly evolving field, pivotal in applications like sentiment analysis, chatbots, machine translation, and more. However, building robust NLP models often requires intricate text preprocessing and feature engineering. Enter the NLP Primitives Library—a powerful Python library designed to simplify and accelera
7 min read
Transition from OpenCV 2 to OpenCV 3.x
OpenCV is one of the most popular and most used Computer vision libraries. It contains tools to carry out image and video processing. When OpenCV 3..4.1 is an improved version of OpenCV 2.4 as it introduced new algorithms and features. Although some of the existing modules were rewritten and moved to sub-modules. In this articles, I will focus on t
2 min read
three90RightbarBannerImg