Switch to Otsu instead of mean

This commit is contained in:
François Boulogne
2016-06-19 09:35:05 +02:00
parent d870bcc5df
commit 25f5729d57
+21 -10
View File
@@ -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()