<p>也许有更好的方法来做这件事,我不确定。
如果您阅读<code>help(cm.jet)</code>,您将看到用于将间隔[0,1]中的值映射到rgb3元组的算法。你可以用一点纸和铅笔,算出公式来反转定义映射的分段线性函数。在</p>
<p>然而,有许多问题使纸笔解决方案有些不吸引人:</p>
<ol>
<li><p>这是一个很费劲的代数,而且
解决方案针对厘米喷气式飞机.
你得把这些工作再做一遍
如果你改变颜色贴图。如何自动解决这些代数方程是有趣的,但不是一个我知道如何解决的问题。</p></li>
<li><p>一般来说,颜色贴图可能不是
可逆(多个值可能
映射到相同的颜色)。在
案例厘米喷气式飞机,值在0.11之间
和0.125都映射到RGB
例如,三元组(0,0,1)。所以如果
你的图像包含纯蓝色
像素,真的没有办法
判断它是否来自0.11的值
或者一个0.125的值。</p></li>
<li>从[0,1]到
三元组是3空间中的曲线。这个
你形象中的颜色可能不会说谎
完全在这条曲线上。有可能
例如,舍入误差。因此,任何实际的解决方案都必须能够插值或以某种方式将3维空间中的点投影到曲线上。在</li>
</ol>
<p>由于非唯一性问题和投影/插值问题,您提出的问题可能有许多可能的解决方案。以下只是一种可能性。在</p>
<p>以下是解决唯一性和投影/插值问题的一种方法:</p>
<p>创建一个<code>gradient</code>,它充当“代码本”。<code>gradient</code>是厘米喷气式飞机彩色地图。<code>gradient</code>的颜色对应于从0到1的值。使用scipy的矢量量化函数<a href="http://docs.scipy.org/doc/scipy/reference/cluster.vq.html#scipy.cluster.vq.vq" rel="nofollow noreferrer">scipy.cluster.vq.vq</a>来映射图像中的所有颜色,mri_演示.png,转换为<code>gradient</code>中最近的颜色。
由于颜色贴图可能对许多值使用相同的颜色,因此渐变可能包含重复的颜色。我把它留给<code>scipy.cluster.vq.vq</code>来决定哪个(可能)非唯一的代码本索引与特定的颜色相关联。在</p>
<pre><code>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()
</code></pre>
<p>你看到的图像应该接近于核磁共振成像_演示.png公司名称:</p>
<p><img src="https://i.stack.imgur.com/0dYWX.png" alt="alt text"/></p>
<p>(最初的核磁共振成像_演示.png有一个白色的边界。因为白色不是一种颜色厘米喷气式飞机,请注意,<code>scipy.cluster.vq.vq</code>将白色映射到<code>gradient</code>代码本中最近的点,这恰好是淡绿色。)</p>