简体   繁体   English

Python中的相似颜色检测

[英]Similar color detection in Python

Given a color either in RGB or Hex, how do I find colors that are similar to it?给定 RGB 或 Hex 颜色,如何找到与其相似的颜色? By similar I mean they should be distinguishable by small values.相似我的意思是它们应该通过小的值来区分。

The RGB color space is device dependent and not perceptually uniform. RGB 颜色空间取决于设备,并且在感知上并不统一。 If you intend to measure color similarities, you should transform first the RGB values into a device-independent and more perceptually uniform color space, for example CIELAB .如果您打算测量颜色相似性,您应该首先将 RGB 值转换为与设备无关且在感知上更加统一的颜色空间,例如CIELAB Then you can measure the color differences through a proper similarity metric, like Lab Delta E .然后,您可以通过适当的相似性度量来衡量颜色差异,例如Lab Delta E。

Demo演示

Consider this image :考虑这个图像

原图

Let us assume that your reference colors are a shade of green and a shade of magenta, whose RGB values are for example [0, 160, 0] and [120, 0, 140] .让我们假设您的参考颜色是绿色阴影和洋红色阴影,其 RGB 值例如为[0, 160, 0][120, 0, 140] The following snippet identifies those image pixels whose Delta E with respect to the reference colors is lower than a certain threshold ( 15 and 20 , respectively).下面的代码片段标识了那些相对于参考颜色的 Delta E 低于某个阈值(分别为1520 )的图像像素。

import numpy as np
from skimage import io
from skimage.color import rgb2lab, deltaE_cie76

rgb = io.imread('https://i.stack.imgur.com/npnrv.png')
lab = rgb2lab(rgb)

green = [0, 160, 0]
magenta = [120, 0, 140]

threshold_green = 15    
threshold_magenta = 20    

green_3d = np.uint8(np.asarray([[green]]))
magenta_3d = np.uint8(np.asarray([[magenta]]))

dE_green = deltaE_cie76(rgb2lab(green_3d), lab)
dE_magenta = deltaE_cie76(rgb2lab(magenta_3d), lab)

rgb[dE_green < threshold_green] = green_3d
rgb[dE_magenta < threshold_magenta] = magenta_3d
io.imshow(rgb)

检测到相似颜色

Based on Tonechas answer,根据 Tonechas 的回答,

To have a similar color detection value (and not a visualization):要具有类似的颜色检测(而不是可视化):

import numpy as np
from skimage import io
from skimage.color import rgb2lab, deltaE_cie76

def get_pct_color(img_rgb, rgb_color, threshold=10):
    img_lab = rgb2lab(img_rgb)
    rgb_color_3d = np.uint8(np.asarray([[rgb_color]]))
    rgb_color_lab = rgb2lab(rgb_color_3d)
    delta = deltaE_cie76(rgb_color_lab, img_lab)
    x_positions, y_positions = np.where(delta < threshold)
    nb_pixel = img_rgb.shape[0] * img_rgb.shape[1]
    pct_color = len(x_positions) / nb_pixel
    return pct_color

With an example:举个例子:

img_rgb = io.imread('https://i.stack.imgur.com/npnrv.png')
green = [0, 160, 0]
get_pct_color(img_rgb, green, 10)
# 0.016131591796875
get_pct_color(img_rgb, green, 250)
# 1.0

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

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