Binarization is used when you want to convert a numerical feature vector into a Boolean vector. In the field of digital image processing, image binarization is the process by which a color or grayscale image is transformed into a binary image, that is, an image with only two colors (typically, black and white).
Binarization
Getting ready
This technique is used for the recognition of objects, shapes, and, specifically, characters. Through binarization, it is possible to distinguish the object of interest from the background on which it is found. Skeletonization is instead an essential and schematic representation of the object, which generally preludes the subsequent real recognition.
How to do it...
Let's see how to binarize data in Python:
- To binarize data, we will use the preprocessing.Binarizer() function as follows (we will use the same data as in the previous recipe):
>> data_binarized = preprocessing.Binarizer(threshold=1.4).transform(data)
The preprocessing.Binarizer() function binarizes data according to an imposed threshold. Values greater than the threshold map to 1, while values less than or equal to the threshold map to 0. With the default threshold of 0, only positive values map to 1. In our case, the threshold imposed is 1.4, so values greater than 1.4 are mapped to 1, while values less than 1.4 are mapped to 0.
- To display the binarized array, we will use the following code:
>> print(data_binarized)
The following output is returned:
[[ 1. 0. 1. 0.]
[ 0. 1. 0. 1.]
[ 0. 1. 0. 0.]]
This is a very useful technique that's usually used when we have some prior knowledge of the data.
How it works...
In this recipe, we binarized the data. The fundamental idea of this technique is to draw a fixed demarcation line. It is therefore a matter of finding an appropriate threshold and affirming that all the points of the image whose light intensity is below a certain value belong to the object (background), and all the points with greater intensity belong to the background (object).
There's more...
Binarization is a widespread operation on count data, in which the analyst can decide to consider only the presence or absence of a characteristic rather than a quantified number of occurrences. Otherwise, it can be used as a preprocessing step for estimators that consider random Boolean variables.
See also
- Scikit-learn's official documentation of the sklearn.preprocessing.Binarizer() function: https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.Binarizer.html.