How to binarize an image in Pillow
Digital image processing is a significant aspect of data science. It is used in image modification and enhancement so that image attributes can be acquired to lead to a greater understanding of data.
An image is made up of elements called pixels, the smallest pieces of information in images. There are three main types of images:
- RGB
Each pixel contains three values for the red, green, and blue color and is stored in three bytes. Each value is in the range 0-255. The values combined make up the resultant color of the pixel.
- Grayscale
Values range from 0-255 and represent the pixel intensity. Each pixel is stored in eight bits. 0 depicts a white pixel, while 255 depicts a black pixel.
- Binary
Each pixel is stored in one bit and can have 0 or 255 as its value. 0 depicts a white pixel, while 255 depicts a black pixel.
Binarization algorithm
This refers to transforming a grayscale image to a binary form (black-and-white). To binarize an image:
- We loop through the pixels using two
forloops. - We initialize an arbitrary threshold against which we compare the intensities of the pixels.
- If the intensity of a particular pixel is less than the threshold, we assign
0(white) to it. If it is greater than or equal to the threshold, we assign255(black) to it.
Thus, a black-and-white image is obtained.
Code
In the code below, the Python imaging library, PIL, is used to read the image.
Original image:
Image after binarization: