OpenCV Python – How to convert a colored image to a binary image? (2024)

Table of Contents
Steps Example Output Example Output FAQs

'; var adpushup = adpushup || {}; adpushup.que = adpushup.que || []; adpushup.que.push(function() { adpushup.triggerAd(ad_id); });

We use cv2.threshold() to convert a grayscale image to binary image. To convert a color image to binary image, we first convert the color image to grayscale image using cv2.cvtColor() then apply cv2.threshold() on the grayscale image.

Steps

One could follow the below given steps to convert a color image to a binary image-

  • Import the required library. In all the following examples, the required Python library is OpenCV. Make sure you have already installed it.

  • Read an the input image using cv2.imread(). The RGB image read using this method is in BGR format. Optionally assign the read BGR image to img.

  • Now convert this BGR image to grayscale image as below using cv2.cvtColor() function. Optionally assign the converted grayscale image to gray.

  • Apply thresholding cv2.threshold() on the grayscale image gray to convert it to a binary image. Adjust the second parameter (threshValue) for better binary image.

  • Display the converted binary image.

Let's look at some examples for a clear understanding about the question.

We will use the following image as the Input File in the examples below.

OpenCV Python – How to convert a colored image to a binary image? (30)

Example

In this Python program, we convert a color image to a binary image. We also display the binary image.

# import required librariesimport cv2# load the input imageimg = cv2.imread('architecture1.jpg')# convert the input image to grayscalegray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)# apply thresholding to convert grayscale to binary imageret,thresh = cv2.threshold(gray,70,255,0)# Display the Binary Imagecv2.imshow("Binary Image", thresh)cv2.waitKey(0)cv2.destroyAllWindows()

Output

When you run the above program, it will produce the following output window showing the binary image.

OpenCV Python – How to convert a colored image to a binary image? (31)

Example

In this example, we convert a color image to a binary image. We also display the original, grayscale and binary images.

# import required librariesimport cv2import matplotlib.pyplot as plt# load the input imageimg = cv2.imread('architecture1.jpg')# convert the input image to grayscalegray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)# apply thresholding to convert grayscale to binary imageret,thresh = cv2.threshold(gray,70,255,0)# convert BGR to RGB to display using matplotlibimgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)# display Original, Grayscale and Binary Imagesplt.subplot(131),plt.imshow(imgRGB,cmap = 'gray'),plt.title('Original Image'), plt.axis('off')plt.subplot(132),plt.imshow(gray,cmap = 'gray'),plt.title('Grayscale Image'),plt.axis('off')plt.subplot(133),plt.imshow(thresh,cmap = 'gray'),plt.title('Binary Image'),plt.axis('off')plt.show()

Output

When you run the above program, it will produce the following output window showing the original, grayscale and binary images.

OpenCV Python – How to convert a colored image to a binary image? (32)

Notice the difference between the Grayscale image and Binary image. Binary image has only two colors: white and black. The pixel values of the Binary image are either 0 (black) or 255 (white).

Updated on: 02-Dec-2022

20K+ Views

Related Articles

Kickstart Your Career

Get certified by completing the course

Get Started

OpenCV Python – How to convert a colored image to a binary image? (34)

Advertisem*nts

';adpushup.triggerAd(ad_id); });

OpenCV Python – How to convert a colored image to a binary image? (2024)

FAQs

OpenCV Python – How to convert a colored image to a binary image? ›

The process of converting a picture to binary is called binarization and it can be done in multiple ways. The first method uses a color quantization algorithm that finds the two dominant colors in a picture and by calculating the difference in hue, all pixels take one or the other color value (whichever is closest).

How to convert RGB image into binary? ›

Code Explanation:
  1. I = imread('lighthouse. ...
  2. imshow(I); This line displays the input image I in the figure window.
  3. J = im2bw(I,0.5); This line converts the RGB Image to Binary with the threshold level set at 0.5 for comparing intensity levels of pixels.
Feb 23, 2022

How to convert an image into binary? ›

The process of converting a picture to binary is called binarization and it can be done in multiple ways. The first method uses a color quantization algorithm that finds the two dominant colors in a picture and by calculating the difference in hue, all pixels take one or the other color value (whichever is closest).

How to binarize an image in OpenCV? ›

Image binarization with OpenCV: cv2.

You can binarize an image with cv2. threshold() . If type is set to cv2. THRESH_BINARY , any value greater than the threshold thresh is replaced with maxval and the other values are replaced with 0 .

How to binarize an image in Python? ›

Code Implementation with Library

For converting the image into a binary image, we can simply make use of the threshold() method available in the cv2 library. This method, irrespective of what the image is (grayscale or RGB) converts into binary. It takes 4 arguments in use.

How to convert color image to grayscale in OpenCV? ›

Step 1: Import OpenCV. Step 2: Read the original image using imread(). Step 3: Convert to grayscale using cv2. cvtcolor() function.

How to convert a color image to binary image in Python? ›

Steps
  1. Import the required library. In all the following examples, the required Python library is OpenCV. ...
  2. Read an the input image using cv2. imread(). ...
  3. Now convert this BGR image to grayscale image as below using cv2. cvtColor() function. ...
  4. Apply thresholding cv2. ...
  5. Display the converted binary image.
Dec 2, 2022

How do you convert colors to binary? ›

Start by converting each of the three numbers into binary, using 8 bits for each. You should get: - red = 10010001, - green = 00110010, - blue = 01111011. Putting these values together gives 100100010011001001111011, which is the bit representation for the colour above.

What does convert (' RGB ') do? ›

As you might know, RGB is simply three 8-bit values for red, green and blue. CMYK is four 8-bit values. When you use Image. convert('RGB') it just converts each pixel to the triple 8-bit value.

What does 11111111 mean in binary in image? ›

With 8-bit data, we can assign the darkest point in an image to the number 00000000, and the brightest point in the image to 11111111. This produces 256 shades of gray between black and white.

What is binary image OpenCV? ›

To convert an image to binary using OpenCV, you can use the cv2. threshold() function. This function applies a threshold to a grayscale image, converting it to a binary image. The cv2. threshold() function in OpenCV is used to apply a threshold to a grayscale image, effectively converting it into a binary image.

Why is image converted to binary image? ›

The importance of Binary Image in image processing is: they allow to separate objects easily from the background. The segmentation allows to label each pixel as 'object' and 'background' and assign black and white colour accordingly.

How to convert image to binary image in cv2? ›

Code for normal to binary image conversion
  1. from google.colab.patches import cv2_imshow. ...
  2. image = cv2.imread(“powerful learning (5).png”) ...
  3. grayimage =cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) ...
  4. thresholdimage = cv2.threshold(grayimage,180,255,cv2.THRESH_BINARY)[1] ...
  5. cv2_imshow(image) ...
  6. cv2_imshow(grayimage)
