codingmaster398
codingmaster398

Reputation: 257

Find the closest RGB value from a table in javascript/nodejs

people of the internet! I'm making a program that needs to try and find the closest RGB match of lots of pixels, using Jimp.

Say if you had a color that was slightly purple, I would want to change it to the purple that I have in my table, here:

    var colors = [
        [0,0,255,0],
        [1,255,165,0],
        [2,0,0,255],
        [3,255,192,203],
        [4,165,42,42],
        [5,255,255,255],
        [6,0,0,0],
        [7,230,230,350],
        [8,255,255,0],
        [9,0,0,0],
    ]

(the first number in one of these arrays can be ignored, the rest are just R, G, and B)

So if I had a red like (255,7,1) I would like to match that to the red in my table, being (255,0,0)

I have tried something, but rather it was very dumb and didn't work, so I will spare you the details.

Can anybody help me? Thanks!

Upvotes: 1

Views: 808

Answers (3)

samuelcolt
samuelcolt

Reputation: 263

RGB is a 3-dimensional space. Consider a color as a point in 3d space, you should find most closest distance between two points by using 3d pythagoras.

const colors = [
  [0,0,255,0],
  [1,255,165,0],
  [2,0,0,255],
  [3,255,192,203],
  [4,165,42,42],
  [5,255,255,255],
  [6,0,0,0],
  [7,230,230,350],
  [8,255,255,0],
  [9,0,0,0],
]

function get_closest_color(colors, [r2, g2, b2]) {
  const [[closest_color_id]] = (
    colors
    .map(([id, r1,g1,b1]) => (
      [id, Math.sqrt((r2-r1)**2 + (g2-g1)**2 + (b2-b1)**2)]
    ))
    .sort(([, d1], [, d2]) => d1 - d2)
  );
  return colors.find(([id]) => id == closest_color_id);
}

const closest_color = get_closest_color(colors, [230, 200,0]);
console.log(closest_color);

Upvotes: 5

R4ncid
R4ncid

Reputation: 7129

If I undestand your question correctly you can do something like this

const colors = [
        [0,0,255,0],
        [1,255,165,0],
        [2,0,0,255],
        [3,255,192,203],
        [4,165,42,42],
        [5,255,255,255],
        [6,0,0,0],
        [7,230,230,350],
        [8,255,255,0],
        [9,0,0,0],
    ]
    
const findClosestColor = (color, colors) => 
 colors.reduce((res, c) => {
 
  const distance = [1,2,3].reduce((sum, i) => sum + Math.abs(c[i] - color[i]), 0)
  if(distance > res.distance){
   return res;
  }
  return {
   closest: c,
   distance
  }
 }, {closest: null, distance: 9999} ).closest



console.log(findClosestColor([0, 255,7,1], [[1,0,0,200], [2,255,0,0], [3, 128,128,128]]))

Upvotes: 0

resle
resle

Reputation: 2364

Use the function(s) from here to find the color with the smallest E distance

Color difference/similarity% between two values with JS

Upvotes: -1

Related Questions