Color, Grayscale and Binary Image Conversion in OpenCV

In this article, we’ll cover two of the available color spaces in the OpenCV library, grayscale color space and binary color space. When we refer to color space conversion, we mean representing a color from one basis to another and converting an image from one color space to another. It is essential to retain as much similarity to the previous color space as possible to make the translated image look as similar to the original image as possible. There are numerous functions available in the OpenCV library for this purpose.

Why do we need color space conversion in image processing?

Color spaces are the representation of the color channels of the image that gives the image that particular hue. By default, the image is read in OpenCV as BGR mode and the color space is RGB.

There are three use cases for color spaces and conversion to different color spaces in data visualizations:
1. Use of color to distinguish data
2. Use of color for representation of data values
3. Using color to highlight information

Grayscale images in OpenCV

Grayscaling is the process of converting an image from any color space to grayscale color space. The grayscaling process simply translates to converting an image to shades of gray. The shade of gray varies between complete black and complete white.

Importance of Grayscaling in OpenCV

1. Reducing the dimension of the images: RGB images have three color channels and constitute a three-dimensional matrix, while in grayscale images, there is no additional parameter for color channels and are only single-dimensional.

2. Due to the dimension reduction, the information provided to each pixel is comparatively less.

3. Reduces the complexity of the model: When there is less information provided to each pixel of the image, the input nodes for the neural network will also be considerably less. Hence, this reduces the complexity of a deep learning model.

4. Difficulty in visualization in color images: Much more information is extracted for some images through gray scaling which might not be possible if the same algorithms or processes are applied to a color image. Features required for extraction become much more visible.

5. For a better understanding of image processing

Methods of converting Color image to Grayscale using OpenCV

In this article we’ll explore three methods of converting a colored image to grayscale color space. The three methods are as follows:

1. Using cv2.imread() function with flag=0

2. Using cv2.cvtColor() method

3. Using Averaging method

1. Using cv2.imread() function with flag=0 in OpenCV

The cv2.imread function provides the option of specifying how an image should be loaded by making use of the flag parameter. The flag parameter of the imread function indicates how the image should be read. There are various modes in which the image could be loaded. The modes to which the flag can be set are listed in the given table.

IMREAD_UNCHANGED Python:CV.IMREAD_UNCHANGED If set, return the loaded image as is (with alpha channel, otherwise it gets cropped). Ignore EXIF orientation
IMREAD_GRAYSCALE Python: CV.IMREAD_GRAYSCALE If set, always converts the image to the single-channel grayscale image (codec internal conversion).
IMREAD_COLOR Python: CV.IMREAD_COLOR If set, always converts the image to the 3 channel BGR color image.
IMREAD_ANYDEPTH Python: CV.IMREAD_ANYDEPTH If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit.
IMREAD_ANYCOLOR Python: CV.IMREAD_ANYCOLOR If set, the image is read in any possible color format.
IMREAD_LOAD_GDAL Python: CV.IMREAD_LOAD_GDAL If set, use the gdal driver for loading the image.
IMREAD_REDUCED_GRAYSCALE_2 Python:CV.IMREAD_REDUCED_GRAYSCALE_2 If set, always converts the image to the single channel grayscale image and the image size is reduced 1/2.
IMREAD_REDUCED_COLOR_2 Python:CV.IMREAD_REDUCED_COLOR_2 If set, always converts the image to the 3 channel BGR color image and the image size is reduced 1/2.
IMREAD_REDUCED_GRAYSCALE_4 Python:CV.IMREAD_REDUCED_GRAYSCALE_4 If set, always converts the image to the single channel grayscale image and the image size is reduced 1/4.
IMREAD_REDUCED_COLOR_4 Python:CV.IMREAD_REDUCED_COLOR_4 If set, always converts the image to the 3 channel BGR color image and the image size is reduced 1/4.
IMREAD_REDUCED_GRAYSCALE_8 Python:CV.IMREAD_REDUCED_GRAYSCALE_8 If set, always converts the image to the single-channel grayscale image and the image size is reduced 1/8.
IREAD_REDUCED_COLOR_8 Python:CV.IMREAD_REDUCED_COLOR_8 If set, always converts the image to the 3 channel BGR color image and the image size is reduced 1/8.

Implementation of cv2.imread() function with flag=0 in OpenCV

# Importing OpenCV
import cv2

# Reading the image in grayscale mode by setting the flag as 0
img = cv2.imread(r'C:\Users\tushi\Downloads\PythonGeeks\flower.jpg', 0)

