<p>这里有两种方法,一种使用Matplotlib,另一种只使用OpenCV</p>
<p>方法1:</strong><code>OpenCV</code>+<a href="https://matplotlib.org/3.1.1/api/cm_api.html#matplotlib.cm.get_cmap" rel="nofollow noreferrer">^{<cd2>}</a></p>
<p>为了实现灰度(1通道)<code>-></code>热图(3通道)转换,我们首先将图像加载为灰度。默认情况下,OpenCV以3通道、8位BGR读取图像。
我们可以使用带<code>cv2.IMREAD_GRAYSCALE</code>参数的<a href="https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_image_display/py_image_display.html#using-opencv" rel="nofollow noreferrer">^{<cd4>}</a>直接将图像加载为灰度,或者使用<a href="https://docs.opencv.org/2.4/modules/imgproc/doc/miscellaneous_transformations.html#cvtcolor" rel="nofollow noreferrer">^{<cd6>}</a>将BGR图像转换为带有<code>cv2.COLOR_BGR2GRAY</code>参数的灰度图像。加载图像后,我们将此灰度图像放入Matplotlib以获得热图图像。Matplotlib返回一个RGB格式,因此我们必须转换回Numpy格式并切换到BGR colorspace,以便与OpenCV一起使用。下面是一个使用科学的红外相机图像作为输入的例子。请参阅<a href="https://matplotlib.org/3.1.0/tutorials/colors/colormaps.html" rel="nofollow noreferrer">choosing color maps in Matplotlib</a>以获取根据您所需的用例而提供的内置颜色图。在</p>
<p>输入图像:</p>
<p><img src="https://i.stack.imgur.com/0bXCi.png" width="500"/></p>
<p>输出热图图像:</p>
<p><img src="https://i.stack.imgur.com/nK4U8.jpg" width="500"/></p>
<p>代码</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
import cv2
image = cv2.imread('frame.png', 0)
colormap = plt.get_cmap('inferno')
heatmap = (colormap(image) * 2**16).astype(np.uint16)[:,:,:3]
heatmap = cv2.cvtColor(heatmap, cv2.COLOR_RGB2BGR)
cv2.imshow('image', image)
cv2.imshow('heatmap', heatmap)
cv2.waitKey()
</code></pre>
<p>方法二:</strong><a href="https://docs.opencv.org/2.4/modules/contrib/doc/facerec/colormaps.html" rel="nofollow noreferrer">^{<cd9>}</a></p>
<p>我们可以使用OpenCV内置的热图函数。以下是使用<code>cv2.COLORMAP_HOT</code>热图得到的结果</p>
<p><img src="https://i.stack.imgur.com/8Zzf0.png" width="500"/></p>
<p>代码</p>
^{pr2}$
<hr/>
<p><strong>注意:</strong>虽然OpenCV的内置实现既短又快,但我建议使用方法1,因为有更大的colormap选择。Matplotlib有<a href="https://matplotlib.org/3.1.0/tutorials/colors/colormaps.html#choosing-colormaps-in-matplotlib" rel="nofollow noreferrer">hundreds of various colormaps</a>,允许您<a href="https://matplotlib.org/3.1.0/tutorials/colors/colormap-manipulation.html" rel="nofollow noreferrer">create your own custom color maps</a>,而OpenCV只有12个可供选择。以下是内置的OpenCV颜色贴图选择:</p>
<p><img src="https://i.stack.imgur.com/uCw5b.png" height="400"/></p>