The Wayback Machine - https://web.archive.org/web/20240605111227/https://www.geeksforgeeks.org/histogram-matching-with-opencv-scikit-image-and-python/
Open In App

Histogram matching with OpenCV, scikit-image, and Python

Last Updated : 03 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Histogram matching is used for normalizing the representation of images, it can be used for feature matching, especially when the pictures are from diverse sources or under varied conditions (depending on the light, etc). each image has a number of channels, each channel is matched individually. Histogram matching is possible only if the number of channels matches in the input and reference images.

The main target of histogram matching is:

  • For each image, we need to create histograms.
  • Take a look at the histogram of the reference image.
  • Using the reference histogram, update the pixel intensity values in the input picture such that they match.

match_histograms() method:

This method is used to modify the cumulative histogram of one picture to match the histogram of another. For each channel, the modification is made independently.

Syntax: skimage.exposure.match_histograms(image, reference, *, channel_axis=None, multichannel=False)

Parameters:

  • image: ndarray. This parameter is our input image it can be grayscale or a colour image.
  • reference: reference image. reference image to match histograms.
  • channel_axis: optional parameter. int or None. If None is specified, the picture will be presumed to be grayscale (single channel). if not, this argument specifies the array axis that corresponds to channels.
  • multichannel: optional parameter. boolean value. Matching should be done independently for each channel. This option has been deprecated; instead, use the channel axis.

Example 1: Using OpenCV and scikit-image.

The code begins with importing the necessary packages, reading images using the OpenCV imread() method, and then we check the number of channels of the input image and reference image, if they don’t match we cannot perform histogram matching. match_histograms is used to find the matched image. Histograms are plotted for each channel.

Python3




# import packages
import matplotlib.pyplot as plt
from skimage import exposure
from skimage.exposure import match_histograms
import cv2
  
# reading main image
img1 = cv2.imread("img.jpeg")
  
# checking the number of channels
print('No of Channel is: ' + str(img1.ndim))
  
# reading reference image
img2 = cv2.imread("2Fw13.jpeg")
  
# checking the number of channels
print('No of Channel is: ' + str(img2.ndim))
  
image = img1
reference = img2
  
matched = match_histograms(image, reference ,
                           multichannel=True)
  
  
fig, (ax1, ax2, ax3) = plt.subplots(nrows=1, ncols=3, 
                                    figsize=(8, 3),
                                    sharex=True, sharey=True)
  
for aa in (ax1, ax2, ax3):
    aa.set_axis_off()
  
ax1.imshow(image)
ax1.set_title('Source')
ax2.imshow(reference)
ax2.set_title('Reference')
ax3.imshow(matched)
ax3.set_title('Matched')
  
plt.tight_layout()
plt.show()
  
fig, axes = plt.subplots(nrows=3, ncols=3, figsize=(8, 8))
  
for i, img in enumerate((image, reference, matched)):
    for c, c_color in enumerate(('red', 'green', 'blue')):
        img_hist, bins = exposure.histogram(img[..., c], 
                                            source_range='dtype')
        axes[c, i].plot(bins, img_hist / img_hist.max())
        img_cdf, bins = exposure.cumulative_distribution(img[..., c])
        axes[c, i].plot(bins, img_cdf)
        axes[c, 0].set_ylabel(c_color)
  
axes[0, 0].set_title('Source')
axes[0, 1].set_title('Reference')
axes[0, 2].set_title('Matched')
  
plt.tight_layout()
plt.show()


Output:

Example 2: Using only scikit-image:

This example is similar to the previous, except that we load images from the skimage.data package. Then we match histograms, display images, and plot histograms.

Python3




# importing packages
import matplotlib.pyplot as plt
from skimage import data
from skimage import exposure
from skimage.exposure import match_histograms
  
# loading data
reference = data.moon()
image = data.camera()
  
# matching histograms
matched = match_histograms(image, reference, 
                           multichannel=True,)
  
fig, (ax1, ax2, ax3) = plt.subplots(nrows=1, 
                                    ncols=3, 
                                    figsize=(8, 3),
                                    sharex=True, 
                                    sharey=True)
