Skip to content

Instantly share code, notes, and snippets.

@dzonesasaki
Created March 6, 2015 05:05
Show Gist options
  • Save dzonesasaki/75069067cab3dd732121 to your computer and use it in GitHub Desktop.
Save dzonesasaki/75069067cab3dd732121 to your computer and use it in GitHub Desktop.
RGB to HSV convert function
% myRgb2Hsv.m
% by Dzone 150306_14:03
function arryHsv = myRgb2Hsv(arryRgb)
% RGB is normalized value (0.0 to 1.0)
[sx,sy,sp] = size(arryRgb);
red = reshape(arryRgb(:,:,1),sx*sy,1);
green = reshape(arryRgb(:,:,2),sx*sy,1);
blue = reshape(arryRgb(:,:,3),sx*sy,1);
[maxv,maxi] = max([red,green,blue].');
[minv,mini] = min([red,green,blue].');
maxv=maxv.';
maxi=maxi.';
minv=minv.';
mini=mini.';
divv = maxv - minv;
isGray= (red==green)&&(blue==green);
hue = (1-isGray).*(...
(mini==1).*((blue - green)*60./divv + 180)...
+ (mini==2).*((red - blue)*60./divv + 300)...
+ (mini==3).*((green - red)*60./divv + 60) ); % isGray==1 then 0
%--- hue must be 0 to 360
hue = (hue > 360).*(hue - 360*floor(hue/360)) ...
+ (hue < 0).*(hue - 360*floor(hue/360)) ...
+ (hue <= 360).*(hue >= 0).*hue;
%--- normalized by 360 deg
hue = hue / 360;
sat = divv./maxv;
bri = maxv;
hue = reshape(hue , sx,sy);
sat = reshape(sat , sx,sy);
bri = reshape(bri , sx,sy);
arryHsv = cat(3, hue, sat, bri);
endfunction
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment