Conversion of RGB image to Binary using Python

In this blog, I will describe how to convert a coloured image to its binary form. An image in which the pixel has only two values, black and white is known as a binary or bi-level or two-level image. Each pixel in a binary image is stored as a single bit either 0 or 1. For RGB to Binary image conversion, the OpenCV library is used.

Approach:

  1. Read the image. cv2.imread() function is used which loads the image for a specified path.
  2. As a coloured image is more complex and layered so convert the image in the grayscale form. cv2.imread() function reads the image in the greyscale form if the second parameter is 0.
  3. Set threshold value so that pixel value above it will turn white and pixel value below it will turn black. cv2.threshold function is used for apply thresholding. The first argument is the source image, which should be a greyscale image. The second argument is the threshold value which is used to classify the pixel values. The third argument is the maximum value which is assigned to pixel values exceeding the threshold. assigned to pixel values exceeding the threshold. The output of this function was a tuple of two elements, first element of tuple is the threshold value and second is the resultant image.

Implementation :

import cv2
 
# read the image file
img = cv2.imread('image.jpg', 0)
  

# setting threshold
ret, bw_img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
  
# converting to its binary form
bw = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
  
#Output
cv2.imshow("Binary", bw_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Input

Output

Leave a comment

Design a site like this with WordPress.com
Get started