Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Given three number values - being the Red, Green, and Blue elements of a colour (eight bits per channel, 0 to 255) - your program must output the name of the given colour.

For example;

Input:  255, 0, 0  
Output: Red

or;

Input:  80, 0, 0
Output: Dark Red

This is a popularity contest, so whichever answer has the most votes by the first of July wins.

Ispired by: Show the input RGB color

share|improve this question
19  
The name according to what? –  curiousdannii Jun 24 at 3:26
6  
Will common sense do? –  unclemeat Jun 24 at 3:27
18  
It's a popularity contest - so the point is creativity. –  unclemeat Jun 24 at 10:37
15  
I'm badly colorblind. Code that would respond in a manner accurate to my vision would take many fewer characters than what the rest of you are coming up with. –  Michael Stern Jun 24 at 17:27
7  
@michaelsterm this isn't code golf. If you post an answer with a link to a wiki page explaining your type of colour blindness, then it could be quite interesting. –  unclemeat Jun 24 at 21:13

15 Answers 15

up vote 103 down vote accepted

Python

This is a Python script that uses the results from xkcd's Color Survey, in which Randall Munroe asked thousands of people the exact same question. He arrived at the following chart:

The chart

The survey only has data on fully-saturated colors (I guess non-saturated colors would all be described as 'grayish'). This means we have to do some color-related tricks to force our input to become fully saturated.

What I've done here is just convert the input color to HSV, crank up the saturation, and call it a day. This is probably not very correct from a color perception point of view, but it works well enough here - and it's simple enough that you only need the standard library. Batteries included indeed.

The script expects satfaces.txt, from here (mirror), to be in the current directory.

import sys, colorsys

n = (int(sys.argv[1], 16))
r = ((n & 0xff0000) >> 16) / 255.0
g = ((n & 0x00ff00) >> 8) / 255.0
b = ((n & 0x0000ff)) / 255.0

(h, s, v) = colorsys.rgb_to_hsv(r, g, b)
(r, g, b) = colorsys.hsv_to_rgb(h, 1, v)

match = "[{}, {}, {}]".format(int(r*255), int(g*255), int(b*255))

for line in open("satfaces.txt"):
    if line.startswith(match):
        print("You were thinking of: " + line.split("] ")[1].strip())
        break

Some example runs:

$ python color.py CEB301
You were thinking of: yellow
$ python color.py CC9900
You were thinking of: orange
$ python color.py CC0000
You were thinking of: red
$ python color.py 0077FF
You were thinking of: blue

And here are the colors:

Yellow Orange Red Blue

I'd say that's pretty close.

share|improve this answer
21  
The XKCD survey is the first thing I thought of when I saw the question. :) –  undergroundmonorail Jun 24 at 10:14
9  
@undergroundmonorail Same here. I'm pretty sure one could just replace my brain with a black box that only references xkcd all day –  Wander Nauta Jun 24 at 10:16
    
For more fun, you can try seeing if there's an exact match in rgb.txt first: xkcd.com/color/rgb.txt –  Not that Charles Jun 24 at 12:01
1  
@Charles Hmm, that would be pretty easy indeed. On the other hand, you'd need an additional data file. I think I'll leave the baby shit detection feature to other competitors :) –  Wander Nauta Jun 24 at 12:14
1  
Well done and congratulations. The winner by a long shot (though neck and neck for a while there) is @WanderNauta. –  unclemeat Jun 30 at 23:13

Update with GUI!

Light cornflower blue A slightly brighter Lime (web) (X11 green)

I take the color list from this Wikipedia page (and the related pages).

I also included some NLG to produce results like "Bulgarian Rose with slightly less green and blue" and some variants of it. Try to play along to see whether you can guess the true "Bulgarian Rose" using those feedbacks. :)

The algorithm will try to find the color which is the closest to the input, as defined by the Euclidean distance. So you can input any number triplet and it will give the color which is the closest to that triplet.

(the code accepts "comma-space separated", "space separated", or "comma separated" values)

Warning

This code connects to Wikipedia, and so it requires Internet connection in order to run the first time (and write the information in a file in the same dictionary). The subsequent times, though, it will read from file. If you want the offline version, the code is available at this Ideone link (with sample run).

Code:

import re, os
from bs4 import BeautifulSoup as BS
import requests
import cPickle as pickle
import random

def encode_color(text):
    return tuple(map(int, re.split(', |,| ', text)))

def color_name(col):
    global color_map, color_nums
    arr = color_nums
    closest = None
    min_dist = 10**8
    for color in arr:
        dist = sum((color[i]-col[i])**2 for i in range(3))
        if dist < min_dist:
            closest = color
            min_dist = dist
    result = color_map[closest]
    rgb = ['red', 'green', 'blue']
    slightly_more = ['with a hint of', 'with traces of', 'with slightly more']
    slightly_less = ['with subdued', 'with slightly less']
    more_more = ['with more', 'with strong hint of']
    more_less = ['with less', 'with diminished']
    count = 0
    adds = ['','']
    for i in range(3):
        expl_list = ['']
        if 5 < col[i]-closest[i] < 10:
            expl_list = slightly_more
            count += 1
            add_idx = 0
        elif 10 <= col[i]-closest[i]:
            expl_list = more_more
            count += 2
            add_idx = 0
        elif -10 <= col[i]-closest[i] < -5:
            expl_list = slightly_less
            count -= 1
            add_idx = 1
        elif col[i]-closest[i] <= -10:
            expl_list = more_less
            count -= 2
            add_idx = 1
        expl = expl_list[random.randint(0, len(expl_list)-1)]
        if expl is not '':
            if adds[add_idx] is '':
                adds[add_idx] += ' %s %s' % (expl, rgb[i])
            else:
                adds[add_idx] += ' and %s' % rgb[i]
    if 3 <= count <= 4:
        result = 'A slightly brighter '+result
    elif 4 < count:
        result = 'A brighter '+result
    elif -4 <= count <= -3:
        result = 'A slightly darker '+result
    elif count < -4:
        result = 'A darker '+result
    elif count > 0:
        result += adds[0]
    elif count < 0:
        result += adds[1]
    return result

links = ['http://en.wikipedia.org/wiki/List_of_colors:_A%E2%80%93F',
         'http://en.wikipedia.org/wiki/List_of_colors:_G%E2%80%93M',
         'http://en.wikipedia.org/wiki/List_of_colors:_N%E2%80%93Z']

def is_color(tag):
    return tag.name == 'th' and len(tag.contents)==1 and tag.contents[0].name=='a'

def parse_color(hexa):
    return (int(hexa[0:2], 16), int(hexa[2:4], 16), int(hexa[4:6], 16))

print 'Loading color names...'
if os.path.exists('parse_wiki_color.pickle'):
    with open('parse_wiki_color.pickle', 'rb') as infile:
        color_map, color_nums = pickle.load(infile)
else:
    color_map = {}
    color_nums = []
    for link in links:
        soup = BS(requests.get(link).text,'lxml')
        for color in soup.find_all(is_color):
            try:
                color_num = parse_color(color.next_sibling.next_sibling.string[1:])
                color_nums.append(color_num)
                color_map[color_num] = str(color.a.string)
            except:
                continue
    color_nums = sorted(color_nums)
    with open('parse_wiki_color.pickle', 'wb') as outfile:
        pickle.dump((color_map, color_nums), outfile, protocol=2)
