Last Updated : 11 Aug, 2025
cv2.cvtColor() is an OpenCV function that converts an image from one color space to another.
It supports over 150 color conversion methods, but in most cases, only a few (like BGR↔GRAY or BGR↔RGB) are used frequently in real-world projects.
Reasons for Changing Color SpacesDifferent tasks require different representations of an image:
cv2.cvtColor(src, code[, dst[, dstCn]])
Parameters:
For the examples, we are using below image:
Example 1: Convert BGR to GrayscaleHere’s a simple Python code using OpenCV to read an image, convert it to grayscale and display it in a window.
Python
import cv2
src = cv2.imread(r'logo.png') # Read the image
# Convert to Grayscale
gray_image = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
# Display
cv2.imshow("Grayscale Image", gray_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output
Explanation:
Here’s a simple Python code using OpenCV to read an image, convert it from BGR to HSV color space and display the result.
Python
import cv2
src = cv2.imread(r'logo.png')
# Convert to HSV
hsv_image = cv2.cvtColor(src, cv2.COLOR_BGR2HSV)
cv2.imshow("HSV Image", hsv_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output
Explanation:
This Python code reads an image using OpenCV, converts it from BGR to RGB color format and then displays it using Matplotlib.
Python
import cv2
import matplotlib.pyplot as plt
src = cv2.imread(r'logo.png')
# Convert from BGR to RGB
rgb_image = cv2.cvtColor(src, cv2.COLOR_BGR2RGB)
# Display with Matplotlib
plt.imshow(rgb_image)
plt.title("RGB Image for Matplotlib")
plt.axis('off')
plt.show()
Output
Explanation:
Let’s see some of the most commonly used OpenCV color conversion codes:
Different color spaces are preferred for specific computer vision tasks because they highlight certain image features better. Let’s see some real-world applications of these conversions:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4