Thursday, 1 February 2024

Convert BGR image to a different color space

cv2.cvtColor is used for color space conversions on OpenCV. This method is helpful, when you want to analyze or manipulate images in different color spaces.

Signature

cv2.cvtColor(src, code, dst)

 

Following table summarizes the parameters of cvtColor method.

Parameter

Description

src

Source image that we want to convert

code

Color space conversion code.

Ex: cv2.COLOR_BGR2RGB, cv2.COLOR_BGR2GRAY

dst

It is an optional parameter, specifies the destination image where the converted image will be stored. If not provided, OpenCV will create an output image for you.

 

Example 1: Convert the BGR image to Gray

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

 

Example 2: Convert BGR image to RGB

bgr_to_rgb = cv.cvtColor(image, cv.COLOR_BGR2RGB)

 

Example 3: Convert BGR image to HSV

bgr_to_hsv = cv.cvtColor(image, cv.COLOR_BGR2HSV)

 

Find the below working application.

 

bgr_to_other_color_spaces.py

import cv2 as cv

# Read the image as matrix of pixels
image = cv.imread('flowers.png')
image = cv.resize(image, (1000, 800))

# Display the image in new window
cv.imshow('Original image', image)

# Convert BGR image to RGB
bgr_to_gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
bgr_to_rgb = cv.cvtColor(image, cv.COLOR_BGR2RGB)
bgr_to_hsv = cv.cvtColor(image, cv.COLOR_BGR2HSV)

#bgr_to_bgr555 = cv.cvtColor(image, cv.COLOR_BGR2BGR555)
#bgr_to_bgr565 = cv.cvtColor(image, cv.COLOR_BGR2BGR565)
#bgr_to_gray = cv.cvtColor(image, cv.COLOR_BGR2YCrCb)
#bgr_to_gray = cv.cvtColor(image, cv.COLOR_BGR2HLS)
#bgr_to_gray = cv.cvtColor(image, cv.COLOR_BGR2BGRA)
#bgr_to_gray = cv.cvtColor(image, cv.COLOR_BGR2HLS_FULL)
#bgr_to_gray = cv.cvtColor(image, cv.COLOR_BGR2HSV)
#bgr_to_gray = cv.cvtColor(image, cv.COLOR_BGR2LAB)
#bgr_to_gray = cv.cvtColor(image, cv.COLOR_BGR2LUV)
#bgr_to_gray = cv.cvtColor(image, cv.COLOR_BGR2XYZ)

cv.imshow('bgr_to_gray', bgr_to_gray)
cv.imshow('bgr_to_rgb', bgr_to_rgb)
cv.imshow('bgr_to_hsv', bgr_to_hsv)

# Wait for Infinite amount of time for a keyboard key to be pressed
cv.waitKey(0)

# Close the OpenCV windows
cv.destroyAllWindows()

Output

 

Original image


 

 

BGR to Gray



BGR to RGB



BGR to HSV

 


  

Previous                                                    Next                                                    Home

No comments:

Post a Comment