Thursday, November 28, 2024
Google search engine
HomeLanguagesConvert image to binary using Python

Convert image to binary using Python

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

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

RELATED ARTICLES

Most Popular

Recent Comments