简体   繁体   中英

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!

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]]))

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 [[best_match_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 == best_match_id); } const closest_color = get_closest_color(colors, [230, 200,0]); console.log(closest_color);

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

Color difference/similarity% between two values with JS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM