Checking if a color is in a specific range of colors

和自甴很熟 提交于 2019-12-08 08:17:34

问题


How would you check if a rgb or hex value is within a specific range of colors? Preferably with ruby.

I'm using ruby and rmagick to extract colors (quantize and color_histogram) from images and then store those colors in the database. If someone searched for a color(hex or rgb) that is similar I want to be able to return that color.

e.g. If someone searched for #f4f4f4 I'd like to return #f5f5f5, #f3f3f3, and all the other close hex values.


回答1:


If you treat RGB as a three-dimensional space with R, G and B being the axes, you can define "close colors" as a cube or a sphere around a color and return all the colors inside it (or check for a given color if it's close enough). Formulars for that are quite simple:

Original color R, G, B
Cube with side length L around it:
  All colors between (R - L/2, G - L/2, B - L/2) and (R + L/2, G + L/2, B + L/2)
Sphere with radius R around it:
  New color R_new, G_new, B_new is inside if
    delta_r * delta_r + delta_g * delta_g + delta_b * delta_b < R * R
      where
        delta_r = abs(R - R_new)
        delta_g = abs(G - G_new)
        delta_b = abs(B - B_new)

Using a sphere instead of a cube is the "correct" way, but it won't make much of a difference for small ones and the colors inside the cube are a bit easier to calculate.



来源:https://stackoverflow.com/questions/5333491/checking-if-a-color-is-in-a-specific-range-of-colors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!