Sunday, December 29, 2024
Google search engine
HomeLanguagesHistogram matching with OpenCV, scikit-image, and Python

Histogram matching with OpenCV, scikit-image, and Python

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:

RELATED ARTICLES

Most Popular

Recent Comments