Adaptive ThresholdingΒΆ

Thresholding is the simplest way to segment objects from a background. If that background is relatively uniform, then you can use a global threshold value to binarize the image by pixel-intensity. If there’s large variation in the background intensity, however, adaptive thresholding (a.k.a. local or dynamic thresholding) may produce better results.

Here, we binarize an image using the threshold_adaptive function, which calculates thresholds in regions of size block_size surrounding each pixel (i.e. local neighborhoods). Each threshold value is the weighted mean of the local neighborhood minus an offset value.

../_images/plot_threshold_adaptive_1.png

import matplotlib.pyplot as plt

from skimage import data
from skimage.filter import threshold_otsu, threshold_adaptive


image = data.page()

global_thresh = threshold_otsu(image)
binary_global = image > global_thresh

block_size = 40
binary_adaptive = threshold_adaptive(image, block_size, offset=10)

fig, axes = plt.subplots(nrows=3, figsize=(7, 8))
ax0, ax1, ax2 = axes
plt.gray()

ax0.imshow(image)
ax0.set_title('Image')

ax1.imshow(binary_global)
ax1.set_title('Global thresholding')

ax2.imshow(binary_adaptive)
ax2.set_title('Adaptive thresholding')

for ax in axes:
    ax.axis('off')

plt.show()

STDOUT


        

STDERR


        

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

IPython Notebook: download (generated using skimage 0.11dev)

aW1wb3J0IG1hdHBsb3RsaWIucHlwbG90IGFzIHBsdAoKZnJvbSBza2ltYWdlIGltcG9ydCBkYXRhCmZyb20gc2tpbWFnZS5maWx0ZXIgaW1wb3J0IHRocmVzaG9sZF9vdHN1LCB0aHJlc2hvbGRfYWRhcHRpdmUKCgppbWFnZSA9IGRhdGEucGFnZSgpCgpnbG9iYWxfdGhyZXNoID0gdGhyZXNob2xkX290c3UoaW1hZ2UpCmJpbmFyeV9nbG9iYWwgPSBpbWFnZSA+IGdsb2JhbF90aHJlc2gKCmJsb2NrX3NpemUgPSA0MApiaW5hcnlfYWRhcHRpdmUgPSB0aHJlc2hvbGRfYWRhcHRpdmUoaW1hZ2UsIGJsb2NrX3NpemUsIG9mZnNldD0xMCkKCmZpZywgYXhlcyA9IHBsdC5zdWJwbG90cyhucm93cz0zLCBmaWdzaXplPSg3LCA4KSkKYXgwLCBheDEsIGF4MiA9IGF4ZXMKcGx0LmdyYXkoKQoKYXgwLmltc2hvdyhpbWFnZSkKYXgwLnNldF90aXRsZSgnSW1hZ2UnKQoKYXgxLmltc2hvdyhiaW5hcnlfZ2xvYmFsKQpheDEuc2V0X3RpdGxlKCdHbG9iYWwgdGhyZXNob2xkaW5nJykKCmF4Mi5pbXNob3coYmluYXJ5X2FkYXB0aXZlKQpheDIuc2V0X3RpdGxlKCdBZGFwdGl2ZSB0aHJlc2hvbGRpbmcnKQoKZm9yIGF4IGluIGF4ZXM6CiAgICBheC5heGlzKCdvZmYnKQoKcGx0LnNob3coKQ==