Search code examples
matlabrgbhsv

Convert HSV to RGB in MATLAB


I have [H,S,V] colour values.
How can I convert them to [R,G,B] in MATLAB?

I've tried with the algorithm but I'm having some problems. Can anyone help me with the code?


Solution

  • Using the in-built hsv2rgb function...

    % Some colour in HSV, [Hue (0-360), Saturation (0-1), Value (0-1)]
    myHSV = [217, 0.4, 0.72];
    % hsv2rgb takes Hue value in range 0-1, so...
    myHSV(1) = myHSV(1) / 360;
    % Convert to RGB with values in range (0-1)
    myRGBpct = hsv2rgb(myHSV);
    % Convert to RGB with values in range (0-255)
    myRGB255 = myRGBpct * 255;
    

    Putting all of this together, we can simply do

    myHSV = [217, 0.4, 0.72];
    myRGB255 = hsv2rgb(myHSV ./ [360, 1, 1]) * 255; 
    >> myRGB255 = [110.16, 138.31, 183.60]
    

    Testing this using Google's color picker, we can see this is the correct solution. If you wanted to do any other RGB manipulation within MATLAB then leave the values in the range (0-1), since that is what MATLAB always uses.

    blue

    If you have many HSV values, store them in an mx3 matrix, with columns H,S and V. Then similarly to the above you can do:

    myHSV = [217, 0.4, 0.72;
             250, 0.5, 0.2; 
             % ... more rows
            ];
    myHSV(:,1) = myHSV(:,1) / 360;
    myRGB255 = hsv2rgb(myHSV) * 255;