How to display HSV image after using RGBtoHSV converter function in c++?

Tomek eM picture Tomek eM · Jan 6, 2015 · Viewed 14.4k times · Source

Good evening, on the internet we can find a lot of algorithm to convert RGB pixel values to HSV, but I can't find function to display it. I'm using MS Visual Studio 2013 and openCV library. I know there is built function to get HSV image: cvtColor(obrazeczek1, obrazeczek1, CV_BGR2HSV); but I try to do this without this function. For example, to get gray images I using function:

#define NORMALIZE_RGB(x) \
    (x > 255 ? 255 : (x < 0 ? 0 : x))

cv::Mat rgb2grey(cv::Mat& I)
{
CV_Assert(I.depth() != sizeof(uchar));
cv::Mat  res(I.rows, I.cols, CV_8UC3);
switch (I.channels())  {
case 3:
    cv::Mat_<cv::Vec3b> _I = I;
    cv::Mat_<cv::Vec3b> _R = res;

    for (int i = 0; i < I.rows; ++i)
        for (int j = 0; j < I.cols; ++j){

        int grey = ((_I(i, j)[0]) + (_I(i, j)[1]) + (_I(i, j)[2])) / 3;

            _I(i, j)[0] = NORMALIZE_RGB(grey);
            _I(i, j)[1] = NORMALIZE_RGB(grey);
            _I(i, j)[2] = NORMALIZE_RGB(grey);
        }

    res = _I;
    break;
}
return res;
}

and to call function and display image:

cv::Mat image = cv::imread("name.jpg");
cv::Mat img = rgb2grey(image);
cv::imshow("Grey image", img);

I found here Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both tips. I know how to convert RGB pixel to HSV, but how to display this matrix using imshow? I also found function rgb2hsv but I dont have any idea what to change, to display it. This is a function:

void rgb2hsv(double r, double g, double b, double &h, double &s, double &v)
{
v = max(max(r, g), b);
double t = min(min(r, g), b);
double delta = v - t;
if (v != 0.0)
    s = delta / v;
else
    s = 0.0;
if (s == 0.0)
    h = 0.0;
else
{
    if (r == v)
        h = (g - b) / delta;
    else
        if (g == v)
            h = 2.0 + (b - r) / delta;
        else
            if (b == v)
                h = 4.0 + (r - g) / delta;
    h = h * 60.0;
    if (h < 0.0)
        h += 360;
}
}

There is not here similar question so plese help.

Answer

user7678894 picture user7678894 · Mar 13, 2017

It doesn´t make sense to display an image that has been converted to HSV using imshow().

imshow() thinks, the Matrix is in BGR order. Converting the image to HSV just converts the RGB values to HSV channel values.

It was before 3 channel and after the conversion it is also 3 channel but other values. imshow() still wants to display the image as RGB image but then with HSV values which leads to an invalid image.

Just convert it back to RGB to make imshow() show the image correctly.

Edit

Mat hsv, bgr; // hsv is the hsv image you want to display
cvtColor(hsv, bgr, CV_HSV2BGR);
imshow("lolz", bgr);