且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在MATLAB中将HSV转换为RGB

更新时间:2023-01-27 22:31:04

使用内置的 Google的颜色选择器对此进行测试,我们可以看到是正确的解决方案.如果要在MATLAB中执行其他任何RGB操作,则将值保留在(0-1)范围内,因为这是MATLAB始终使用的值.

如果您有许多HSV值,请将它们存储在具有H,S和V列的mx3矩阵中.然后,与上述类似,您可以执行以下操作:

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

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?

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.

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;