Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Convert image to binary using Python

  • Last Updated : 17 Dec, 2020

In this article, we are going to convert the image into its binary form. A binary image is a monochromatic image that consists of pixels that can have one of exactly two colors, usually black and white. Binary images are also called bi-level or two-level. This means that each pixel is stored as a single bit—i.e., 0 or 1.

The most important library needed for image processing in Python is OpenCV. Make sure you have installed the library into your Python. For steps for installing OpenCV refers to this article: Set up Opencv with anaconda environment

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

Approach:



  1. Read the image from the location.
  2. As a colored image has RGB layers in it and is more complex, convert it to its Grayscale form first.
  3. Set up a Threshold mark, pixels above the given mark will turn white, and below the mark will turn black.

Below is the implementation:

Python3




import cv2
  
# read the image file
img = cv2.imread('ff.jpg', 2)
  
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)
  
cv2.imshow("Binary", bw_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Output:

Original Image

Binary Form

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!