OpenCV: convert Scalar to different color space

fuenfundachtzig picture fuenfundachtzig · Apr 4, 2017 · Viewed 9k times · Source

I am using a Scalar to define the color of a rectangle I am drawing with OpenCV:

rectangle(imgOriginal, Point(0, 0), Point(25, 50), Scalar(H, S, V), CV_FILLED);

However, the color is defined in HSV color space rather than RGB (imgOriginal is RGB).

How do I convert Scalar (or its input, the integer variables H, S, and V) to RGB?

(So far I only found answers telling me how to convert a whole image with cvtColor which is not what I want.)

Answer

Morris Franken picture Morris Franken · Apr 5, 2017

Although not optimal, You can use the following:

Scalar ScalarHSV2BGR(uchar H, uchar S, uchar V) {
    Mat rgb;
    Mat hsv(1,1, CV_8UC3, Scalar(H,S,V));
    cvtColor(hsv, rgb, CV_HSV2BGR);
    return Scalar(rgb.data[0], rgb.data[1], rgb.data[2]);
}