Jan 6, 2023

How do I change the format of an image in OpenCV? ›

OpenCV uses BGR image format. So, when we read an image using cv2. imread() it interprets in BGR format by default. We can use cvtColor() method to convert a BGR image to RGB and vice-versa.

What is image binarization? ›

Image Binarization is the conversion of document image into bi-level document image. Image pixels are separated into dual collection of pixels, i.e. black and white. The main goal of image binarization is the segmentation of document into foreground text and background.

How to get image binary data in Python? ›

To read a binary file in Python, first, we need to open it in binary mode ('”rb”'). We can use the 'open()' function to achieve this. To create a binary file in Python, You need to open the file in binary write mode ( wb ).

How do you convert image format using Python? ›

Step by Step Image Conversion with Python
  1. Create a virtual environment. ...
  2. Loading and presenting an image's properties. ...
  3. Changing the Format of Every Image in a Directory. ...
  4. Step 1 – Create a virtual environment and install package dependencies. ...
  5. Step 3 – Add environment variables. ...
  6. Step 4 – Converting an image to another format.
Mar 14, 2024

How to convert object to binary Python? ›

Convert a String to Binary in Python
  1. Method 1: Using the bin() function. The simplest method to convert a string to binary in Python is to use the built-in bin() function. ...
  2. Method 2: Using the bytearray() function. ...
  3. Method 3: Using the struct. ...
  4. Method 4: Using the ord() function and bitwise operations.
Mar 28, 2023

What is image binary format? ›

Binary Images are image which consists of two colours i.e. “Black” and “White”. The pixels have only two possible intensity values, '0' for 'Black' and either '1' or '255' for 'White'. The importance of Binary Image in image processing is: they allow to separate objects easily from the background.

Top Articles
How to Make Your Windows 11 PC Never Go To Sleep?
Understanding Behavioral Finance: Concepts, Biases & Applications
Section 4Rs Dodger Stadium
Po Box 7250 Sioux Falls Sd
Napa Autocare Locator
Alan Miller Jewelers Oregon Ohio
Ingles Weekly Ad Lilburn Ga
Evil Dead Rise Showtimes Near Massena Movieplex
Craigslist Dog Sitter
Pbr Wisconsin Baseball
LeBron James comes out on fire, scores first 16 points for Cavaliers in Game 2 vs. Pacers
FAQ: Pressure-Treated Wood
Jesus Calling Oct 27
Espn Horse Racing Results
Nhl Wikia
Milspec Mojo Bio
Satisfactory: How to Make Efficient Factories (Tips, Tricks, & Strategies)
Quick Answer: When Is The Zellwood Corn Festival - BikeHike
Getmnapp
January 8 Jesus Calling
Afni Collections
Lilpeachbutt69 Stephanie Chavez
2021 Tesla Model 3 Standard Range Pl electric for sale - Portland, OR - craigslist
How Do Netspend Cards Work?
Rugged Gentleman Barber Shop Martinsburg Wv
Rund um die SIM-Karte | ALDI TALK
Beaver Saddle Ark
Bee And Willow Bar Cart
Pensacola 311 Citizen Support | City of Pensacola, Florida Official Website
Samsung 9C8
Asian Grocery Williamsburg Va
Merge Dragons Totem Grid
How To Get Soul Reaper Knife In Critical Legends
Pepsi Collaboration
159R Bus Schedule Pdf
Hireright Applicant Center Login
Mcalister's Deli Warrington Reviews
Executive Lounge - Alle Informationen zu der Lounge | reisetopia Basics
Umd Men's Basketball Duluth
Panolian Batesville Ms Obituaries 2022
Stosh's Kolaches Photos
Gabrielle Abbate Obituary
Trending mods at Kenshi Nexus
Okta Login Nordstrom
York Racecourse | Racecourses.net
Research Tome Neltharus
Coleman Funeral Home Olive Branch Ms Obituaries
O'reilly's On Marbach
Convert Celsius to Kelvin
Blippi Park Carlsbad
Https://Eaxcis.allstate.com
Ravenna Greataxe
Latest Posts
Article information

Author: Frankie Dare

Last Updated:

Views: 6140

Rating: 4.2 / 5 (53 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Frankie Dare

Birthday: 2000-01-27

Address: Suite 313 45115 Caridad Freeway, Port Barabaraville, MS 66713

Phone: +3769542039359

Job: Sales Manager

Hobby: Baton twirling, Stand-up comedy, Leather crafting, Rugby, tabletop games, Jigsaw puzzles, Air sports

Introduction: My name is Frankie Dare, I am a funny, beautiful, proud, fair, pleasant, cheerful, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.