Please checked and optimize this code
Code: Select all
;-TOP
; Source Link: https://stackoverflow.com/questions/3018313/algorithm-to-convert-rgb-to-hsv-and-hsv-to-rgb-in-range-0-255-for-both
Structure rgb
r.d; // a fraction between 0 and 1
g.d; // a fraction between 0 and 1
b.d; // a fraction between 0 and 1
EndStructure
Structure hsv
h.d; // angle in degrees
s.d; // a fraction between 0 and 1
v.d; // a fraction between 0 and 1
EndStructure
Procedure rgb2hsv(*in.rgb, *out.hsv)
Protected.d min, max, delta;
If *in\r < *in\g
If *in\r < *in\b
min = *in\r
Else
min = *in\b
EndIf
Else
If *in\g < *in\b
min = *in\g
Else
min = *in\b
EndIf
EndIf
If *in\r > *in\g
If *in\r > *in\b
max = *in\r
Else
max = *in\b
EndIf
Else
If *in\g > *in\b
max = *in\g
Else
max = *in\b
EndIf
EndIf
*out\v = max; // v
delta = max - min;
If delta < 0.00001
*out\s = 0;
*out\h = 0; // undefined, maybe nan?
ProcedureReturn 0
EndIf
If max > 0.0 ; NOTE: If Max is == 0, this divide would cause a crash
*out\s = delta / max
Else
; If max is 0, then r = g = b = 0
; s = 0, h is undefined
*out\s = 0.0;
*out\h = NaN(); its now undefined
ProcedureReturn 0
EndIf
If *in\r >= max ; > is bogus, just keeps compilor happy
*out\h = ( *in\g - *in\b ) / delta ; between yellow & magenta
ElseIf *in\g >= max
*out\h = 2.0 + ( *in\b - *in\r ) / delta ; between cyan & yellow
Else
*out\h = 4.0 + ( *in\r - *in\g ) / delta ; between magenta & cyan
EndIf
*out\h * 60.0 ; degrees
If( *out\h < 0.0 )
*out\h + 360.0;
EndIf
EndProcedure
Procedure hsv2rgb(*in.hsv, *out.rgb)
Protected.d hh, p, q, t, ff;
Protected.i i ;
If *in\s <= 0.0 ; // < is bogus, just shuts up warnings
*out\r = *in\v;
*out\g = *in\v;
*out\b = *in\v;
ProcedureReturn
EndIf
hh = *in\h;
If hh >= 360.0
hh = 0.0;
EndIf
hh / 60.0 ;
i = hh ;
ff = hh - i ;
p = *in\v * (1.0 - *in\s);
q = *in\v * (1.0 - (*in\s * ff));
t = *in\v * (1.0 - (*in\s * (1.0 - ff)));
Select i
Case 0:
*out\r = *in\v;
*out\g = t ;
*out\b = p ;
Case 1:
*out\r = q;
*out\g = *in\v;
*out\b = p ;
Case 2:
*out\r = p;
*out\g = *in\v;
*out\b = t ;
Case 3:
*out\r = p;
*out\g = q;
*out\b = *in\v;
Case 4:
*out\r = t;
*out\g = p;
*out\b = *in\v;
Case 5:
Default:
*out\r = *in\v;
*out\g = p ;
*out\b = q ;
EndSelect
ProcedureReturn
EndProcedure
Macro NormRGB(Color, sRGB)
sRGB\r = Red(Color) / 255.0
sRGB\g = Green(Color) / 255.0
sRGB\b = Blue(Color) / 255.0
EndMacro
Macro ScaleRGB(sRGB)
RGB(sRGB\r*255, sRGB\g*255, sRGB\b*255)
EndMacro
Define rgb1.RGB
Define hsv1.hsv
Define color.i
color = $73B966
Debug "Color = " + Hex(color)
Debug "RGB2HSV"
NormRGB(color, rgb1)
rgb2hsv(rgb1, hsv1)
With hsv1
Debug "H = " + \h
Debug "S = " + \s
Debug "V = " + \v
EndWith
Debug "HSV2RGB"
hsv2rgb(hsv1, rgb1)
With rgb1
Debug "R = " + \r
Debug "G = " + \g
Debug "B = " + \b
EndWith
Debug "Color = " + Hex(ScaleRGB(rgb1))