# Displaying the image
cv2.imshow('grayscale', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

original imread

imread

 

2. Using cv2.cvtColor() method in OpenCV

cvtColor() function converts an image between color spaces. The OpenCV library offers more than 150 color space conversion functions.

Syntax:

cv2.cvtColor(src, code, dst, dstCn)

Parameters of cv2.cvtColor() method in OpenCV:

1. src: Source image or the image which has to be converted to another color space.

2. code: color space conversion codes provided by OpenCV

3. dst: Output image of the same size and depth as source image.

4. dstCn: Number of channels of the output image

5. Return Value: The function returns a converted image

Implementation of cv2.cvtColor() method in OpenCV

# Importing opencv
import cv2

# Importing matplotlib.pyplot
import matplotlib.pyplot as plt

# Reading the image
image = cv2.imread(r'C:\Users\tushi\Downloads\PythonGeeks\flower.jpg')
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Displaying the original image
plt.imshow(image)

original imread

# Converting into grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Displaying the converted image
plt.imshow(gray_image, cmap='gray')

grayscale cvt

3. Averaging method in OpenCV

Averaging method or pixel manipulation method is useful to convert a color image array to a grayscale array, for each pixel of the image. It consists of computing the average of the three colors. For an RGB image, we have to add the values of respective red, green and blue pixels and divide by 3.

Grayscale pixel value = (R + G + B) / 3

Implementation of OpenCV Averaging method

# Importing OpenCV
import cv2

# Reading the image in grayscale mode by setting the flag as 0
img = cv2.imread(r'C:\Users\tushi\Downloads\PythonGeeks\flower.jpg')

# Obtaining dimensions of the image array
(row, col) = img.shape[0:2]

# Take the average of RGB values to convert to grayscale
 for i in range(row):
  for j in range(col):
   img[i, j] = sum(img[i, j]) * 0.33

# Displaying the image
cv2.imshow('grayscale', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

original imread

averaging

Binary conversion in OpenCV

Binary images are images for which the pixels have only two possible intensity values. These are displayed as black and white, where each pixel of the image has the value 0 or 255 representing black and white.

Importance of OpenCV Binary conversion

1. Binary images are particularly useful for image processing as they allow easy separation of an object from the background. The process of segmentation allows the labeling of each pixel as the background pixel or the object pixel and assigns corresponding intensity values.

2. Binary images find several applications as they are the simplest images to process, they are an impoverished representation of the image information.

3. These images are used when necessary information is to be obtained by the silhouette of the object and the silhouette of the object can be obtained easily.

4. Binary images find use in digital image processing as masks or thresholding.

Thresholding in OpenCV

Thresholding is an image segmentation process, where a common function is applied to the pixels of an image to make images easier to analyze. The same threshold value is used for each pixel value. If the pixel value is less than the threshold value, it is updated to 0, otherwise, it is updated to a maximum value. In OpenCV, cv2.threshold() is used for thresholding. In thresholding, an image is converted from color or grayscale into a binary image.

Syntax:
cv2.threshold(src, thresh, maxval, type, dst)

Parameters of thresholding in OpenCV

1. src: Source image or the input image to which the threshold function will be applied

2. dst: Output array of the same size and depth as source image

3. thresh: Threshold value for the image.

4. maxval: Maximum value for THRESH_BINARY and THRESH_BINARY_INV methods

5. type: The type of threshold provided by OpenCV

Mathematically, the THRESH_BINARY method is as below:

grayscale and binary equation

1. Colored to binary image conversion in OpenCV

Implementation of OpenCV Colored image to binary image conversion

# Importing opencv
import cv2

# Importing matplotlib.pyplot
import matplotlib.pyplot as plt

# Reading the image
image = cv2.imread(r'C:\Users\tushi\Downloads\PythonGeeks\flower.jpg')
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Displaying the original image
plt.imshow(image)

original imread

# Converting into grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

grayscale for binary

# Displaying the converted image
plt.imshow(gray_image, cmap='gray')

# Converting to binary image using thresholding
(thresh, binary_image) = cv2.threshold(gray_image, 175, 255, cv2.THRESH_BINARY)

# Displaying binary image
plt.imshow(binary_image, cmap='gray')

binary

 

2. Grayscale to binary conversion in OpenCV

Implementation of Grayscale to binary conversion in OpenCV

# Importing OpenCV
import cv2

# Reading the image in grayscale mode by setting the flag as 0
img = cv2.imread(r'C:\Users\tushi\Downloads\PythonGeeks\flower.jpg', 0)
(thresh, binary_image) = cv2.threshold(img, 175, 255, cv2.THRESH_BINARY)

# Displaying original grayscale image and binary image
cv2.imshow('Original Image', img)
cv2.imshow('Binary Image', binary_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

grayscale for binary

grayscale to binary

Conclusion

In this article, we learned about color spaces and color space conversion. We understood the grayscale and binary color spaces and how we can convert any image to these color spaces using functions provided in the OpenCV library. Furthermore, we implemented the conversion of color image to grayscale using three methods available with OpenCV library and we converted color and grayscale images to binary images using thresholding.

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google | Facebook


Leave a Reply

Your email address will not be published. Required fields are marked *