Convert Image from RGB to HSV Color Space using OpenCV (2024)

HSV is a color space that has three components: hue, saturation and value. When implementing object tracking based on color, images are often converted from RGB to HSV color space. Using HSV is much easier to represent a color and extract a colored object from an image than using RGB color space.

This tutorial provides an example how to convert an image from RGB to HSV color space using OpenCV.

OpenCV has the cvtColor function which is used for converting an image from one color space to another. This function accepts color conversion code. COLOR_BGR2HSV code allows converting from RGB to HSV color space. Note that, OpenCV loads an image where the order of the color channels is Blue, Green, Red (BGR) instead of RGB.

import cv2img = cv2.imread('test.jpg')hsvImg = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)cv2.imshow('RGB image', img)cv2.imshow('HSV image', hsvImg)cv2.waitKey(0)cv2.destroyAllWindows()
#include <opencv2/opencv.hpp>using namespace cv;int main(){ Mat img = imread("test.jpg"); Mat hsvImg; cvtColor(img, hsvImg, COLOR_BGR2HSV); imshow("RGB image", img); imshow("HSV image", hsvImg); waitKey(0); destroyAllWindows(); return 0;}
#include <opencv2/opencv.hpp>#include <opencv2/cudaimgproc.hpp>using namespace cv;int main(){ Mat img = imread("test.jpg"); cuda::GpuMat gpuImg(img); cuda::cvtColor(gpuImg, gpuImg, COLOR_BGR2HSV); Mat hsvImg(gpuImg); imshow("RGB image", img); imshow("HSV image", hsvImg); waitKey(0); destroyAllWindows(); return 0;}
package app;import org.opencv.core.Core;import org.opencv.core.Mat;import org.opencv.highgui.HighGui;import org.opencv.imgcodecs.Imgcodecs;import org.opencv.imgproc.Imgproc;public class Main{ static { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); } public static void main(String[] args) { Mat img = Imgcodecs.imread("test.jpg"); Mat hsvImg = new Mat(); Imgproc.cvtColor(img, hsvImg, Imgproc.COLOR_BGR2HSV); HighGui.imshow("RGB image", img); HighGui.imshow("HSV image", hsvImg); HighGui.waitKey(0); HighGui.destroyAllWindows(); System.exit(0); }}

Result:

Convert Image from RGB to HSV Color Space using OpenCV (1)

Convert Image from RGB to HSV Color Space using OpenCV (2024)
Top Articles
Latest Posts
Article information

Author: Rob Wisoky

Last Updated:

Views: 6537

Rating: 4.8 / 5 (68 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Rob Wisoky

Birthday: 1994-09-30

Address: 5789 Michel Vista, West Domenic, OR 80464-9452

Phone: +97313824072371

Job: Education Orchestrator

Hobby: Lockpicking, Crocheting, Baton twirling, Video gaming, Jogging, Whittling, Model building

Introduction: My name is Rob Wisoky, I am a smiling, helpful, encouraging, zealous, energetic, faithful, fantastic person who loves writing and wants to share my knowledge and understanding with you.