how to convert RGB to HSV(Lossless) in matlab?

6 views (last 30 days)
https://bitbucket.org/chernov/colormath/src/012a5ae28033dc8e91ec66ec349c95d81caddb71/colormath/hsv.cpp?at=default&fileviewer=file-view-default. This link gave me code to convert rgb to hsv lossless but it is in C++ . I want in matlab. I am new to matlab please help me.

Answers (2)

Walter Roberson
Walter Roberson on 26 Sep 2016
rgb2hsv(im2double(YourImage))
Note: this is only lossless if YourImage is no more than approximately 32 bit depth (I would need to work out the exact boundaries.) In particular, if your image is double precision to start with and uses the full 53 bits of precision per channel per pixel, then this will not be lossless; if you have those kinds of precision requirements then you will need to use an extended precision mechanism (such as the Symbolic Toolbox)
  11 Comments
Walter Roberson
Walter Roberson on 29 Sep 2016
You are presuming here that lossless rgb to hsv to rgb is possible when you use uint8 to store the hsv . It is not clear that is the case.
If you use
HSVd = rgb2hsv(YourImage);
HSVu = im2uint8(HSVd);
HSVud = im2double(HSVu);
RGBd = hsv2rgb(HSVud);
RGBu = im2uint8(RGBd);
then HSVu will be a uint8 representation of the HSV, and RGBu will be the reconstruction after going through the RGB->HSV (uint8) -> RGB steps. You will find that the values are not exactly the same. My tests show a maximum difference of 3.
[gR,gG,gB] = ndgrid(uint8(0:255));
YourImage = cat(3, reshape(gR,[],size(gR,3)), reshape(gG,[],size(gG,3)), reshape(gB, [], size(gB,3)));
HSVd = rgb2hsv(YourImage);
HSVu = im2uint8(HSVd);
HSVud = im2double(HSVu);
RGBd = hsv2rgb(HSVud);
RGBu = im2uint8(RGBd);
max(max(abs(double(RGBu)-double(YourImage))))
However if you do not go through uint8,
HSVd = rgb2hsv(YourImage);
RGBd = hsv2rgb(HSVd);
RGBu = im2uint8(RGBd);
then the conversion is exact.
You could try other methods of converting from the [0,1] range to [0,255], such as floor(HSVd*255) or round() or fix(), but you will find that those then fail the test of converting exactly when converting im2double(YourImage) back to YourImage, which im2uint8() handles fine.

Sign in to comment.


Dilshad Ahmad
Dilshad Ahmad on 29 Sep 2016
You can do by colormap function like I=Imread('your colour image');
Colormap HSV
  1 Comment
Walter Roberson
Walter Roberson on 29 Sep 2016
Unfortunately not relevant to this question.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!