Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Open CV
  • scikit-image
  • pycairo
  • Pyglet
  • Python
  • Numpy
  • Pandas
  • Python Database
  • Data Analysis
  • ML Math
  • Machine Learning
  • NLP
  • Deep Learning
  • Deep Learning Interview Questions
  • ML Projects
  • ML Interview Questions
  • 100 Days of Machine Learning
Open In App
Next Article:
Histogram matching with OpenCV, scikit-image, and Python
Next article icon

Histogram matching with OpenCV, scikit-image, and Python

Last Updated : 03 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
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:


Next Article
Histogram matching with OpenCV, scikit-image, and Python

I

isitapol2002
Improve
Article Tags :
  • Python
  • OpenCV
  • Python-OpenCV
Practice Tags :
  • python

Similar Reads

    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 nu
    5 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 Th
    2 min read
    How to Display an OpenCV image in Python with Matplotlib?
    The OpenCV module is an open-source computer vision and machine learning software library. It 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 vide
    2 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
    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: OpenCVmatplotlibImporting image dataimport matplotlib.pyplot as plt #importing matplotlib The image sh
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences