From 25f5729d570c66e4f55cb23a7a41db9382b9015e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Boulogne?= Date: Sun, 19 Jun 2016 09:35:05 +0200 Subject: [PATCH] Switch to Otsu instead of mean --- .../segmentation/plot_thresholding.py | 31 +++++++++++++------ 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/doc/examples/segmentation/plot_thresholding.py b/doc/examples/segmentation/plot_thresholding.py index 09654b5d..1324db72 100644 --- a/doc/examples/segmentation/plot_thresholding.py +++ b/doc/examples/segmentation/plot_thresholding.py @@ -15,28 +15,39 @@ Thresholding is used to create a binary image from a grayscale image [1]_. ###################################################################### # We illustrate how to apply one of these thresholding algorithms. -# This example uses the mean value of pixel intensities. It is a simple -# and naive threshold value, which is sometimes used as a guess value. +# Otsu's method [2]_ 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. +# +# .. [2] http://en.wikipedia.org/wiki/Otsu's_method import matplotlib.pyplot as plt -from skimage.filters.thresholding import threshold_mean from skimage import data +from skimage.filters import threshold_otsu + image = data.camera() -thresh = threshold_mean(image) +thresh = threshold_otsu(image) binary = image > thresh -fig, axes = plt.subplots(ncols=2, figsize=(8, 3)) +fig, axes = plt.subplots(ncols=3, figsize=(8, 2.5)) ax = axes.ravel() +ax[0] = plt.subplot(1, 3, 1, adjustable='box-forced') +ax[1] = plt.subplot(1, 3, 2) +ax[2] = plt.subplot(1, 3, 3, sharex=ax[0], sharey=ax[0], adjustable='box-forced') ax[0].imshow(image, cmap=plt.cm.gray) -ax[0].set_title('Original image') +ax[0].set_title('Original') +ax[0].axis('off') -ax[1].imshow(binary, cmap=plt.cm.gray) -ax[1].set_title('Result') +ax[1].hist(image.ravel(), bins=256) +ax[1].set_title('Histogram') +ax[1].axvline(thresh, color='r') -for a in ax: - a.axis('off') +ax[2].imshow(binary, cmap=plt.cm.gray) +ax[2].set_title('Thresholded') +ax[2].axis('off') plt.show()