Convert RGB to Binary Image in Python (Black and White)
A binary image is the type of image where each pixel is black or white. You can also say the pixels as 0 or 1 value. Here 0 represents black and 1 represents a white pixel.
I often find peoples calling grayscale image as black and white. Now let’s understand what is grayscale and what is a black and white or binary image with the example of my own picture.
Many peoples think the grayscale image as black and white. Many of us will think the below image as black and white:
But this is a wrong concept. Real binary image or pure black and white image look like you can see below:
Each of the pixels of the above binary image is either black or white. Or we cay each pixel value is 0 or 1.
So you have seen the same image as grayscale and binary and got the idea of a binary image.
Convert RGB to Binary Image in Python using OpenCV
Now I am going to show you how you can convert RGB to Binary Image or convert a colored image to black and white.
Here we are just going to write a few lines of Python code and it will convert our RGB image into a binary image.
To convert an RGB image into a binary type image, we need OpenCV. So first of all, if we don’t have OpenCV installed, then we can install it via pip:
pip install opencv-python
Now we can continue writing Python code.
At the top, we have to import the OpenCV Python library:
After that, read our image as grayscale. Grayscale is a simplified image and it makes the process simple. Below is the code to get grayscale data of the image:
img = cv2.imread('imgs/mypic.jpg',2)
Then set the threshold value for our grayscale image:
ret, bw_img = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
Now show the image:
In the end, we have to use waitKey and destroyAllWindows method to keep our window always open until we press any key or close our window and also destroy all windows. Below is the Python code that will do that:
- How to create a database in MySQL using Python
- Graph Plot of X and Y-Axis for given values as input in Python 3
The complete and final Python code to convert an RGB or colored image into the binary is given below:
import cv2 img = cv2.imread('imgs/mypic.jpg',2) ret, bw_img = cv2.threshold(img,127,255,cv2.THRESH_BINARY) cv2.imshow("Binary Image",bw_img) cv2.waitKey(0) cv2.destroyAllWindows()
now you can run and test the above code on your system. You have to pass your own image to the imread() method. After you run the code, you will able to see the binary image of the given image which path you have given to the imread() method.