Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Events
Videos
Audiobooks
Packt Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Python Image Processing Cookbook

You're reading from   Python Image Processing Cookbook Over 60 recipes to help you perform complex image processing and computer vision tasks with ease

Arrow left icon
Product type Paperback
Published in Apr 2020
Publisher Packt
ISBN-13 9781789537147
Length 438 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Sandipan Dey Sandipan Dey
Author Profile Icon Sandipan Dey
Sandipan Dey
Arrow right icon
View More author details
Toc

Table of Contents (11) Chapters Close

Preface 1. Image Manipulation and Transformation 2. Image Enhancement FREE CHAPTER 3. Image Restoration 4. Binary Image Processing 5. Image Registration 6. Image Segmentation 7. Image Classification 8. Object Detection in Images 9. Face Recognition, Image Captioning, and More 10. Other Books You May Enjoy

Implementing histogram matching

Histogram matching is an image processing task where an image is altered in such a way that its histogram matches the histogram of another reference (template) image's histogram. The algorithm is described as follows:

  1. Compute the cumulative histogram for each image.
  2. For any given pixel value, xi, in the input image, find the corresponding pixel value, xj, in the output image by matching the input image's histogram with the template image's histogram (G(xi)=H(xj), as shown in the following diagram.
  3. Replace pixel xi in the input with xj as shown in the following diagram:

In this recipe, we will implement histogram matching for colored images on our own.

Getting ready

As usual, let's start by importing the required libraries:

from skimage.exposure import cumulative_distribution
from skimage.color import rgb2gray
import matplotlib.pylab as plt
import numpy as np

How to do it...

Perform the following steps to implement histogram matching:

  1. Let's implement the histogram-matching algorithm with the hist_matching() function, which accepts the original and the template image's cdf along with the original image:
def hist_matching(c, c_t, im):
b = np.interp(c, c_t, np.arange(256))
# find closest matches to b_t
pix_repl = {i:b[i] for i in range(256)}
# dictionary to replace the pixels
mp = np.arange(0,256)
for (k, v) in pix_repl.items():
mp[k] = v
s = im.shape
im = np.reshape(mp[im.ravel()], im.shape)
im = np.reshape(im, s)
return im
  1. Compute cdf of an image with the following function:
def cdf(im):
c, b = cumulative_distribution(im)
for i in range(b[0]):
c = np.insert(c, 0, 0)
for i in range(b[-1]+1, 256):
c = np.append(c, 1)
return c

  1. Finally, read the input and template images, compute their cdfs, and create the output image with the hist_matching() function. Plot the input, template, and output images by running the following code:
im = imread('images/goddess.png').astype(np.uint8)
im_t = imread('images/leaves.png')

im1 = np.zeros(im.shape).astype(np.uint8)
for i in range(3):
c = cdf(im[...,i])
c_t = cdf(im_t[...,i])
im1[...,i] = hist_matching(c, c_t, im[...,i])

plt.figure(figsize=(20,17))
plt.subplots_adjust(left=0, top=0.95, right=1, bottom=0, \
wspace=0.05, hspace=0.05)
plt.subplot(221), plt.imshow(im), plt.axis('off'), \
plt.title('Input Image', size=25)
plt.subplot(222), plt.imshow(im_t), plt.axis('off'), \
plt.title('Template Image', size=25)
plt.subplot(223), plt.imshow(im1[...,:3]), plt.axis('off'), \
plt.title('Output Image', size=25)
plt.show()

How it works...

The cumulative_distribution() function from the scikit-image.exposure module was used to compute the cdf of an image.

Note that the cumulative_distribution() function returns the bins in increasing order of consecutive pixel values, starting from the minimum pixel value present in the image up to the maximum pixel value present.

Since we needed all the pixel values starting from 0 to 255, we used np.insert() with an appropriate cdf value (0 for all the smaller pixel values and 1 for higher pixel values not present).

For each of the color channels, cdf was computed separately for the input and the template images using the cdf() function, and then the hist_matching() function was invoked with these values along with the input image to construct the corresponding color channel in the output image.

The following diagram shows the output image generated for these given input and template images:

There's more...

You can use histogram matching to change an image taken in daylight to a night-vision image using an appropriate template image. The next example shows a similar fun application of histogram matching:

See also

CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Python Image Processing Cookbook
You have been reading a chapter from
Python Image Processing Cookbook
Published in: Apr 2020
Publisher: Packt
ISBN-13: 9781789537147
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Modal Close icon
Modal Close icon