PDA

View Full Version : RGB to HSV and vice versa conversion.



heinz85
01-23-2012, 04:09 AM
Hello.
Can anybody refer me to a reliable code snippet of RGB to HSV and vice versa conversion?

Thanks,
Heinrich

Thallius
01-23-2012, 07:28 AM
-(void)hsvToRGB:(struct rgbhsvColor*)color
{
if(color->saturation==0.0)
{
color->red=round(color->vvalue*255.0);
color->green=round(color->vvalue*255.0);
color->blue=round(color->vvalue*255.0);
}
else
{
float hTemp=0.0;

if(color->hue==360.0)
hTemp=0.0;
else
hTemp=color->hue/60.0;

int i=trunc(hTemp);
float f=hTemp-i;

float p=color->vvalue*(1.0-color->saturation);
float q=color->vvalue*(1.0-(color->saturation*f));
float t=color->vvalue*(1.0-(color->saturation*(1.0-f)));

switch (i)
{
default:
case 0:
case 6:
color->red=round(color->vvalue*255.0);
color->green=round(t*255.0);
color->blue=round(p*255.0);
break;
case 1:
color->red=round(q*255.0);
color->green=round(color->vvalue*255.0);
color->blue=round(p*255.0);
break;
case 2:
color->red=round(p*255.0);
color->green=round(color->vvalue*255.0);
color->blue=round(t*255.0);
break;
case 3:
color->red=round(p*255.0);
color->green=round(q*255.0);
color->blue=round(color->vvalue*255.0);
break;
case 4:
color->red=round(t*255.0);
color->green=round(p*255.0);
color->blue=round(color->vvalue*255.0);
break;
case 5:
color->red=round(color->vvalue*255.0);
color->green=round(p*255.0);
color->blue=round(q*255.0);
break;
}

}
return;
}

// calc HSV values of rgbhsvColor from RGB values
-(void)rgbToHSV:(struct rgbhsvColor*)color
{
UBYTE maxRGBValue=MAX(MAX(color->red,color->green),color->blue);
float minValue=MIN(MIN(color->red,color->green),color->blue);
float maxValue=maxRGBValue;
float hue,saturation,vvalue,delta;

minValue=minValue/255.0;
maxValue=maxValue/255.0;

vvalue=maxValue;
delta=vvalue-minValue;

if(delta==0)
saturation=0;
else
saturation=round(delta/vvalue);

if(saturation==0)
hue=0;
else
{
if(color->red==maxRGBValue)
hue=60.0*(float)(color->green-color->blue)/255.0/delta;
else
{
if(color->green==maxRGBValue)
hue=120.0+60.0*(float)(color->blue-color->red)/255.0/delta;
else
{
if(color->blue==maxRGBValue)
hue=240.0+60.0*(float)(color->red-color->green)/255.0/delta;
}
}
if(hue<0.0)
hue+=360.0;
}
color->hue=round(hue);
color->saturation=round(saturation);
color->vvalue=round(vvalue);
return;
}


hope that helps

Thallius

heinz85
01-23-2012, 03:44 PM
if(delta==0)
saturation=0;
???
are you sure it is not:

if (maxValue==0) saturation = 0; ?