Request for an HSV to RGB algorithm

General Help regarding HMG, Compilation, Linking, Samples

Moderator: Rathinagiri

Post Reply
bluebird
Posts: 172
Joined: Wed Sep 28, 2016 3:55 am
DBs Used: DBF

Request for an HSV to RGB algorithm

Post by bluebird »

Dear HMG people

Does anyone have an existing HMG/Clipper coded algorithm to convert HSV (hue,saturation,value) to RGB colors.

There are some examples in other languages on the net, but a proven version in HMG would help avoid porting mistakes.

Thanks, - not sure what forum section to use to request a piece of code.

PS. The merry Christmas posts were great indicators of friendliness of HMG folks
User avatar
Anand
Posts: 595
Joined: Tue May 24, 2016 4:36 pm
DBs Used: DBF

Re: Request for an HSV to RGB algorithm

Post by Anand »

Hi bluebird,

I have this code, which is in C, downloaded from web.
See if it helps you.

Code: Select all

/**
 * Converts an HSV color value to RGB. Conversion formula
 * adapted from http://en.wikipedia.org/wiki/HSV_color_space.
 * Assumes h, s, and v are contained in the set [0, 1] and
 * returns r, g, and b in the set [0, 255].
 *
 * @param   Number  h       The hue
 * @param   Number  s       The saturation
 * @param   Number  v       The value
 * @return  Array           The RGB representation
 */
function hsvToRgb(h, s, v) {
  var r, g, b;

  var i = Math.floor(h * 6);
  var f = h * 6 - i;
  var p = v * (1 - s);
  var q = v * (1 - f * s);
  var t = v * (1 - (1 - f) * s);

  switch (i % 6) {
    case 0: r = v, g = t, b = p; break;
    case 1: r = q, g = v, b = p; break;
    case 2: r = p, g = v, b = t; break;
    case 3: r = p, g = q, b = v; break;
    case 4: r = t, g = p, b = v; break;
    case 5: r = v, g = p, b = q; break;
  }

  return [ r * 255, g * 255, b * 255 ];
}
Regards,

Anand
Regards,

Anand

Image
PeteWG
Posts: 176
Joined: Sun Mar 21, 2010 5:45 pm

Re: Request for an HSV to RGB algorithm

Post by PeteWG »

Anand wrote: Wed Dec 27, 2017 10:05 am I have this code, which is in C, downloaded from web.
...
Thanks Anand,
and although I'm not sure what kind of C-dialect is the code posted above, here is the same code "ported" to Harbour:
(warning: not tested!)

Code: Select all

FUNCTION HsvToRgb(h, s, v)
// NOTE: h,s,v given values must be in the range 0..1
  LOCAL r, g, b
  LOCAL i := Int(h * 6)
  LOCAL f := h * 6 - i
  LOCAL p := v * (1 - s)
  LOCAL q := v * (1 - f * s)
  LOCAL t := v * (1 - (1 - f) * s)

  SWITCH (i % 6)
    CASE 0 ; r := v ; g := t ; b := p; EXIT
    CASE 1 ; r := q ; g := v ; b := p; EXIT
    CASE 2 ; r := p ; g := v ; b := t; EXIT
    CASE 3 ; r := p ; g := q ; b := v; EXIT
    CASE 4 ; r := t ; g := p ; b := v; EXIT
    CASE 5 ; r := v ; g := p ; b := q; EXIT
  ENDSWITCH

  r := Max( Min( r*256, 255 ), 0 )
  g := Max( Min( g*256, 255 ), 0 )
  b := Max( Min( b*256, 255 ), 0 )
  
  RETURN { r , g , b }
  
regards,
Pete
Post Reply