简体   繁体   English

从 javascript/nodejs 中的表中找到最接近的 RGB 值

[英]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.我正在制作一个程序,该程序需要使用 Jimp 尝试找到最接近的大量像素的 RGB 匹配。

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) (其中一个数组中的第一个数字可以忽略,其余的只是 R、G 和 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)所以如果我有一个像 (255,7,1) 这样的红色,我想把它和我桌子上的红色相匹配,是 (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. RGB 是一个 3 维空间。 Consider a color as a point in 3d space, you should find most closest distance between two points by using 3d pythagoras.将颜色视为 3d 空间中的一个点,您应该使用 3d 毕达哥拉斯找到两点之间最接近的距离。

 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使用此处的函数查找 E 距离最小的颜色

Color difference/similarity% between two values with JS JS 两个值之间的色差/相似度%

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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