print 'Color names loaded'

def main(event=None):
    global var, col_name, col_disp
    text = var.get()
    color = encode_color(text)
    result = color_name(color)
    col_name.set(result)
    col_rgb.set(color)
    var.set('')
    col_disp.configure(background='#%02x%02x%02x' % color)

from Tkinter import *
root = Tk()
frame = Frame(root)
frame.pack()
caption = Label(frame, text='Enter RGB color:')
caption.pack(side=LEFT)
var = StringVar()
entry = Entry(frame, textvariable=var)
entry.focus_set()
entry.pack(side=LEFT)
entry.bind('<Return>',func=main)
button = Button(frame, text='Get name', command=main)
button.pack(side=LEFT)
col_rgb = StringVar()
col_rgb_disp = Label(root, textvariable=col_rgb)
col_rgb_disp.pack()
col_name = StringVar()
col_label = Label(root, textvariable=col_name)
col_label.pack()
col_disp = Label(root)
col_disp.configure(padx=50, pady=45, relief=RAISED)
col_disp.pack()
root.geometry('400x200')
root.mainloop()
share|improve this answer
38  
Good, but you need to make your terminology a little more pretentious. You should change slightly more to with a hint of and slightly less to subdued. –  steveverrill Jun 24 at 8:55
    
@steveverrill: Updated! –  justhalf Jun 24 at 10:33
1  
Impressive. +1 it is. –  Sieg Jun 24 at 10:51
    
is this python? –  user1886419 Jun 25 at 18:35
1  
I've never got so many votes in StackExchange before. Thanks everyone! –  justhalf Jun 30 at 10:43

JavaScript

The following function is written with canine users in mind:

function getColorName(r, g, b) {
    return "gray";
}

For the more refined dogs out there:

function getColorName(r, g, b) {
    var gray = (0.21*r + 0.71*g + 0.07*b);
    if (gray < 64)
        return "black";
    else if (gray < 128)
        return "dark gray";
    else if (gray < 192)
        return "light gray";
    else if (gray < 256)
        return "white";
    else
        whimper();
}
share|improve this answer
2  
canines do actually see color though –  Pinna_be Jun 24 at 20:59
10  
@Pinna_be Sssh, I know, but you are ruining the joke. ;) –  IQAndreas Jun 24 at 21:02
28  
roses are yellow / violets are blue / dogs can see color / just not quite like you –  fluffy Jun 25 at 3:04
11  
+1 else whimper(); - love it –  Lego Stormtroopr Jun 25 at 10:54
5  
Food is food, who cares what colour it is... ;) –  The Blue Dog Jun 26 at 7:38

Javascript

window.location = 'http://www.color-hex.com/color/' + 'ff00ff'
share|improve this answer
1  
I like this one. –  MxyL Jun 24 at 21:51

Mathematica

Update: Added a parameter for setting the number of closest colors to display. The default is 5 colors.

Given the RGB values of an unnamed color, the following finds the n nearest colors from a list of 140 HTML color names. It then plots the unnamed color and its 5 nearest neighbors in a 3-space, with axes for Red, Green, and Blue. In the plot label it names the nearest color and provides its RGB values.

