This is one of the 100 recipes of the IPython Cookbook, the definitive guide to high-performance scientific computing and data science in Python.

11.1. Manipulating the exposure of an image

You need scikit-image for this recipe. You will find the installation instructions here.

You also need to download the Beach dataset. (

  1. Let's import the packages.
In [ ]:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import skimage.exposure as skie
%matplotlib inline
  1. We open an image with matplotlib. We only take a single RGB component to have a grayscale image.
In [ ]:
img = plt.imread('data/pic1.jpg')[...,0]
  1. We create a function that displays the image along with its histogram.
In [ ]:
def show(img):
    # Display the image.
    # Display the histogram.
    plt.hist(img.ravel(), lw=0, bins=256);
    plt.xlim(0, img.max());
  1. Let's display the image along with its histogram.
In [ ]:

The histogram is unbalanced and the image appears slightly over-exposed.

  1. Now, we rescale the intensity of the image using scikit-image's rescale_intensity function. The in_range and out_range define a linear mapping from the original image to the modified image. The pixels that are outside in_range are clipped to the extremal values of out_range. Here, the darkest pixels (intensity less than 100) become completely black (0), whereas the brightest pixels (>240) become completely white (255).
In [ ]:
     in_range=(100, 240), out_range=(0, 255)))

Many intensity values seem to be missing in the histogram, which reflects the poor quality of this exposure correction technique.

  1. We now use a more advanced exposure correction technique called Contrast Limited Adaptive Histogram Equalization.
In [ ]:

The histogram seems more balanced, and the image now appears more contrasted.

You'll find all the explanations, figures, references, and much more in the book (to be released later this summer).

IPython Cookbook, by Cyrille Rossant, Packt Publishing, 2014 (500 pages).