for aa in (ax1, ax2, ax3):
    aa.set_axis_off()
  
# displaying images
ax1.imshow(image)
ax1.set_title('Source image')
ax2.imshow(reference)
ax2.set_title('Reference image')
ax3.imshow(matched)
ax3.set_title('Matched image')
  
plt.tight_layout()
plt.show()


Output”

Displaying histogram of the above-used images.

Python3




# displaying histograms.
fig, axes = plt.subplots(nrows=3, ncols=3, figsize=(8, 8))
  
for i, img in enumerate((image, reference, matched)):
    for c, c_color in enumerate(('red', 'green', 'blue')):
        img_hist, bins = exposure.histogram(img[..., c],
                                            source_range='dtype')
        axes[c, i].plot(bins, img_hist / img_hist.max())
        img_cdf, bins = exposure.cumulative_distribution(img[..., c])
        axes[c, i].plot(bins, img_cdf)
        axes[c, 0].set_ylabel(c_color)
  
axes[0, 0].set_title('Source image')
axes[0, 1].set_title('Reference image')
axes[0, 2].set_title('Matched image')
  
plt.tight_layout()
plt.show()


Output:



Similar Reads

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
OpenCV Python Program to analyze an image using Histogram
In this article, image analysis using Matplotlib and OpenCV is discussed. Let's first understand how to experiment image data with various styles and how to represent with Histogram. Prerequisites: OpenCV matplotlib Importing image data import matplotlib.pyplot as plt #importing matplotlib The image should be used in a PNG file as matplotlib suppor
4 min read
Image processing with Scikit-image in Python
scikit-image is an image processing Python package that works with NumPy arrays which is a collection of algorithms for image processing. Let's discuss how to deal with images in set of information and its application in the real world. Important features of scikit-image : Simple and efficient tools for image processing and computer vision techniqu
2 min read
Image Segmentation using Python's scikit-image module
The process of splitting images into multiple layers, represented by a smart, pixel-wise mask is known as Image Segmentation. It involves merging, blocking, and separating an image from its integration level. Splitting a picture into a collection of Image Objects with comparable properties is the first stage in image processing. Scikit-Image is the
14 min read
CLAHE Histogram Equalization - OpenCV
In this tutorial, we are going to learn how to apply CLAHE and process a given input image for histogram equalization. In this tutorial, we are going to see how to apply Contrast Limited Adaptive Histogram Equalization (CLAHE) to equalize images. CLAHE is a variant of Adaptive histogram equalization (AHE) which takes care of over-amplification of t
2 min read
Feature detection and matching with OpenCV-Python
In this article, we are going to see about feature detection in computer vision with OpenCV in Python. Feature detection is the process of checking the important features of the image in this case features of the image can be edges, corners, ridges, and blobs in the images. In OpenCV, there are a number of methods to detect the features of the imag
5 min read
Template matching using OpenCV in Python
Template matching is a technique for finding areas of an image that are similar to a patch (template). A patch is a small image with certain features. The goal of template matching is to find the patch/template in an image. To find it, the user has to give two input images: Source Image (S) - The image to find the template in, and Template Image (T
6 min read
Feature matching using ORB algorithm in Python-OpenCV
ORB is a fusion of FAST keypoint detector and BRIEF descriptor with some added features to improve the performance. FAST is Features from Accelerated Segment Test used to detect features from the provided image. It also uses a pyramid to produce multiscale-features. Now it doesn’t compute the orientation and descriptors for the features, so this is
2 min read
Feature Matching using Brute Force in OpenCV
In this article, we will do feature matching using Brute Force in Python by using OpenCV library. Prerequisites: OpenCV OpenCV is a python library which is used to solve the computer vision problems. OpenCV is an open source Computer Vision library. So computer vision is a way of teaching intelligence to machine and making them see things just like
13 min read
Multi-template matching with OpenCV
In this tutorial, we are going to see how to perform Multi-template matching with OpenCV. We'll walk you through the entire process of multi-template matching using OpenCV. For this tutorial, you'll need a basic understanding of computer vision with OpenCV and have all the dependencies installed on your working environment. What is template matchin
5 min read
Article Tags :
Practice Tags :