colorInterpret[rgb_,n_: 5]:=
Module[{colorData,valsRGB,pts,closest},
colorData=({ColorData["HTML",#],#}&/@ColorData["HTML","Range"][[1]])/.{RGBColor[x__]:> {x}};
valsRGB=colorData[[All,1]];
pts=Append[colorData[[Position[valsRGB,#]&/@Nearest[valsRGB,rgb,n]//Flatten]],{rgb,"Unnamed Color"}];
closest=pts[[1]];
Graphics3D[{PointSize[.05],
{RGBColor@@#,Point[#],Text[Style[#2,Black,14],(#-{.01,.01,.01})]}&@@@pts
},
Axes-> True,
PlotLabel-> Row[{"closest color: ", closest}],
ImageSize-> 600,
ImagePadding-> 50,
BaseStyle-> 14,
AxesLabel->{Style["Red",18],Style["Green",18],Style["Blue",18]}]]

Examples

Display the 5 closest colors:

 colorInterpret[{.55, .86, .69}]

green


Display the 15 closest colors:

blue

share|improve this answer
3  
Nice visualisation! –  tomsmeding Jun 29 at 18:53
1  
Really awesome solution, +1 for 3-dimensional visualization. –  Nit Jun 30 at 17:28

CJam

l~]:X;"xkcd.com/color/rgb.txt"gN%"  "f%{[1=1>eu2/{:~Gb}%X]z{:-}%2f#:+}$0=0=

This gets the list of colors from xkcd and finds the nearest one.
Note: the space-looking string in the middle is actually one tab.

To run it, please use the interpreter from http://sf.net/p/cjam

Example:

Input 147 125 0
Output baby poop

share|improve this answer
2  
+1 for baby poop –  tomsmeding Jun 29 at 18:52

R

R has an embedded list of 657 color names for plotting purposes. The following code take input from user, and computes the distance between this rgb input and the rgb value of those 657 colors and outputs the name of the closest one.

a=as.integer(strsplit(readline(),", ")[[1]]);color_list=sapply(colors(),col2rgb);names(which.min(colSums(abs(apply(color_list,2,function(x)x-a)))))

Ungolfed:

a <- as.integer(strsplit(readline(),", ")[[1]]) #Ask user input as stdin, and process it
color_list <- sapply(colors(),col2rgb) #Convert the color name list into an RGB matrix
#Computes the difference with user input, adds the absolute value and output the name of the element with the minimal value
names(which.min(colSums(abs(apply(color_list, 2, function(x)x-a)))))

Examples:

> a=as.integer(strsplit(readline(),", ")[[1]]);color_list=sapply(colors(),col2rgb);names(which.min(colSums(abs(apply(color_list,2,function(x)x-a)))))
80, 0, 2
[1] "darkred"
> a=as.integer(strsplit(readline(),", ")[[1]]);color_list=sapply(colors(),col2rgb);names(which.min(colSums(abs(apply(color_list,2,function(x)x-a)))))
150, 150, 150
[1] "gray59"
> a=as.integer(strsplit(readline(),", ")[[1]]);color_list=sapply(colors(),col2rgb);names(which.min(colSums(abs(apply(color_list,2,function(x)x-a)))))
0, 200, 255
[1] "deepskyblue"
> a=as.integer(strsplit(readline(),", ")[[1]]);color_list=sapply(colors(),col2rgb);names(which.min(colSums(abs(apply(color_list,2,function(x)x-a)))))
255, 100, 70
[1] "tomato"

Edit: Same idea but using the list of name from colorHexa:

a=strsplit(xpathSApply(htmlParse("http://www.colorhexa.com/color-names"),"//li",xmlValue),"#")
n=sapply(a,`[`,1)
r=apply(do.call(rbind,strsplit(sapply(a,`[`,2)," "))[,2:4],2,as.integer)
n[which.min(colSums(abs(apply(r,1,`-`,as.integer(strsplit(readline(),", ")[[1]])))))]

Example:

> a=strsplit(xpathSApply(htmlParse("http://www.colorhexa.com/color-names"),"//li",xmlValue),"#")
> n=sapply(a,`[`,1)
> r=apply(do.call(rbind,strsplit(sapply(a,`[`,2)," "))[,2:4],2,as.integer)
> n[which.min(colSums(abs(apply(r,1,`-`,as.integer(strsplit(readline(),", ")[[1]])))))]
208, 32, 12
[1] " Fire engine red "
share|improve this answer
5  
Not sure why you golfed it. –  Pierre Arlaud Jun 24 at 15:01
3  
1) Because it amuses me. 2) I didn't golf it, i just made it a one-liner so that readline doesn't read the following line of code as if it was stdin in interactive mode. I used the word "ungolfed" to say "indented, with line breaks and comments". If I had really golfed it i wouldn't have used color_list as variable name. –  plannapus Jun 25 at 7:06
    
@plannapus You're contradicting yourself; you golfed it because it amused you but you didn't golf it. :P Nice solution anyway, and the right language for the job. –  tomsmeding Jun 29 at 18:56

Scala

My attempt — the killer feature is that it doesn't require Internet connection! (I hope it's not too long :D ) Also, I did summon Chtulhu while preparing color database (because I parsed a subset of HTML with regex; the regex and the link to source are in comments)

Edit: improved accuracy

Example run: http://ideone.com/e3n0dG

object Main {

  def main(args: Array[String]) {
    val color = extractBrightness(readLine().split("[, ]+").map(_.toInt))

    val nearestColor = colors.minBy(t => distance(extractBrightness(parseColor(t._1)), color, weight))._2
    println(s"Your color is $nearestColor")
  }

  def parseColor(s: String) = {
    s.sliding(2, 2).map(Integer.parseInt(_, 16)).toVector
  }

  def distance(c1: Seq[Double], c2: Seq[Double], weight: Seq[Double]) = {
    c1.zip(c2).map(t => ((x: Double) => x * x)(t._1 - t._2)).zip(weight).map(t => t._1 * t._2).sum
  }

  val weight = Vector(0.01, 1.0, 0.8)

  def extractBrightness(c: Seq[Int]) = {
    val Seq(r, g, b) = c
    val brightness = c.sum.toDouble / 3
    val rOffset = r - brightness
    val bOffset = b - brightness
    Seq(brightness, rOffset, bOffset)
  }

  // colors are extracted by using this regex: <li>[\s\S]*?<a href="/......">([\w ]+)</a>[\s\S]*?<a href="/......">#(......)</a>[\s\S]*?</li>
  // from this page: http://www.colorhexa.com/color-names
  val colors = Vector(
    "5d8aa8" -> "Air Force blue",
    "f0f8ff" -> "Alice blue",
    "e32636" -> "Alizarin crimson",
    "efdecd" -> "Almond",
    "e52b50" -> "Amaranth",
    "ffbf00" -> "Amber",
    "ff033e" -> "American rose",
    "9966cc" -> "Amethyst",
    "a4c639" -> "Android Green",
    "cd9575" -> "Antique brass",
    "915c83" -> "Antique fuchsia",
    "faebd7" -> "Antique white",
    "008000" -> "Ao",
    "8db600" -> "Apple green",
    "fbceb1" -> "Apricot",
    "00ffff" -> "Aqua",
    "7fffd4" -> "Aquamarine",
    "4b5320" -> "Army green",
    "e9d66b" -> "Arylide yellow",
    "b2beb5" -> "Ash grey",
    "87a96b" -> "Asparagus",
    "ff9966" -> "Atomic tangerine",
    "a52a2a" -> "Auburn",
    "fdee00" -> "Aureolin",
    "6e7f80" -> "AuroMetalSaurus",
    "ff2052" -> "Awesome",
    "007fff" -> "Azure",
    "89cff0" -> "Baby blue",
    "a1caf1" -> "Baby blue eyes",
    "f4c2c2" -> "Baby pink",
    "21abcd" -> "Ball Blue",
    "fae7b5" -> "Banana Mania",
    "ffe135" -> "Banana yellow",
    "848482" -> "Battleship grey",
    "98777b" -> "Bazaar",
    "bcd4e6" -> "Beau blue",
    "9f8170" -> "Beaver",
    "f5f5dc" -> "Beige",
    "ffe4c4" -> "Bisque",
    "3d2b1f" -> "Bistre",
    "fe6f5e" -> "Bittersweet",
    "000000" -> "Black",
    "ffebcd" -> "Blanched Almond",
    "318ce7" -> "Bleu de France",
    "ace5ee" -> "Blizzard Blue",
    "faf0be" -> "Blond",
    "0000ff" -> "Blue",
    "a2a2d0" -> "Blue Bell",
    "6699cc" -> "Blue Gray",
    "0d98ba" -> "Blue green",
    "8a2be2" -> "Blue purple",
    "8a2be2" -> "Blue violet",
    "de5d83" -> "Blush",
    "79443b" -> "Bole",
    "0095b6" -> "Bondi blue",
    "e3dac9" -> "Bone",
    "cc0000" -> "Boston University Red",
    "006a4e" -> "Bottle green",
    "873260" -> "Boysenberry",
    "0070ff" -> "Brandeis blue",
    "b5a642" -> "Brass",
    "cb4154" -> "Brick red",
    "1dacd6" -> "Bright cerulean",
    "66ff00" -> "Bright green",
    "bf94e4" -> "Bright lavender",
    "c32148" -> "Bright maroon",
    "ff007f" -> "Bright pink",
    "08e8de" -> "Bright turquoise",
    "d19fe8" -> "Bright ube",
    "f4bbff" -> "Brilliant lavender",
    "ff55a3" -> "Brilliant rose",
    "fb607f" -> "Brink pink",
    "004225" -> "British racing green",
    "cd7f32" -> "Bronze",
    "a52a2a" -> "Brown",
    "ffc1cc" -> "Bubble gum",
    "e7feff" -> "Bubbles",
    "f0dc82" -> "Buff",
    "480607" -> "Bulgarian rose",
    "800020" -> "Burgundy",
    "deb887" -> "Burlywood",
    "cc5500" -> "Burnt orange",
    "e97451" -> "Burnt sienna",
    "8a3324" -> "Burnt umber",
    "bd33a4" -> "Byzantine",
    "702963" -> "Byzantium",
    "007aa5" -> "CG Blue",
    "e03c31" -> "CG Red",
    "536872" -> "Cadet",
    "5f9ea0" -> "Cadet blue",
    "91a3b0" -> "Cadet grey",
    "006b3c" -> "Cadmium green",
    "ed872d" -> "Cadmium orange",
    "e30022" -> "Cadmium red",
    "fff600" -> "Cadmium yellow",
    "a67b5b" -> "Café au lait",
    "4b3621" -> "Café noir",
    "1e4d2b" -> "Cal Poly Pomona green",
    "a3c1ad" -> "Cambridge Blue",
    "c19a6b" -> "Camel",
    "78866b" -> "Camouflage green",
    "ffff99" -> "Canary",
    "ffef00" -> "Canary yellow",
    "ff0800" -> "Candy apple red",
    "e4717a" -> "Candy pink",
    "00bfff" -> "Capri",
    "592720" -> "Caput mortuum",
    "c41e3a" -> "Cardinal",
    "00cc99" -> "Caribbean green",
    "ff0040" -> "Carmine",
    "eb4c42" -> "Carmine pink",
    "ff0038" -> "Carmine red",
    "ffa6c9" -> "Carnation pink",
    "b31b1b" -> "Carnelian",
    "99badd" -> "Carolina blue",
    "ed9121" -> "Carrot orange",
    "ace1af" -> "Celadon",
    "b2ffff" -> "Celeste",
    "4997d0" -> "Celestial blue",
    "de3163" -> "Cerise",
    "ec3b83" -> "Cerise pink",
    "007ba7" -> "Cerulean",
    "2a52be" -> "Cerulean blue",
    "a0785a" -> "Chamoisee",
    "fad6a5" -> "Champagne",
    "36454f" -> "Charcoal",
    "7fff00" -> "Chartreuse",
    "de3163" -> "Cherry",
    "ffb7c5" -> "Cherry blossom pink",
    "cd5c5c" -> "Chestnut",
    "d2691e" -> "Chocolate",
    "ffa700" -> "Chrome yellow",
    "98817b" -> "Cinereous",
    "e34234" -> "Cinnabar",
    "d2691e" -> "Cinnamon",
    "e4d00a" -> "Citrine",
    "fbcce7" -> "Classic rose",
    "0047ab" -> "Cobalt",
    "d2691e" -> "Cocoa brown",
    "6f4e37" -> "Coffee",
    "9bddff" -> "Columbia blue",
    "002e63" -> "Cool black",
    "8c92ac" -> "Cool grey",
    "b87333" -> "Copper",
    "996666" -> "Copper rose",
    "ff3800" -> "Coquelicot",
    "ff7f50" -> "Coral",
    "f88379" -> "Coral pink",
    "ff4040" -> "Coral red",
    "893f45" -> "Cordovan",
    "fbec5d" -> "Corn",
    "b31b1b" -> "Cornell Red",
    "9aceeb" -> "Cornflower",
    "6495ed" -> "Cornflower blue",
    "fff8dc" -> "Cornsilk",
    "fff8e7" -> "Cosmic latte",
    "ffbcd9" -> "Cotton candy",
    "fffdd0" -> "Cream",
    "dc143c" -> "Crimson",
    "990000" -> "Crimson Red",
    "be0032" -> "Crimson glory",
    "00ffff" -> "Cyan",
    "ffff31" -> "Daffodil",
    "f0e130" -> "Dandelion",
    "00008b" -> "Dark blue",
    "654321" -> "Dark brown",
    "5d3954" -> "Dark byzantium",
    "a40000" -> "Dark candy apple red",
    "08457e" -> "Dark cerulean",
    "986960" -> "Dark chestnut",
    "cd5b45" -> "Dark coral",
    "008b8b" -> "Dark cyan",
    "536878" -> "Dark electric blue",
    "b8860b" -> "Dark goldenrod",
    "a9a9a9" -> "Dark gray",
    "013220" -> "Dark green",
    "1a2421" -> "Dark jungle green",
    "bdb76b" -> "Dark khaki",
    "483c32" -> "Dark lava",
    "734f96" -> "Dark lavender",
    "8b008b" -> "Dark magenta",
    "003366" -> "Dark midnight blue",
    "556b2f" -> "Dark olive green",
    "ff8c00" -> "Dark orange",
    "9932cc" -> "Dark orchid",
    "779ecb" -> "Dark pastel blue",
    "03c03c" -> "Dark pastel green",
    "966fd6" -> "Dark pastel purple",
    "c23b22" -> "Dark pastel red",
    "e75480" -> "Dark pink",
    "003399" -> "Dark powder blue",
    "872657" -> "Dark raspberry",
    "8b0000" -> "Dark red",
    "e9967a" -> "Dark salmon",
    "560319" -> "Dark scarlet",
    "8fbc8f" -> "Dark sea green",
    "3c1414" -> "Dark sienna",
    "483d8b" -> "Dark slate blue",
    "2f4f4f" -> "Dark slate gray",
    "177245" -> "Dark spring green",
    "918151" -> "Dark tan",
    "ffa812" -> "Dark tangerine",
    "483c32" -> "Dark taupe",
    "cc4e5c" -> "Dark terra cotta",
    "00ced1" -> "Dark turquoise",
    "9400d3" -> "Dark violet",
    "00693e" -> "Dartmouth green",
    "555555" -> "Davy grey",
    "d70a53" -> "Debian red",
    "a9203e" -> "Deep carmine",
    "ef3038" -> "Deep carmine pink",
    "e9692c" -> "Deep carrot orange",
    "da3287" -> "Deep cerise",
    "fad6a5" -> "Deep champagne",
    "b94e48" -> "Deep chestnut",
    "704241" -> "Deep coffee",
    "c154c1" -> "Deep fuchsia",
    "004b49" -> "Deep jungle green",
    "9955bb" -> "Deep lilac",
    "cc00cc" -> "Deep magenta",
    "ffcba4" -> "Deep peach",
    "ff1493" -> "Deep pink",
    "ff9933" -> "Deep saffron",
    "00bfff" -> "Deep sky blue",
    "1560bd" -> "Denim",
    "c19a6b" -> "Desert",
    "edc9af" -> "Desert sand",
    "696969" -> "Dim gray",
    "1e90ff" -> "Dodger blue",
    "d71868" -> "Dogwood rose",
    "85bb65" -> "Dollar bill",
    "967117" -> "Drab",
    "00009c" -> "Duke blue",
    "e1a95f" -> "Earth yellow",
    "c2b280" -> "Ecru",
    "614051" -> "Eggplant",
    "f0ead6" -> "Eggshell",
    "1034a6" -> "Egyptian blue",
    "7df9ff" -> "Electric blue",
    "ff003f" -> "Electric crimson",
    "00ffff" -> "Electric cyan",
    "00ff00" -> "Electric green",
    "6f00ff" -> "Electric indigo",
    "f4bbff" -> "Electric lavender",
    "ccff00" -> "Electric lime",
    "bf00ff" -> "Electric purple",
    "3f00ff" -> "Electric ultramarine",
    "8f00ff" -> "Electric violet",
    "ffff00" -> "Electric yellow",
    "50c878" -> "Emerald",
    "96c8a2" -> "Eton blue",
    "c19a6b" -> "Fallow",
    "801818" -> "Falu red",
    "ff00ff" -> "Famous",
    "b53389" -> "Fandango",
    "f400a1" -> "Fashion fuchsia",
    "e5aa70" -> "Fawn",
    "4d5d53" -> "Feldgrau",
    "71bc78" -> "Fern",
    "4f7942" -> "Fern green",
    "ff2800" -> "Ferrari Red",
    "6c541e" -> "Field drab",
    "ce2029" -> "Fire engine red",
    "b22222" -> "Firebrick",
    "e25822" -> "Flame",
    "fc8eac" -> "Flamingo pink",
    "f7e98e" -> "Flavescent",
    "eedc82" -> "Flax",
    "fffaf0" -> "Floral white",
    "ffbf00" -> "Fluorescent orange",
    "ff1493" -> "Fluorescent pink",
    "ccff00" -> "Fluorescent yellow",
    "ff004f" -> "Folly",
    "228b22" -> "Forest green",
    "a67b5b" -> "French beige",
    "0072bb" -> "French blue",
    "86608e" -> "French lilac",
    "f64a8a" -> "French rose",
    "ff00ff" -> "Fuchsia",
    "ff77ff" -> "Fuchsia pink",
    "e48400" -> "Fulvous",
    "cc6666" -> "Fuzzy Wuzzy",
    "dcdcdc" -> "Gainsboro",
    "e49b0f" -> "Gamboge",
    "f8f8ff" -> "Ghost white",
    "b06500" -> "Ginger",
    "6082b6" -> "Glaucous",
    "e6e8fa" -> "Glitter",
    "ffd700" -> "Gold",
    "996515" -> "Golden brown",
    "fcc200" -> "Golden poppy",
    "ffdf00" -> "Golden yellow",
    "daa520" -> "Goldenrod",
    "a8e4a0" -> "Granny Smith Apple",
    "808080" -> "Gray",
    "465945" -> "Gray asparagus",
    "00ff00" -> "Green",
    "1164b4" -> "Green Blue",
    "adff2f" -> "Green yellow",
    "a99a86" -> "Grullo",
    "00ff7f" -> "Guppie green",
    "663854" -> "Halayà úbe",
    "446ccf" -> "Han blue",
    "5218fa" -> "Han purple",
    "e9d66b" -> "Hansa yellow",
    "3fff00" -> "Harlequin",
    "c90016" -> "Harvard crimson",
    "da9100" -> "Harvest Gold",
    "808000" -> "Heart Gold",
    "df73ff" -> "Heliotrope",
    "f400a1" -> "Hollywood cerise",
    "f0fff0" -> "Honeydew",
    "49796b" -> "Hooker green",
    "ff1dce" -> "Hot magenta",
    "ff69b4" -> "Hot pink",
    "355e3b" -> "Hunter green",
    "fcf75e" -> "Icterine",
    "b2ec5d" -> "Inchworm",
    "138808" -> "India green",
    "cd5c5c" -> "Indian red",
    "e3a857" -> "Indian yellow",
    "4b0082" -> "Indigo",
    "002fa7" -> "International Klein Blue",
    "ff4f00" -> "International orange",
    "5a4fcf" -> "Iris",
    "f4f0ec" -> "Isabelline",
    "009000" -> "Islamic green",
    "fffff0" -> "Ivory",
    "00a86b" -> "Jade",
    "f8de7e" -> "Jasmine",
    "d73b3e" -> "Jasper",
    "a50b5e" -> "Jazzberry jam",
    "fada5e" -> "Jonquil",
    "bdda57" -> "June bud",
    "29ab87" -> "Jungle green",
    "e8000d" -> "KU Crimson",
    "4cbb17" -> "Kelly green",
    "c3b091" -> "Khaki",
    "087830" -> "La Salle Green",
    "d6cadd" -> "Languid lavender",
    "26619c" -> "Lapis lazuli",
    "fefe22" -> "Laser Lemon",
    "a9ba9d" -> "Laurel green",
    "cf1020" -> "Lava",
    "e6e6fa" -> "Lavender",
    "ccccff" -> "Lavender blue",
    "fff0f5" -> "Lavender blush",
    "c4c3d0" -> "Lavender gray",
    "9457eb" -> "Lavender indigo",
    "ee82ee" -> "Lavender magenta",
    "e6e6fa" -> "Lavender mist",
    "fbaed2" -> "Lavender pink",
    "967bb6" -> "Lavender purple",
    "fba0e3" -> "Lavender rose",
    "7cfc00" -> "Lawn green",
    "fff700" -> "Lemon",
    "fff44f" -> "Lemon Yellow",
    "fffacd" -> "Lemon chiffon",
    "bfff00" -> "Lemon lime",
    "f56991" -> "Light Crimson",
    "e68fac" -> "Light Thulian pink",
    "fdd5b1" -> "Light apricot",
    "add8e6" -> "Light blue",
    "b5651d" -> "Light brown",
    "e66771" -> "Light carmine pink",
    "f08080" -> "Light coral",
    "93ccea" -> "Light cornflower blue",
    "e0ffff" -> "Light cyan",
    "f984ef" -> "Light fuchsia pink",
    "fafad2" -> "Light goldenrod yellow",
    "d3d3d3" -> "Light gray",
    "90ee90" -> "Light green",
    "f0e68c" -> "Light khaki",
    "b19cd9" -> "Light pastel purple",
    "ffb6c1" -> "Light pink",
    "ffa07a" -> "Light salmon",
    "ff9999" -> "Light salmon pink",
    "20b2aa" -> "Light sea green",
    "87cefa" -> "Light sky blue",
    "778899" -> "Light slate gray",
    "b38b6d" -> "Light taupe",
    "ffffed" -> "Light yellow",
    "c8a2c8" -> "Lilac",
    "bfff00" -> "Lime",
    "32cd32" -> "Lime green",
    "195905" -> "Lincoln green",
    "faf0e6" -> "Linen",
    "c19a6b" -> "Lion",
    "534b4f" -> "Liver",
    "e62020" -> "Lust",
    "18453b" -> "MSU Green",
    "ffbd88" -> "Macaroni and Cheese",
    "ff00ff" -> "Magenta",
    "aaf0d1" -> "Magic mint",
    "f8f4ff" -> "Magnolia",
    "c04000" -> "Mahogany",
    "fbec5d" -> "Maize",
    "6050dc" -> "Majorelle Blue",
    "0bda51" -> "Malachite",
    "979aaa" -> "Manatee",
    "ff8243" -> "Mango Tango",
    "74c365" -> "Mantis",
    "800000" -> "Maroon",
    "e0b0ff" -> "Mauve",
    "915f6d" -> "Mauve taupe",
    "ef98aa" -> "Mauvelous",
    "73c2fb" -> "Maya blue",
    "e5b73b" -> "Meat brown",
    "0067a5" -> "Medium Persian blue",
    "66ddaa" -> "Medium aquamarine",
    "0000cd" -> "Medium blue",
    "e2062c" -> "Medium candy apple red",
    "af4035" -> "Medium carmine",
    "f3e5ab" -> "Medium champagne",
    "035096" -> "Medium electric blue",
    "1c352d" -> "Medium jungle green",
    "dda0dd" -> "Medium lavender magenta",
    "ba55d3" -> "Medium orchid",
    "9370db" -> "Medium purple",
    "bb3385" -> "Medium red violet",
    "3cb371" -> "Medium sea green",
    "7b68ee" -> "Medium slate blue",
    "c9dc87" -> "Medium spring bud",
    "00fa9a" -> "Medium spring green",
    "674c47" -> "Medium taupe",
    "0054b4" -> "Medium teal blue",
    "48d1cc" -> "Medium turquoise",
    "c71585" -> "Medium violet red",
    "fdbcb4" -> "Melon",
    "191970" -> "Midnight blue",
    "004953" -> "Midnight green",
    "ffc40c" -> "Mikado yellow",
    "3eb489" -> "Mint",
    "f5fffa" -> "Mint cream",
    "98ff98" -> "Mint green",
    "ffe4e1" -> "Misty rose",
    "faebd7" -> "Moccasin",
    "967117" -> "Mode beige",
    "73a9c2" -> "Moonstone blue",
    "ae0c00" -> "Mordant red 19",
    "addfad" -> "Moss green",
    "30ba8f" -> "Mountain Meadow",
    "997a8d" -> "Mountbatten pink",
    "c54b8c" -> "Mulberry",
    "f2f3f4" -> "Munsell",
    "ffdb58" -> "Mustard",
    "21421e" -> "Myrtle",
    "f6adc6" -> "Nadeshiko pink",
    "2a8000" -> "Napier green",
    "fada5e" -> "Naples yellow",
    "ffdead" -> "Navajo white",
    "000080" -> "Navy blue",
    "ffa343" -> "Neon Carrot",
    "fe59c2" -> "Neon fuchsia",
    "39ff14" -> "Neon green",
    "059033" -> "North Texas Green",
    "0077be" -> "Ocean Boat Blue",
    "cc7722" -> "Ochre",
    "008000" -> "Office green",
    "cfb53b" -> "Old gold",
    "fdf5e6" -> "Old lace",
    "796878" -> "Old lavender",
    "673147" -> "Old mauve",
    "c08081" -> "Old rose",
    "808000" -> "Olive",
    "6b8e23" -> "Olive Drab",
    "bab86c" -> "Olive Green",
    "9ab973" -> "Olivine",
    "0f0f0f" -> "Onyx",
    "b784a7" -> "Opera mauve",
    "ffa500" -> "Orange",
    "f8d568" -> "Orange Yellow",
    "ff9f00" -> "Orange peel",
    "ff4500" -> "Orange red",
    "da70d6" -> "Orchid",
    "654321" -> "Otter brown",
    "414a4c" -> "Outer Space",
    "ff6e4a" -> "Outrageous Orange",
    "002147" -> "Oxford Blue",
    "1ca9c9" -> "Pacific Blue",
    "006600" -> "Pakistan green",
    "273be2" -> "Palatinate blue",
    "682860" -> "Palatinate purple",
    "bcd4e6" -> "Pale aqua",
    "afeeee" -> "Pale blue",
    "987654" -> "Pale brown",
    "af4035" -> "Pale carmine",
    "9bc4e2" -> "Pale cerulean",
    "ddadaf" -> "Pale chestnut",
    "da8a67" -> "Pale copper",
    "abcdef" -> "Pale cornflower blue",
    "e6be8a" -> "Pale gold",
    "eee8aa" -> "Pale goldenrod",
    "98fb98" -> "Pale green",
    "dcd0ff" -> "Pale lavender",
    "f984e5" -> "Pale magenta",
    "fadadd" -> "Pale pink",
    "dda0dd" -> "Pale plum",
    "db7093" -> "Pale red violet",
    "96ded1" -> "Pale robin egg blue",
    "c9c0bb" -> "Pale silver",
    "ecebbd" -> "Pale spring bud",
    "bc987e" -> "Pale taupe",
    "db7093" -> "Pale violet red",
    "78184a" -> "Pansy purple",
    "ffefd5" -> "Papaya whip",
    "50c878" -> "Paris Green",
    "aec6cf" -> "Pastel blue",
    "836953" -> "Pastel brown",
    "cfcfc4" -> "Pastel gray",
    "77dd77" -> "Pastel green",
    "f49ac2" -> "Pastel magenta",
    "ffb347" -> "Pastel orange",
    "ffd1dc" -> "Pastel pink",
    "b39eb5" -> "Pastel purple",
    "ff6961" -> "Pastel red",
    "cb99c9" -> "Pastel violet",
    "fdfd96" -> "Pastel yellow",
    "800080" -> "Patriarch",
    "536878" -> "Payne grey",
    "ffe5b4" -> "Peach",
    "ffdab9" -> "Peach puff",
    "fadfad" -> "Peach yellow",
    "d1e231" -> "Pear",
    "eae0c8" -> "Pearl",
    "88d8c0" -> "Pearl Aqua",
    "e6e200" -> "Peridot",
    "ccccff" -> "Periwinkle",
    "1c39bb" -> "Persian blue",
    "32127a" -> "Persian indigo",
    "d99058" -> "Persian orange",
    "f77fbe" -> "Persian pink",
    "701c1c" -> "Persian plum",
    "cc3333" -> "Persian red",
    "fe28a2" -> "Persian rose",
    "df00ff" -> "Phlox",
    "000f89" -> "Phthalo blue",
    "123524" -> "Phthalo green",
    "fddde6" -> "Piggy pink",
    "01796f" -> "Pine green",
    "ffc0cb" -> "Pink",
    "fc74fd" -> "Pink Flamingo",
    "f78fa7" -> "Pink Sherbet",
    "e7accf" -> "Pink pearl",
    "93c572" -> "Pistachio",
    "e5e4e2" -> "Platinum",
    "dda0dd" -> "Plum",
    "ff5a36" -> "Portland Orange",
    "b0e0e6" -> "Powder blue",
    "ff8f00" -> "Princeton orange",
    "003153" -> "Prussian blue",
    "df00ff" -> "Psychedelic purple",
    "cc8899" -> "Puce",
    "ff7518" -> "Pumpkin",
    "800080" -> "Purple",
    "69359c" -> "Purple Heart",
    "9678b6" -> "Purple mountain majesty",
    "fe4eda" -> "Purple pizzazz",
    "50404d" -> "Purple taupe",
    "5d8aa8" -> "Rackley",
    "ff355e" -> "Radical Red",
    "e30b5d" -> "Raspberry",
    "915f6d" -> "Raspberry glace",
    "e25098" -> "Raspberry pink",
    "b3446c" -> "Raspberry rose",
    "d68a59" -> "Raw Sienna",
    "ff33cc" -> "Razzle dazzle rose",
    "e3256b" -> "Razzmatazz",
    "ff0000" -> "Red",
    "ff5349" -> "Red Orange",
    "a52a2a" -> "Red brown",
    "c71585" -> "Red violet",
    "004040" -> "Rich black",
    "d70040" -> "Rich carmine",
    "0892d0" -> "Rich electric blue",
    "b666d2" -> "Rich lilac",
    "b03060" -> "Rich maroon",
    "414833" -> "Rifle green",
    "ff007f" -> "Rose",
    "f9429e" -> "Rose bonbon",
    "674846" -> "Rose ebony",
    "b76e79" -> "Rose gold",
    "e32636" -> "Rose madder",
    "ff66cc" -> "Rose pink",
    "aa98a9" -> "Rose quartz",
    "905d5d" -> "Rose taupe",
    "ab4e52" -> "Rose vale",
    "65000b" -> "Rosewood",
    "d40000" -> "Rosso corsa",
    "bc8f8f" -> "Rosy brown",
    "0038a8" -> "Royal azure",
    "4169e1" -> "Royal blue",
    "ca2c92" -> "Royal fuchsia",
    "7851a9" -> "Royal purple",
    "e0115f" -> "Ruby",
    "ff0028" -> "Ruddy",
    "bb6528" -> "Ruddy brown",
    "e18e96" -> "Ruddy pink",
    "a81c07" -> "Rufous",
    "80461b" -> "Russet",
    "b7410e" -> "Rust",
    "00563f" -> "Sacramento State green",
    "8b4513" -> "Saddle brown",
    "ff6700" -> "Safety orange",
    "f4c430" -> "Saffron",
    "23297a" -> "Saint Patrick Blue",
    "ff8c69" -> "Salmon",
    "ff91a4" -> "Salmon pink",
    "c2b280" -> "Sand",
    "967117" -> "Sand dune",
    "ecd540" -> "Sandstorm",
    "f4a460" -> "Sandy brown",
    "967117" -> "Sandy taupe",
    "507d2a" -> "Sap green",
    "0f52ba" -> "Sapphire",
    "cba135" -> "Satin sheen gold",
    "ff2400" -> "Scarlet",
    "ffd800" -> "School bus yellow",
    "76ff7a" -> "Screamin Green",
    "006994" -> "Sea blue",
    "2e8b57" -> "Sea green",
    "321414" -> "Seal brown",
    "fff5ee" -> "Seashell",
    "ffba00" -> "Selective yellow",
    "704214" -> "Sepia",
    "8a795d" -> "Shadow",
    "45cea2" -> "Shamrock",
    "009e60" -> "Shamrock green",
    "fc0fc0" -> "Shocking pink",
    "882d17" -> "Sienna",
    "c0c0c0" -> "Silver",
    "cb410b" -> "Sinopia",
    "007474" -> "Skobeloff",
    "87ceeb" -> "Sky blue",
    "cf71af" -> "Sky magenta",
    "6a5acd" -> "Slate blue",
    "708090" -> "Slate gray",
    "003399" -> "Smalt",
    "933d41" -> "Smokey topaz",
    "100c08" -> "Smoky black",
    "fffafa" -> "Snow",
    "0fc0fc" -> "Spiro Disco Ball",
    "a7fc00" -> "Spring bud",
    "00ff7f" -> "Spring green",
    "4682b4" -> "Steel blue",
    "fada5e" -> "Stil de grain yellow",
    "990000" -> "Stizza",
    "008080" -> "Stormcloud",
    "e4d96f" -> "Straw",
    "ffcc33" -> "Sunglow",
    "fad6a5" -> "Sunset",
    "fd5e53" -> "Sunset Orange",
    "d2b48c" -> "Tan",
    "f94d00" -> "Tangelo",
    "f28500" -> "Tangerine",
    "ffcc00" -> "Tangerine yellow",
    "483c32" -> "Taupe",
    "8b8589" -> "Taupe gray",
    "cd5700" -> "Tawny",
    "d0f0c0" -> "Tea green",
    "f4c2c2" -> "Tea rose",
    "008080" -> "Teal",
    "367588" -> "Teal blue",
    "006d5b" -> "Teal green",
    "e2725b" -> "Terra cotta",
    "d8bfd8" -> "Thistle",
    "de6fa1" -> "Thulian pink",
    "fc89ac" -> "Tickle Me Pink",
    "0abab5" -> "Tiffany Blue",
    "e08d3c" -> "Tiger eye",
    "dbd7d2" -> "Timberwolf",
    "eee600" -> "Titanium yellow",
    "ff6347" -> "Tomato",
    "746cc0" -> "Toolbox",
    "ffc87c" -> "Topaz",
    "fd0e35" -> "Tractor red",
    "808080" -> "Trolley Grey",
    "00755e" -> "Tropical rain forest",
    "0073cf" -> "True Blue",
    "417dc1" -> "Tufts Blue",
    "deaa88" -> "Tumbleweed",
    "b57281" -> "Turkish rose",
    "30d5c8" -> "Turquoise",
    "00ffef" -> "Turquoise blue",
    "a0d6b4" -> "Turquoise green",
    "66424d" -> "Tuscan red",
    "8a496b" -> "Twilight lavender",
    "66023c" -> "Tyrian purple",
    "0033aa" -> "UA blue",
    "d9004c" -> "UA red",
    "536895" -> "UCLA Blue",
    "ffb300" -> "UCLA Gold",
    "3cd070" -> "UFO Green",
    "014421" -> "UP Forest green",
    "7b1113" -> "UP Maroon",
    "990000" -> "USC Cardinal",
    "ffcc00" -> "USC Gold",
    "8878c3" -> "Ube",
    "ff6fff" -> "Ultra pink",
    "120a8f" -> "Ultramarine",
    "4166f5" -> "Ultramarine blue",
    "635147" -> "Umber",
    "5b92e5" -> "United Nations blue",
    "b78727" -> "University of California Gold",
    "ffff66" -> "Unmellow Yellow",
    "ae2029" -> "Upsdell red",
    "e1ad21" -> "Urobilin",
    "d3003f" -> "Utah Crimson",
    "f3e5ab" -> "Vanilla",
    "c5b358" -> "Vegas gold",
    "c80815" -> "Venetian red",
    "43b3ae" -> "Verdigris",
    "e34234" -> "Vermilion",
    "a020f0" -> "Veronica",
    "ee82ee" -> "Violet",
    "324ab2" -> "Violet Blue",
    "f75394" -> "Violet Red",
    "40826d" -> "Viridian",
    "922724" -> "Vivid auburn",
    "9f1d35" -> "Vivid burgundy",
    "da1d81" -> "Vivid cerise",
    "ffa089" -> "Vivid tangerine",
    "9f00ff" -> "Vivid violet",
    "004242" -> "Warm black",
    "00ffff" -> "Waterspout",
    "645452" -> "Wenge",
    "f5deb3" -> "Wheat",
    "ffffff" -> "White",
    "f5f5f5" -> "White smoke",
    "ff43a4" -> "Wild Strawberry",
    "fc6c85" -> "Wild Watermelon",
    "a2add0" -> "Wild blue yonder",
    "722f37" -> "Wine",
    "c9a0dc" -> "Wisteria",
    "738678" -> "Xanadu",
    "0f4d92" -> "Yale Blue",
    "ffff00" -> "Yellow",
    "ffae42" -> "Yellow Orange",
    "9acd32" -> "Yellow green",
    "0014a8" -> "Zaffre",
    "2c1608" -> "Zinnwaldite brown")
}
share|improve this answer
    
+1 for the killer feature. –  Mr Lister Jun 27 at 7:03

Perl

Expects http://xkcd.com/color/rgb.txt in current directory. Displays five closest colours with nice percentage.

Example run

> perl code.pl
147,125,0
99.87% baby poop
98.44% yellowish brown
98.31% puke brown
97.79% poo
97.27% diarrhea

Code

#!perl -w
use strict;

sub hex2rgb ($) {
    my ($h) = @_;
    map {hex} ($h=~/[0-9a-fA-F]{2}/g)
}

sub distance ($$) {
    my ($acol1, $acol2) = @_;
    my $r = 0;
    $r += abs($acol1->[$_] - $acol2->[$_]) for (0..$#$acol1);
    $r
}

sub read_rgb {
    open my $rgb, '<', 'rgb.txt' or die $!;
    my @col;
    while (<$rgb>) {
    my ($name, $hex) = split /\t#/;
    my @rgb = hex2rgb $hex;
    push @col, [@rgb, $name];
    }
    close $rgb;
    \@col
}

my $acolours = read_rgb;
my @C = split /, */, <>;

printf "%.02f%% %s\n", (768-$_->[0])/768*100, $_->[4] for 
    (sort {$a->[0] <=> $b->[0]} 
     map [distance(\@C, $_), @$_], @$acolours)[0..4];
share|improve this answer
2  
perfect example! But also a good solution. –  Sam Denton Jun 30 at 14:35

Pharo Smalltalk

Put this in a Pharo Workspace and print it.

| color colorNames nearestColorName |
color := Color r: 255 g: 0 b: 0 range: 255.
colorNames := Color registeredColorNames copyWithout: #transparent.
nearestColorName := colorNames detectMin: [ :each | (Color named: each) diff: color].

The results are of mixed quality. All darker colors are named as gray, dark gray or very dark gray. Probably Color's diff: method could be better.

For a very simple visualization do:

((Morph newBounds: (0@0 extent: 200@200 ) color: color) addMorph: nearestColorName asMorph) openInWorld.
share|improve this answer

Well, since I had it laying around, here it is in Objective-C:

- (NSString*)colorNameFromColor:(NSColor*)chosenColor
{
    NSColor*    calibratedColor = [chosenColor colorUsingColorSpaceName:NSCalibratedRGBColorSpace];

    CGFloat  hue;
    CGFloat  saturation;
    CGFloat  brightness;
    [calibratedColor getHue:&hue
                 saturation:&saturation
                 brightness:&brightness
                      alpha:nil];

    // I found that when the saturation was below 1% I couldn't tell
    // the color from gray
    if (saturation <= 0.01)
    {
        saturation = 0.0;
    }

    NSString*   colorName   = @"";

    // If saturation is 0.0, then this is a grayscale color
    if (saturation == 0.0)
    {
        if (brightness <= 0.2)
        {
            colorName = @"black";
        }
        else if (brightness > 0.95)
        {
            colorName = @"white";
        }
        else
        {
            colorName = @"gray";

            if (brightness < 0.33)
            {
                colorName = [@"dark " stringByAppendingString:colorName];
            }
            else if (brightness > 0.66)
            {
                colorName = [@"light " stringByAppendingString:colorName];
            }
        }
    }
    else
    {
        if ((hue <= 15.0 / 360.0) || (hue > 330.0 / 360.0))
        {
            colorName = @"red";
        }
        else if (hue < 45.0 / 360.0)
        {
            colorName = @"orange";
        }
        else if (hue < 70.0 / 360.0)
        {
            colorName = @"yellow";
        }
        else if (hue < 150.0 / 360.0)
        {
            colorName = @"green";
        }
        else if (hue < 190.0 / 360.0)
        {
            colorName = @"cyan";
        }
        else if (hue < 250.0 / 360.0)
        {
            colorName = @"blue";
        }
        else if (hue < 290.0 / 360.0)
        {
            colorName = @"purple";
        }
        else
        {
            colorName = @"magenta";
        }

        if (brightness < 0.5)
        {
            colorName = [@"dark " stringByAppendingString:colorName];
        } 
        else if (brightness > 0.8)
        {
            colorName = [@"bright " stringByAppendingString:colorName];
        }
    }

    return colorName;
}
share|improve this answer

A C# Solution with Linq and KnownColors from .NET

string GetColorName(int r, int g, int b){
    return Enum.GetValues(typeof(KnownColor))
        .OfType<KnownColor>()
        .Select(x => Color.FromKnownColor(x))
        .Select(x => new {Col = x, Offset = Math.Abs(r - x.R) + Math.Abs(g - x.G) + Math.Abs(b - x.B)})
        .OrderBy(x => x.Offset)
        .Select(x => x.Col)
        .First().Name;
}
share|improve this answer

Tcl

This references X11 colors from rgb.txt. On my Ubuntu it's in /etc/X11/rgb.txt though I know on some systems it's in /usr/lib/X11/rgb.txt. Google rgb.txt and download it if you don't run X11.

#! /usr/bin/env tclsh

set f [open /etc/X11/rgb.txt]
set raw [read $f]
close $f

set COLORS {}
foreach line [split $raw \n] {
    regexp {(\d+)\s+(\d+)\s+(\d+)\s+(.+)} $line -> r g b name
    if {[info exists name] && $name != ""} {
        lappend COLORS [format %02x%02x%02x $r $g $b] $name
    }
}

proc color_distance {a b} {
    set a [scan $a %2x%2x%2x]
    set b [scan $b %2x%2x%2x]
    set dist 0

    foreach x $a y $b {
        set dist [expr {$dist + (abs($x-$y)**2)}]
    }
    return $dist
}

proc identify {given_color} {
    global COLORS
    set d 0xffffff
    set n "not found"
    set c ""

    foreach {test_color name} $COLORS {
        set dist [color_distance $given_color $test_color]
        if {$dist < $d} {
            set d $dist
            set n $name
            set c $test_color
        }
    }

    return "$n ($c)"
}

puts [identify $argv]

Pass color code as command line argument.

share|improve this answer

SAS macro, based on the (rather quaint) SAS V8 colour names as documented here: https://v8doc.sas.com/sashtml/gref/zgscheme.htm#zrs-hues

Sample input:

%rgbname(100,100,50);

Sample output:

As seen on Windows 7

EDIT: Updated with much more compact version.

%macro rgbname(r,g,b);
data _null_;
    infile "C:\temp\colours.csv" dlm = ',' lrecl=32767 missover firstobs = 2 end = eof;
    format name description $32. rgb hls $8.;
    input name description rgb hls;
    R = input(substr(rgb,3,2),hex.);
    G = input(substr(rgb,5,2),hex.);
    B = input(substr(rgb,7,2),hex.);
    retain min_distance outdesc;
    distance = (r-&r)**2 + (g-&g)**2 + (b-&b)**2;
    min_distance = min(distance, min_distance);
    if distance = min_distance then outdesc = description;
    if eof then call symput("COLOUR_NAME", outdesc);
run;
dm log "postmessage ""You meant &COLOUR_NAME""" continue;
%mend rgbname;

XKCD version - a blatant ripoff of the top answer, but it's a nice little demo of the filename URL engine, and doesn't require manual preparation of a CSV:

%macro rgb_xkcd_name(r,g,b);
filename xkcd URL "http://bpaste.net/raw/402634/" debug;
data _null_;
    infile xkcd dlm = ',][' lrecl=32767 missover end = eof;
    format r g b 3. name $32.;
    input r g b name;
    retain min_distance outname;
    distance = (r-&r)**2 + (g-&g)**2 + (b-&b)**2;
    min_distance = min(distance, min_distance);
    if distance = min_distance then outname = name;
    if eof then do;
        call symput("COLOUR_NAME", outname);
        put _all_;
    end;
run;
dm log "postmessage ""XKCD thinks you meant &COLOUR_NAME""" continue;
%mend rgb_xkcd_name;
share|improve this answer

VB.net

Function ColorName(r AS Integer, g As Integer, b As Integer)As String
  Dim nc = Color.FromArgb(255, r, g, b)
  For Each ob In [Enum].GetValues(GetType(System.Drawing.KnownColor))
    Dim c = Color.FromKnownColor(CType(ob, System.Drawing.KnownColor))
    If (c.R = nc.R) AndAlso (c.B = nc.B) AndAlso (c.G = nc.G) Then Return c.Name
  Next
  Return nc.Name
End Function
share|improve this answer
    
Am I missing something? This seems to cover only 174 out of 16 M possible RGB colors. –  Jon of All Trades Jun 27 at 14:39
    
@JonofAllTrades Depends on the questions definition output the colors name. Eg If the color doesn't have a name then it outputs the html color eg &FFFFFFFF. Does the question say output the name of the "nearest" known named color. Nope. –  Adam Speight Jun 28 at 8:30
    
As always, you like to interpret things in a different way from others. –  justhalf Jul 2 at 0:20

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.