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 fol...
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.
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 h**e 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.
In this Python program, we convert a color image to a binary image. We also display the binary image.
When you run the above program, it will produce the following output window showing the binary image.
In this example, we convert a color image to a binary image. We also display the original, grayscale and binary images.
When you run the above program, it will produce the following output window showing the original, grayscale and binary images.
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).