Sunday 3 December 2023

Convert an image to grayscale in OpenCV

 

Using ‘cvtColor’ method, we can convert the color space of an image.

 

Signature

dstImage = cv2.cvtColor(srcImage, code[, dst[, dstCn]])

 

Example

grayscale_image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)

 

Following table summarizes the parameters of cvtColor method.

 

Parameter

Description

src

Source image that you want to convert to.

code

Specifies the destination image color code.

 

Ex: cv2.COLOR_BGR2GRAY

dst

It is an optional parameter, where the converted image will be stored.

dstCn

Specifies the number of channels in the destination image. For example, RGB color space has 3 channels, HSV color space has three channels: one for hue, one for saturation, and one for value.

 

What is color space?

Color space is a way of representing the colors in a digital space. For example, RGB (Red, Green, Blue) is the most common used color space. Each color space has its own set of rules and coordinates to represent the colors.

 

Following are some mostly used color spaces.

 

1.   RGB: This color space represent the colors by mixing various intensities of red, green, and blue channels.

2.   Grayscale: It represents images in shades of gray (from black to white.) rather than color. Each pixel in a grayscale image is represented by a single value, which represents the brightness of the pixel. Gray scale images are used where color information is not needed.

3.   HSV (Hue, Saturation, Value): Hue represents the type of color (e.g., red, blue, green), Saturation represents the intensity or purity of the color, and Value represents the brightness or lightness of the color.

 

Following example convert the BGR color image to Grayscale image.

 

to_grayscale.py

import cv2 as cv

def resize_frame(frame, scale_width=0.5, scale_height=0.5):
    width = int(frame.shape[1] * scale_width)
    height = int(frame.shape[0] * scale_height)
    new_dimensions = (width, height)
    return cv.resize(frame, new_dimensions, interpolation=cv.INTER_AREA)

image = cv.imread('taj.jpeg')
cv.imshow('BGR image', resize_frame(image, 0.5, 0.5))

grayscale_image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
cv.imshow('Gray scale image', resize_frame(grayscale_image, 0.5, 0.5))

cv.waitKey(0)

# Close the OpenCV windows
cv.destroyAllWindows()

 

Output

 

Simple RGB image

 


Grayscale version of the same image.


 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment