 # Challenge - Sort Colors for the best gradient

#1

As the title of the thread implies - suggest some sorting algorithm to get the longest and smoothest color sequences possible:

Here’s a test setup and the first that came into my head:

``````fn vcomp v1 v2 = if v1 < v2 then -1 else if v1 > v2 then 1 else 0

fn sort_by_value c1 c2 =
(
vcomp c1.v c2.v
)
fn sort_by_hue c1 c2 =
(
vcomp c1.h c2.h
)

fn sort_by_magnitude c1 c2 =
(
h1 = int (c1.h / 16)
h2 = int (c2.h / 16)

if (h = vcomp h1 h2) != 0 then h else
(
d1 = length (c1 as point3)
d2 = length (c2 as point3)

vcomp d1 d2
)
)

try (undisplay bmp_palette) catch()

bmp_palette = bitmap (32*32) (32*16) color:black
colors = #()
seed 100

for y = 0 to 31 do for x = 0 to 31 do
(
append colors (random black white)
)

--qsort colors sort_by_value
--qsort colors sort_by_hue
qsort colors sort_by_magnitude

for y = 0 to 31 do for x = 0 to 31 do
(
index = y*32 + x + 1
temp = bitmap 32 16 color:colors[index]
pasteBitmap temp bmp_palette (box2 0 0 32 16) ([x,y] * [32,16])
free temp
)

display bmp_palette ``````

#2

seems like a better sorting result:

``````fn _luminance c R:0.299 G:0.587 B:0.114 =
(
c.r*c.r*R + c.g*c.g*G + c.b*c.b*B
)
fn sort_by_luminance c1 c2 =
(
h1 = int (c1.h / 16)
h2 = int (c2.h / 16)

if (h = vcomp h1 h2) != 0 then h else
(
d1 = _luminance c1
d2 = _luminance c2
vcomp d1 d2
)
)``````

#3

#4

ha ha ha… I already saw it. My #dirty method looks better (IMHO) #5

have you tried this for the luminance

`lum = math.pow((0.299 * r + 0.587 * g + 0.114 * b), 1/2.2)`

?

#6

``````fn _luminance c R:0.299 G:0.587 B:0.114 =
(
c.r*c.r*R + c.g*c.g*G + c.b*c.b*B
)``````

… I like most.

#7

I feel like I should take the saturation into account…but I can’t find its a good role.

#8

there is another #luminance method:

``````fn relative_luminance c =
(
fn relative v = (if v <= 0.03928 then v/12.92 else ((v + 0.055)/1.055) ^ 2.4)

v = c as point4

R = relative v.x
G = relative v.y
B = relative v.z

L = 0.2126 * R + 0.7152 * G + 0.0722 * B
)``````