Thursday, April 9th, 2009...19:50

Blue And Yellow

Jump to Comments

While working with a friend on a project, I received a chunk of data consisting of 122443 schools/parishes/colleges along with their primary and secondary colors (in hexadecimal). I hacked together a simple color quantizer that converted the colors to the 216 color web safe palette. If the color combinations are given, 1 per row, formatted as primary|secondary, then this bit of Perl:

while(<>) {
  my @colors = split(/\|/,$_);
  my @qColors = (); # will hold the quantized version of @colors
  foreach my $orig (@colors) {
    my $quantized = "";
    for(my $i = 0; $i < 5; $i += 2) {
      my $c = substr($orig,$i,2);
      my $dec = hex($c);
      if($dec <= 26) {
        $quantized .= "00";
      } elsif($dec <= 76) {
        $quantized .= "33";
      } elsif($dec <= 127) {
        $quantized .= "66";
      } elsif($dec <= 177) {
        $quantized .= "99";
      } elsif($dec <= 228) {
        $quantized .= "CC";
      } else {
        $quantized .= "FF";
      }
    }
    push(@qColors,$quantized);
  }
}

will get the job done. Looking back I probably could have just as easily computed the distance between points in 3 dimensional space. In addition, I probably could have reduced my palette to 32-64 colors and ended up with a similar result. If you're curious about the accuracy of this algorithm, here are the colors from the first 10000 schools. The original is on the left, the quantized on the right:

CE0505 CC0000
11147F 000066
FFB300 FFCC00
FA620F FF6600
389CFF 3399FF
808080 999999
108810 009900
4A0C76 330066
832C38 993333
181717 000000
1B1640 330033
0F4509 003300
007080 006699
6A371C 663333
FFEE44 FFFF33
FF4DB8 FF66CC
B9A36A CC9966
C4C4C4 CCCCCC
770B0B 660000
FF2400 FF3300
F5E6BD FFFFCC
00BDEC 00CCFF
DD46DD CC33CC
B55109 CC6600

Here are the statistics:

Most Popular Primary Color Counts:
60825
18359
8036
7126
6686
6005
4641
3569
2424
2024
1476
375
283
166
108
 

Most Popular Primary+Secondary Color Counts:
  44275  
  13479  
  10632  
  4677  
  4268  
  3732  
  2933  
  2700  
  2449  
  2397  
  2395  
  2294  
  1840  
  1654  
  1522  
 

I had whipped up a neat HTML5 Canvas bar graph as well, but WordPress is not liking my JavaScript, maybe next time.

Comments are closed.