RGB / HEX到Colormap值

时间:2017-03-14 04:55:17

标签: colors rgb colormap color-mapping

我想在给定特定色彩图的情况下将RGB / HEX颜色转换为相应的(标准化)数值。有许多实用程序可以执行正向操作(即使用色彩映射将一组规范化值映射到RGB / HEX颜色),但我无法找到任何反向执行。

正向:

> import matplotlib.cm as cm
> cm.viridis([.2, .4, .6, .8, 1])

array([[ 0.253935,  0.265254,  0.529983,  1.      ],
       [ 0.163625,  0.471133,  0.558148,  1.      ],
       [ 0.134692,  0.658636,  0.517649,  1.      ],
       [ 0.477504,  0.821444,  0.318195,  1.      ],
       [ 0.993248,  0.906157,  0.143936,  1.      ]])

我怎样才能从[ 0.253935, 0.265254, 0.529983, 1. ]0.2,当然知道这些来自viridis

1 个答案:

答案 0 :(得分:0)

我可以用Matlab实现给你一个例子(解释反向映射的原理)。

如果您正在寻找Python实现,请在您的问题中添加Python标记。

这是我的代码示例(解释在评论中):

array = [0.253935,  0.265254,  0.529983,  1;
         0.163625,  0.471133,  0.558148,  1;
         0.134692,  0.658636,  0.517649,  1;
         0.477504,  0.821444,  0.318195,  1;
         0.993248,  0.906157,  0.143936,  1];

%c is the RGB value (value is assumed to exist in array).
c = [0.253935,  0.265254,  0.529983,  1];

%B is the mapped value.
B = [.2, .4, .6, .8, 1];

%1 Remove the alpha channel (assume all alpha values equal 1):
A = array(:, 1:3);

%2. Convert from normalized value in range [0, 1] to fixed point values in range [0, 255].
%(assume each color channel is a byte).
A = round(A*255);

%3. Convert RGB triple to single fixed point value (24 bits integer).
%   Remark: For best performance, you can create a Look Up Table (16MBytes look up table that maps all possible combinations).
%   Remark: You can also create a Dictionary.
A = A(:,1) + A(:,2)*2^8 + A(:,3)*2^16;

%4. Do the same conversion for c:
c = round(c*255);
c = c(1)+c(2)*2^8+c(3)*2^16;

%5. Find index of c in A:
%   Remark: In case A is sorted, you can use binary search.
%   Remark: In case A is Look Up Table (or dictionary), you can use something like idx = A(c).
idx = find(A == c);

%6. The result is B in place idx:
reverse_val = B(idx)

结果:

reverse_val =

    0.2000

在Python中你可以找到一个快捷方式,如:转换为字符串,构建字典(从字符串到索引或值)...