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

3 次查看(过去 30 天)
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.

回答(2 个)

Walter Roberson
Walter Roberson 2016-9-26
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 个评论
Guillaume
Guillaume 2016-9-29
Matlab is not C. Writing matlab code like it was C code is not going to be efficient. You could write an efficient and accurate matlab rgb to hsv conversion in about 5 lines of code. However, mathworks have already done the work for you with the rgb2hsv and hsv2rgb function they provide.
The code you've written will not be more accurate than the function provided by matlab and certainly will be a lot slower, so what's the point?
Walter Roberson
Walter Roberson 2016-9-29
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.

请先登录,再进行评论。


Dilshad Ahmad
Dilshad Ahmad 2016-9-29
You can do by colormap function like I=Imread('your colour image');
Colormap HSV

Community Treasure Hunt

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

Start Hunting!

Translated by