Approximate a given image using only colors from a given list The Specs


Your program must read the image from one file and write the results to another file, the name of at least the first of which should be taken from the input
You may accept and return any image format or formats, as long as you specify in your answers which ones you are using
An exception should be thrown if the specified source file does not exist
The final image must be as close as possible to the initial image (by per-pixel euclidean metric on RGB values) while using only colors from a list read from the file "colors.txt" (it will not necessarily use all of them)
When determing the nearest color, you should use the euclidean metric on RGB values, Δc=sqrt((Δr)2+(Δg)2+(Δb)2), when two or more colors on the list are equally close, any of those colors is valid
The list of colors given will be formatted with one rgb color code on each line, with spaces seperating the red, green, and blue values
You may assume that at least three but no more than 1,000 colors will be listed


This is code golf, so the shortest program wins

Some test cases:

(if RGB values in the output images do not exactly match those in the list, this is due to a problem with Java's ImageIO.write)

input:



colors.txt:


255 0 0
250 150 0
255 50 0
0 0 200
0 0 80
0 0 0


output:





input:



colors.txt:


100 60 0
0 0 20
0 0 70
0 20 90
15 15 15
100 100 100
120 120 120
150 150 150


output:





input:



colors.txt:


0 0 0
10 20 15
25 25 20
35 30 20
40 35 25
55 55 60
70 60 50
130 100 80
130 140 145
140 100 70
165 130 90
200 160 130
230 210 220
250 250 250


output:





input:



colors.txt:


0 0 0
70 50 40
80 0 0
120 100 90
120 120 120
170 150 90
170 170 170
170 200 195
190 140 100
190 205 165
210 170 120


output:



Again, I put together a java program to generate the sample output. I'll golf it down a little further, and then I may post it as an answer later.
Mathematica 109 100 97 111
Update: now outputs the image as required.
The function, f, replaces a single pixel with the closest pixel found in the input file (in this case, &quot;colors.txt&quot;).
t is the output file.
The function, g, applies f to each pixel in the input image.
g[i_,h_,t_]:=Export[t,(c=Import[h,&quot;Data&quot;]/255;
f@p_:=Sort[{p~EuclideanDistance~#,#}&amp;/@c][[1,2]];f~ImageApply~i)]

Test Cases
Example 1: Seascape
(*creating &quot;colors.txt&quot;*)
    c = &quot;255 0 0
      250 150 0
      255 50 0
      0 0 200
      0 0 80
      0 0 0&quot;;
    Export[&quot;colors.txt&quot;, c]



Example 2: Earth from moon
I'll skip the part about storing the color info into &quot;colors.txt&quot;.
It closely follows example 1.


Example 3: Jupiter


Example 4: American Gothic