Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
pillow
communitycreator

How to binarize an image in Pillow

Eman Kashif

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:

  1. 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.

  1. 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.

  1. 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 for loops.
  • 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 assign 255 (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.

#import libraries
import PIL
from PIL import Image
 
img=Image.open('og_image.png') 
#binarization function
def binarize(img):

  #initialize threshold
  thresh=200

  #convert image to greyscale
  img=img.convert('L') 

  width,height=img.size

  #traverse through pixels 
  for x in range(width):
    for y in range(height):

      #if intensity less than threshold, assign white
      if img.getpixel((x,y)) < thresh:
        img.putpixel((x,y),0)

      #if intensity greater than threshold, assign black 
      else:
        img.putpixel((x,y),255)

  return img

bin_image=binarize(img)
bin_image

Original image:

Image after binarization:

RELATED TAGS

python
pillow
communitycreator
RELATED COURSES

View all Courses

Keep Exploring