ThresholdingΒΆ

Thresholding is used to create a binary image. This example uses Otsu’s method to calculate the threshold value.

Otsu’s method calculates an “optimal” threshold (marked by a red line in the histogram below) by maximizing the variance between two classes of pixels, which are separated by the threshold. Equivalently, this threshold minimizes the intra-class variance.

[1]http://en.wikipedia.org/wiki/Otsu’s_method
../_images/plot_otsu_1.png

import matplotlib
import matplotlib.pyplot as plt

from skimage.data import camera
from skimage.filter import threshold_otsu


matplotlib.rcParams['font.size'] = 9


image = camera()
thresh = threshold_otsu(image)
binary = image > thresh

fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(8, 2.5))
ax1.imshow(image, cmap=plt.cm.gray)
ax1.set_title('Original')
ax1.axis('off')

ax2.hist(image)
ax2.set_title('Histogram')
ax2.axvline(thresh, color='r')

ax3.imshow(binary, cmap=plt.cm.gray)
ax3.set_title('Thresholded')
ax3.axis('off')

plt.show()

STDOUT


        

STDERR


        

Python source code: download (generated using skimage 0.11dev)

IPython Notebook: download (generated using skimage 0.11dev)

aW1wb3J0IG1hdHBsb3RsaWIKaW1wb3J0IG1hdHBsb3RsaWIucHlwbG90IGFzIHBsdAoKZnJvbSBza2ltYWdlLmRhdGEgaW1wb3J0IGNhbWVyYQpmcm9tIHNraW1hZ2UuZmlsdGVyIGltcG9ydCB0aHJlc2hvbGRfb3RzdQoKCm1hdHBsb3RsaWIucmNQYXJhbXNbJ2ZvbnQuc2l6ZSddID0gOQoKCmltYWdlID0gY2FtZXJhKCkKdGhyZXNoID0gdGhyZXNob2xkX290c3UoaW1hZ2UpCmJpbmFyeSA9IGltYWdlID4gdGhyZXNoCgpmaWcsIChheDEsIGF4MiwgYXgzKSA9IHBsdC5zdWJwbG90cygxLCAzLCBmaWdzaXplPSg4LCAyLjUpKQpheDEuaW1zaG93KGltYWdlLCBjbWFwPXBsdC5jbS5ncmF5KQpheDEuc2V0X3RpdGxlKCdPcmlnaW5hbCcpCmF4MS5heGlzKCdvZmYnKQoKYXgyLmhpc3QoaW1hZ2UpCmF4Mi5zZXRfdGl0bGUoJ0hpc3RvZ3JhbScpCmF4Mi5heHZsaW5lKHRocmVzaCwgY29sb3I9J3InKQoKYXgzLmltc2hvdyhiaW5hcnksIGNtYXA9cGx0LmNtLmdyYXkpCmF4My5zZXRfdGl0bGUoJ1RocmVzaG9sZGVkJykKYXgzLmF4aXMoJ29mZicpCgpwbHQuc2hvdygp