0

I am trying to make an object tracker using OpenCV 3.1.0 and C++ following this Python example: http://docs.opencv.org/3.1.0/df/d9d/tutorial_py_colorspaces.html#gsc.tab=0.

I have some problems with cvtColor() function, because it changes the colors of my images and not its colorspace. I have this code:

Mat original_image;
original_image = imread(argv[1], CV_LOAD_IMAGE_COLOR); // The image is passed as arg
if (!original_image.data)
{
    printf("Problem!\n");
    return -1;
}

// From BGR to HSV
Mat hsv_image(original_image.rows, original_image.cols, original_image.type());
cvtColor(original_image, hsv_image, CV_BGR2HSV);
imwrite("hsv_image.png", hsv_image);

original_image is a CV_8UC3, compatible with cvtColor() and should be originally in BGR colorspace.

I made the test image below with GIMP:

Test image

And I get this image as result:

HSV image - result

I decided to try the conversion from BGR to RGB, changing BGR2HSV to BGR2RGB, and with the same test image, I get this result

RGB image - result

Here, it's more clear that the channels of the image are changed directly...

Has anybody any idea about what's happening here?

Scott Stensland
  • 26,870
  • 12
  • 93
  • 104
  • 2
    In the second image, you're interpreting the channels of [HSV image](https://en.wikipedia.org/wiki/HSL_and_HSV) (that is Hue, Saturation, Value) as Blue, Green and Red respectively. What did you expect to get as a result (imwrite expects BGR)? – Dan Mašek May 15 '16 at 18:32
  • Basically you didn't notice this crucial information in the documentation of [`imwrite()`](http://docs.opencv.org/3.0-beta/modules/imgcodecs/doc/reading_and_writing_images.html#imwrite): "Only 8-bit... 3-channel (with ‘BGR’ channel order) images can be saved using this function." – Dan Mašek May 15 '16 at 18:47
  • Thank you so much Dan! I really didn't check that, I was thinking that the problem was in the transformation and I didn't check the imwrite() function. Thank you again! –  May 15 '16 at 19:09

2 Answers2

1

Function imwrite doesn't care what color space mat has and this information isn't stored. According to documentation it's BGR order.

So before saving image you should be sure it is BGR.

If you really want to save image as HSV use file storages

Giebut
  • 342
  • 2
  • 13
-1

Try this:

// From BGR to HSV
Mat hsv_image;
cvtColor(original_image, hsv_image, COLOR_BGR2HSV);
imwrite("hsv_image.png", hsv_image);
PR16
  • 39
  • 3
  • That will have an identical effect to the last 3 lines in the OPs example. It also doesn't answer his question, which is not understanding why saving an HSV image with `imwrite` returns nonsense. – Dan Mašek May 15 '16 at 18:45