fuenfundachtzig
fuenfundachtzig

Reputation: 8352

OpenCV: convert Scalar to different color space

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.)

Upvotes: 11

Views: 12300

Answers (4)

tinkerbell
tinkerbell

Reputation: 421

This worked for me,

Mat rgb;
Mat hsv(1, 1, CV_8UC3, Scalar(224, 224, 160));

cvtColor(hsv, rgb, CV_HSV2BGR);
Scalar rgb = Scalar((int)rgb.at<cv::Vec3b>(0, 0)[0],(int)rgb.at<cv::Vec3b>(0, 0)[0],(int)rgb.at<cv::Vec3b>(0, 0)[0])

Upvotes: 4

j-a
j-a

Reputation: 1810

OpenCV 3.2.0. Note: h is in range [0,360] and l and s is in [0,1]

        Mat hls(1, 1, CV_32FC3, Scalar(h, l, s));
        Mat rgb;
        cvtColor(hls, rgb, COLOR_HLS2RGB);
        Scalar c = Scalar(255*rgb.at<float>(0,0), 255*rgb.at<float>(0,1), 255*rgb.at<float>(0,2));

Upvotes: 1

Morris Franken
Morris Franken

Reputation: 2555

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]);
}

Upvotes: 8

Rama
Rama

Reputation: 3305

Use this to convert a single value:

cv::Vec3f rgb;
cv::Vec3f hsv;
hsv[0] = H;
hsv[1] = S;
hsv[2] = V;
cvtColor(hsv, rgb, CV_HSV2BGR);

Then you can use it:

rectangle(imgOriginal, Point(0, 0), Point(25, 50), 
    Scalar(rgb[0], rgb[1], rgb[2]), CV_FILLED);

Upvotes: -1

Related Questions