Python OpenCV: Converting an image to black and white

In this tutorial we will learn how to convert an image to black and white, using Python and OpenCV.

Introduction

In this tutorial we will learn how to convert an image to black and white, using Python and OpenCV.

Converting an image to black and white with OpenCV can be done with a simple binary thresholding operation. We start with a gray scale image and we define a threshold value.

Then, for each pixel of the gray scale image, if its value is lesser than the threshold, then we assign to it the value 0 (black). Otherwise, we assign to it the value 255 (white).

Note whoever that this is a very simple approach, which may not give the best results if, for example, the image has different light conditions in different areas [1]. You can read here about more advanced operations that we can do in OpenCV to obtain better results.

This tutorial was tested on Windows 8.1, with version 4.0.0 of OpenCV. The Python version used was 3.7.2.

The code

The first thing we need to do is importing the cv2 module, so we have access to all the functions that will allow us to convert the image to black and white.

import cv2

Then we will need to obtain the image that we want to convert. So, to read an image from the file system, we simply need to call the imread function, passing as input the path to the file we want to read.

Note that the image will be read as a numpy ndarray.

originalImage = cv2.imread('C:/Users/N/Desktop/Test.jpg')

In order for us to be able to apply the thresholding operation, the image should be in gray scale [2], as already mentioned in the introductory section.

Thus, after reading the image, we will convert it to gray scale with a call to the cvtColor function. For a detailed explanation on how to convert an image to gray scale using OpenCV, please check here.

So, as first input of the cvtColor, we will pass the original image. As second input we need to pass the color space conversion code.

Since OpenCV uses the BGR color space when reading an image, we need to use the COLOR_BGR2GRAY conversion code. For an interesting explanation about why OpenCV uses the BGR format, please check here.

As output, the cvtColor function will return the image in gray scale.

grayImage = cv2.cvtColor(originalImage, cv2.COLOR_BGR2GRAY)

Now, to convert our image to black and white, we will apply the thresholding operation. To do it, we need to call the threshold function of the cv2 module.

For this tutorial we are going to apply the simplest thresholding approach, which is the binary thresholding. Note however that OpenCV offers more types of thresholding, as can be seen here.

As already mentioned, the algorithm for binary thresholding corresponds to the following: for each pixel of the image, if the value of the pixel is lesser than a given threshold, then it is set to zero. Otherwise, it is set to a user defined value [3].

Note that since we are operating over a gray scale image, pixel values vary between 0 and 255. Also, since we want to convert the image to black and white, when the pixel is greater than the threshold, the value to which we want it to be converted is 255.

Naturally, the threshold function allows us to specify these parameters. So, the first input of the function is the gray scale image to which we want to apply the operation.

As second input, it receives the value of the threshold. We will consider the value 127, which is in the middle of the scale of the values a pixel in gray scale can take (from 0 to 255).

As third input, the function receives the user defined value to which a pixel should be converted in case its value is greater than the threshold. We will use the value 255, which corresponds to white. Recall that we want to convert the image to black and white, which means that at the end we want a image having pixels with either the value 0 or 255.

As fourth input, the function receives a constant indicating the type of thesholding to apply. As already mentioned, we are going to use a binary threshold, so we pass the value THRESH_BINARY.

As output, this function call will return a tuple. The first value can be ignored, since it is relevant only for more advanced thresholding methods. The second returned value corresponds to the resulting image, after applying the operation.

(thresh, blackAndWhiteImage) = cv2.threshold(grayImage, 127, 255, cv2.THRESH_BINARY)

After this, we will show the black and white image in a window, by calling the imshow function.

cv2.imshow('Black white image', blackAndWhiteImage)

For comparison, we will create two more windows to display the original image and the gray scale version.

cv2.imshow('Original image',originalImage)
cv2.imshow('Gray image', grayImage)

To finalize, we will call the waitKey function with a value of zero, so it blocks indefinitely waiting for a key press. So, until the user presses a key, the windows with the images will be shown.

After the user presses a key, the function will return and unblock the execution. Then, we will call the destroyAllWindows function to destroy the previously created windows.

cv2.waitKey(0)
cv2.destroyAllWindows()

The final code can be seen below.

import cv2
 
originalImage = cv2.imread('C:/Users/N/Desktop/Test.jpg')
grayImage = cv2.cvtColor(originalImage, cv2.COLOR_BGR2GRAY)
 
(thresh, blackAndWhiteImage) = cv2.threshold(grayImage, 127, 255, cv2.THRESH_BINARY)

cv2.imshow('Black white image', blackAndWhiteImage)
cv2.imshow('Original image',originalImage)
cv2.imshow('Gray image', grayImage)
 
cv2.waitKey(0)
cv2.destroyAllWindows()

Testing the code

To test the code, simply run the previous Python script in an environment of your choice. Naturally, you should use as input of the imread function a path pointing to an image in your file system.

You should get an output similar to figure 1, which shows the three versions of the image being displayed in different windows. As can be seen, the image was converted to black and white, as expected.

Showing original image, gray and black and white versions, using OpenCV and Python
Figure 1 – Output of the program, showing the three versions of the image: original, gray scale and black and white

Related Posts

References

[1] https://docs.opencv.org/3.4/d7/d4d/tutorial_py_thresholding.html

[2] https://docs.opencv.org/3.2.0/d7/d4d/tutorial_py_thresholding.html

[3] https://docs.opencv.org/2.4.13.7/doc/tutorials/imgproc/threshold/threshold.html#threshold-binary

Leave a Reply