开发者

Checking if a color is in a specific range of colors

开发者 https://www.devze.com 2023-02-17 12:58 出处:网络
How would you check if a rgb or hex value is within a specific range of colors? Preferably with ruby.

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 ot开发者_运维问答her close hex values.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消