范围值为伪彩色 [英] Range values to pseudocolor
问题描述
我有一个浮点数(在Python中)可能范围从0到100.我想创建一个伪彩色图像,使颜色从绿色(对应于0)到红色(100)。这类似于matplotlib的pcolor。但是,我不想使用pcolor。
I have a certain array of floats (in Python) that might range from 0 to 100. I want to create a pseudo-color image so that the colors vary from green (corresponding to 0) to red (100). This is similar to pcolor from matplotlib. However, I do not want to use pcolor.
有一个函数,如pseudocolorForValue(val,(minval,maxval))返回一个RGB三元组, 'val'的颜色值?此外,在此功能中是否有灵活性来选择是显示从绿色到红色还是从红色到绿色的颜色?
Is there a function like pseudocolorForValue(val,(minval,maxval)) which returns an RGB triple corresponding to the pseudo-color value for 'val'? Also, is there a flexibility in this function to choose whether to display colors from green-to-red or from red-to-green?
谢谢,
Nik
Thanks, Nik
推荐答案
您可以编写自己的函数,将0..100转换为0..120度, HLS(或HSV)色彩空间中的颜色的H(或角度)。
You could write your own function that converted 0..100 to 0..120 degrees and then used that value as the H (or angle) of a color in the HLS (or HSV) colorspace. This could then be converted into an RGB color for display purposes.
更新:
好消息,原来Python在其内置的 colorsys
模块(它们真的意味着包括电池)。有什么很好的是,它使创建一个函数,做我所描述的相当容易,如下所示:
Good news, turns out that Python has colorspace conversion routines in its built-in colorsys
module (they really mean "batteries included"). What's nice about that is that it makes creating a function that does what I described fairly easy, as illustrated below:
import colorsys
def pseudocolor(val, minval, maxval):
# convert val in range minval..maxval to the range 0..120 degrees which
# correspond to the colors red..green in the HSV colorspace
h = (float(val-minval) / (maxval-minval)) * 120
# convert hsv color (h,1,1) to its rgb equivalent
# note: the hsv_to_rgb() function expects h to be in the range 0..1 not 0..360
r, g, b = colorsys.hsv_to_rgb(h/360, 1., 1.)
return r, g, b
if __name__ == '__main__':
steps = 10
print 'val R G B'
for val in xrange(0, 100+steps, steps):
print '%3d -> (%.3f, %.3f, %.3f)' % ((val,) + pseudocolor(val, 0, 100))
输出:
val R G B
0 -> (1.000, 0.000, 0.000)
10 -> (1.000, 0.200, 0.000)
20 -> (1.000, 0.400, 0.000)
30 -> (1.000, 0.600, 0.000)
40 -> (1.000, 0.800, 0.000)
50 -> (1.000, 1.000, 0.000)
60 -> (0.800, 1.000, 0.000)
70 -> (0.600, 1.000, 0.000)
80 -> (0.400, 1.000, 0.000)
90 -> (0.200, 1.000, 0.000)
100 -> (0.000, 1.000, 0.000)
下面是一个示例,显示其输出结果:
Here's a sample showing what its output looks like:
我想你可能会发现颜色比我的其他答案更好。
I think you may find the colors generated nicer than in my other answer.
这篇关于范围值为伪彩色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!