可能有更好的方法来做到这个;我不确定。 如果您阅读help(cm.jet)
,您将看到用于将区间[0,1]中的值映射到RGB 3元组的算法。你可以用一些纸和铅笔制定公式来反演定义映射的分段线性函数。
不过,也有一些这使纸张和铅笔的解决方案有些不吸引人的问题:
这是一个很大费力的代数和 该解决方案是具体的cm.jet。 如果更改颜色映射表,则必须再次执行所有这些工作 。如何自动化解这些代数方程是有趣的,但不是我知道如何解决的问题。
一般而言,颜色映射可能不是 可逆(可能有多于一个值可能会映射到相同颜色的 )。例如,在cm.jet的 的情况下,0.11 和0.125之间的值全都被映射到三元组(0,0,1)的RGB 。因此,如果您的图片包含纯蓝色 像素,则确实无法通过 判断它是来自0.11 的值还是0.125的值。
- 从[0,1]到 三元组的映射是三维空间中的一条曲线。在这条曲线上,图像中的 颜色可能不会完美地包含 。例如,可能有 是舍入错误。所以任何实际的解决方案都必须能够插入或以某种方式将三维空间中的点投影到曲线上。
由于非唯一性问题以及投影/插值问题,可能会有很多可能的解决方案来解决您提出的问题。以下只是一种可能性。
这是解决的独特性和投影/插值问题的一种方法:
创建gradient
充当“码书”。 gradient
是cm.jet彩色贴图中的一组RGBA四元组。 gradient
的颜色对应于从0到1的值。使用scipy的矢量量化函数scipy.cluster.vq.vq将图像中的所有颜色mri_demo.png映射到gradient
的最近颜色。 由于彩色贴图可能对许多值使用相同的颜色,因此渐变可能包含重复的颜色。我把它留到scipy.cluster.vq.vq
来决定哪个(可能)非唯一的代码簿索引与特定的颜色关联。
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
import scipy.cluster.vq as scv
def colormap2arr(arr,cmap):
# http://stackoverflow.com/questions/3720840/how-to-reverse-color-map-image-to-scalar-values/3722674#3722674
gradient=cmap(np.linspace(0.0,1.0,100))
# Reshape arr to something like (240*240, 4), all the 4-tuples in a long list...
arr2=arr.reshape((arr.shape[0]*arr.shape[1],arr.shape[2]))
# Use vector quantization to shift the values in arr2 to the nearest point in
# the code book (gradient).
code,dist=scv.vq(arr2,gradient)
# code is an array of length arr2 (240*240), holding the code book index for
# each observation. (arr2 are the "observations".)
# Scale the values so they are from 0 to 1.
values=code.astype('float')/gradient.shape[0]
# Reshape values back to (240,240)
values=values.reshape(arr.shape[0],arr.shape[1])
values=values[::-1]
return values
arr=plt.imread('mri_demo.png')
values=colormap2arr(arr,cm.jet)
# Proof that it works:
plt.imshow(values,interpolation='bilinear', cmap=cm.jet,
origin='lower', extent=[-3,3,-3,3])
plt.show()
你看到的应该是接近再生mri_demo.png图像:
(原mri_demo.png有白色边框由于白色是不是在cm.jet的颜色。请注意,以scipy.cluster.vq.vq
白色映射到最接近的点在gradient
码书,这恰好是淡绿色。)
是的,这基本上是我认为是可能的。您的初始解决方案包括从具有相同颜色图的图像中读取一条线,这可能对那些说,扫描一个数字并希望进行自己的数字分析的人有所帮助。我陷入了矢量量化的问题 - 最初,似乎最好的选择是循环遍历每个可能的颜色,并计算出距离实际像素值的3d距离 - 我无法看到如何快速执行循环。谢谢! – user448764 2010-09-16 20:33:19