def binarize_image(image, method='li', **kwargs):
"""Binarize image using one of the available methods: 'isodata',
'li', 'otsu', 'sauvola', and 'boolean'. Defaults to 'li'.
Extra keyword arguments are passed in as is to the corresponding
scikit-image thresholding function. The 'boolean' method refers to simple
thresholding from a grey-scale image. If a 'threshold' kwarg is not passed
to the 'boolean' method, 'li' thresholding is performed.
For reference
Sezgin M. and Sankur B. (2004) "Survey over Image Thresholding Techniques
and Quantitative Performance Evaluation" Journal of Electronic Imaging,
13(1): 146-165 DOI:10.1117/1.1631315
"""
if image.ndim != 2:
# image is not gray-scale
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
if np.unique(image).size == 2:
# image is already binary
return image
boolean_threshold = kwargs.get('threshold', None)
if method == 'boolean' and boolean_threshold:
preprocessing.binarize(image, threshold=boolean_threshold, copy=False)
return convert(image)
if method not in ('sauvola', 'isodata', 'otsu', 'li'):
method = 'li'
thresh_func = getattr(filters.thresholding, "threshold_{}".format(method))
threshold = thresh_func(image, **kwargs)
# OpenCV can't write black and white images using boolean values, it needs
# at least a 8bits 1-channel image ranged from 0 (black) to 255 (white)
return convert(image <= threshold)
评论列表
文章目录