1 ! Copyright (C) 2014 John Benediktsson
2 ! See http://factorcode.org/license.txt for BSD license
4 USING: accessors colors colors.lab colors.lch kernel math
5 math.functions math.libm math.order math.trig ;
9 : rgba-distance ( color1 color2 -- distance )
11 [ [ red>> ] bi@ - sq ]
12 [ [ blue>> ] bi@ - sq ]
13 [ [ green>> ] bi@ - sq ] 2tri
18 :: mean-hue ( h1 h2 -- mh )
29 :: diff-hue ( h1 h2 -- dh )
30 h2 h1 - dup abs 180 > [
31 dup 0 <= [ 360 + ] [ 360 - ] if
34 : sind ( x -- y ) deg>rad sin ;
36 : cosd ( x -- y ) deg>rad cos ;
38 : atan2d ( x y -- z ) [ deg>rad ] bi@ fatan2 ;
42 :: CIEDE2000 ( color1 color2 -- distance )
44 ! Ensure inputs are L*C*H*
48 lch1 lch2 [ l>> ] bi@ :> ( l1 l2 )
49 lch1 lch2 [ c>> ] bi@ :> ( c1 c2 )
50 lch1 lch2 [ h>> ] bi@ :> ( h1 h2 )
52 ! Calculate the delta values for each channel
55 c2 c1 * zero? [ 0 ] [ h1 h2 diff-hue ] if
56 2 / sind c1 c2 * sqrt * 2 * :> dh
58 ! Calculate mean values
61 c2 c1 * zero? [ 0 ] [ h1 h2 mean-hue ] if :> mh
65 mls dup 20 + sqrt / 0.015 * 1 + :> sl
74 mh 3 * 6 + cosd 0.32 * +
75 mh 4 * 63 - cosd 0.20 * - :> T
76 0.015 mc * T * 1 + :> sh
79 mh 275 - 25 / sq neg e^ 30 * :> dtheta
80 mc 7 ^ dup 25 7 ^ + / sqrt 2 * :> cr
81 dtheta 2 * sind neg cr * :> tr
87 [ [ sq ] bi@ ] [ * tr * ] 2bi
90 :: CIE94 ( color1 color2 -- distance )
92 ! Ensure inputs are L*a*b*
96 lab1 lab2 [ l>> ] bi@ :> ( l1 l2 )
97 lab1 lab2 [ a>> ] bi@ :> ( a1 a2 )
98 lab1 lab2 [ b>> ] bi@ :> ( b1 b2 )
100 ! Calculate the delta values for each channel
104 a1 sq b1 sq + sqrt :> c1
105 a2 sq b2 sq + sqrt :> c2
107 da sq db sq + dc sq - sqrt :> dh
110 1 0.045 0.015 :> ( kl k1 k2 )
113 ! 2 0.048 0.014 :> ( kl k1 k2 )
123 : CIE76 ( color1 color2 -- distance )
127 [ [ b>> ] bi@ - sq ] 2tri
130 :: CMC-l:c ( color1 color2 -- distance )
132 ! Ensure inputs are L*a*b*
136 lab1 lab2 [ a>> ] bi@ :> ( a1 a2 )
137 lab1 lab2 [ b>> ] bi@ :> ( b1 b2 )
139 ! Ensure inputs are L*C*H*
140 color1 >LCHab :> lch1
141 color2 >LCHab :> lch2
143 lch1 lch2 [ l>> ] bi@ :> ( l1 l2 )
144 lch1 lch2 [ c>> ] bi@ :> ( c1 c2 )
145 lch1 lch2 [ h>> ] bi@ :> ( h1 h2 )
152 da sq db sq + dc sq - sqrt :> dh
155 l1 [ 0.040975 * ] [ 0.01765 * 1 + ] bi /
158 c1 [ 0.0638 * ] [ 0.0131 * 1 + ] bi / 0.638 + :> sc
160 c1 4 ^ dup 1900 + / sqrt :> F
162 h1 164 345 between? [
163 h1 168 + cosd 0.2 * abs 0.56 +
165 h1 35 + cosd 0.4 * abs 0.36 +
168 F T * 1 + F - sc * :> sh
170 2.0 :> kl ! default lightness
171 1.0 :> kc ! default chroma
175 dh sh / sq + + sqrt ;