Conv-Color RGB-16 to HSV

From Vectorlab
Jump to: navigation, search


Converts a RGB-16 triplet into HSV returning unrounded Hue angle in degrees, Saturation and Value in range 0-1. Mind that this routines takes 16-bit values (range 0-65535). There is a second variant which returns the values as they are displayed in the VW color palette: Hue as angle (degrees) and Saturation and Value in range 0-255. By Orso B. Schmid


{ Orso *********************************************** }
{ Converts RGB to HSV }
{ returns a Hue angle in degrees, Saturation and Value in range 0-1, all unrounded }
{ takes 16-bit values (range 0-65535), as returned by most standard VW color routines }
{ based upon code in http://de.wikipedia.org/wiki/HSV-Farbraum }
{ for example }
{ red: 	rgb = 65535; 0; 0 --> hsv = 0, 1, 1 }
{ ugly lila: 	rgb = 49807; 39455; 46877 --> hsv = 316.98; 0.207; 0.76 }
PROCEDURE C_RGBtoHSV(r, g, b: LONGINT; VAR h, s, v: REAL);
	VAR
		maxRGB, minRGB, delta : REAL;
		
	BEGIN
		h := 0;
		maxRGB := Max(Max(r, g), b);
		minRGB := Min(Min(r, g), b);
		delta := maxRGB-minRGB;
			
		IF maxRGB = 0 THEN
			s := 0
		ELSE
			s := delta/maxRGB;
		
		IF delta <> 0 THEN BEGIN
			{ between yellow & magenta }
			IF maxRGB = r THEN 
				h := (g-b)/delta
				
			{ between cyan & yellow }
			ELSE IF maxRGB = g THEN
				h := (2 + (b-r)/delta)
				
			{ between magenta & cyan }
			ELSE IF maxRGB = b THEN
				h := (4 + (r-g)/delta);
		END;
		
		h := h * 60;
		IF h < 0 THEN
			h := h + 360;
		
		v := maxRGB/65535;
	END;


{ Orso *********************************************** }
{ the same as above, but returns saturation and value in range 0-255 as displayed by the VW help hints in the color palette, keeping the hue in angle }
{ for example: }
{ red: 	rgb = 65535; 0; 0 --> hsv = 0, 1, 1 }
{ ugly lila: 	rgb = 49807; 39455; 46877 --> hsv = 317; 53; 94 }
PROCEDURE C_RGBtoHSV_VW(r, g, b: LONGINT; VAR h, s, v: REAL);
	BEGIN
		C_RGBtoHSV(r, g, b, h, s, v); 
		
		h := round(h);
		s := round(s * 255);
		v := round(v * 255);
	END;