2

NetLogo provides an extract-hsb that gets the hsb values for a NetLogo color. However, it doesn't appear to work on colors specified with an rgb list, even though rgb lists are legitimate colors in NetLogo. So my question is, how might one go about doing this manually?

BTW, I've added a feature request to NetLogo to extend extract-hsb appropriately: https://github.com/NetLogo/NetLogo/issues/643

Bryan Head
  • 12,360
  • 5
  • 32
  • 50

2 Answers2

3

Here is a generalization of extract-hsb based on wikipedia's definition of HSB (note that V and B are the same thing)

to-report to-hsb [ rgb-color ]
  if is-number? rgb-color [ set rgb-color extract-rgb rgb-color ]
  let r item 0 rgb-color / 255
  let g item 1 rgb-color / 255
  let b item 2 rgb-color / 255
  let v max (list r g b)
  let chroma v - (min (list r g b))
  let h 0
  let s ifelse-value (v = 0) [ 0 ] [ chroma / v ]

  if chroma > 0 [
    if v = r [
      set h ((g - b) / chroma) mod 6
    ]
    if v = g [
      set h (b - r) / chroma + 2
    ]
    if v = b [
      set h (r - g) / chroma + 4
    ]
    set h h / 6
  ]
  report map [ precision (? * 255) 3 ] (list h s v)
end

It matches extract-hsb perfectly on all color numbers except 44 for some reason...

observer> show filter [ (extract-hsb ?) != (to-hsb extract-rgb ?) ] (n-values 140 [ ? ])
observer: [44]

Unfortunately, it looks like NetLogo rounds RGB values when converting from HSB (well, this actually makes sense). This means that you can't do a perfect HSB->RGB->HSB conversion. For example, using the function above:

observer> show to-hsb hsb 30 64 128
observer: [30.547 63.75 128]

Oh well.

Bryan Head
  • 12,360
  • 5
  • 32
  • 50
1

Agreed on the issue. In the meanwhile, you can pass the list through approximate-rgb to get a color that extract-hsb will handle:

to-report extract-hsb-from [ c ]
  report ifelse-value (is-list? c)
    [ extract-hsb approximate-rgb (item 0 c) (item 1 c) (item 2 c) ]
    [ extract-hsb c ]
end

(Edit: see Seth's comment below for big caveat, however.)

Nicolas Payette
  • 14,847
  • 1
  • 27
  • 37
  • 1
    This will sometimes give good results, and sometimes quite bad, depending on whether there is something close to the input color in NetLogo's native color space. – Seth Tisue Aug 31 '14 at 19:12