将MatplotLib或自定义颜色图应用于OpenCV图像 [英] Apply MatplotLib or custom colormap to OpenCV image

查看:124
本文介绍了将MatplotLib或自定义颜色图应用于OpenCV图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

OpenCV的颜色图数量有限. MatplotLib具有更多的颜色图,但是将这些颜色图应用于给定的OpenCV图像并非易事.使用Python API时,如何将下一页的MatplotLib颜色映射应用于OpenCV图像?这类似于将自定义颜色图应用于给定图像.

OpenCV has a limited amount of color maps. MatplotLib has many more color maps, but it is not straightforward to apply these colormaps to given OpenCV images. How to apply MatplotLib color maps from the page below to OpenCV images when using the Python API? This is similar to applying a custom colormap to a given image.

https://matplotlib.org/examples/color/colormaps_reference.html

推荐答案

回答我自己的问题,因为在StackOverflow上找不到简单的解决方案:

Answering my own question because I did not find an easy solution on StackOverflow:

def apply_custom_colormap(image_gray, cmap=plt.get_cmap('seismic')):

    assert image_gray.dtype == np.uint8, 'must be np.uint8 image'
    if image_gray.ndim == 3: image_gray = image_gray.squeeze(-1)

    # Initialize the matplotlib color map
    sm = plt.cm.ScalarMappable(cmap=cmap)

    # Obtain linear color range
    color_range = sm.to_rgba(np.linspace(0, 1, 256))[:,0:3]    # color range RGBA => RGB
    color_range = (color_range*255.0).astype(np.uint8)         # [0,1] => [0,255]
    color_range = np.squeeze(np.dstack([color_range[:,2], color_range[:,1], color_range[:,0]]), 0)  # RGB => BGR

    # Apply colormap for each channel individually
    channels = [cv2.LUT(image_gray, color_range[:,i]) for i in range(3)]
    return np.dstack(channels)


image_gray = cv2.imread('./lena.jpg', cv2.IMREAD_GRAYSCALE)
image_bgr = apply_custom_colormap(image_gray, cmap=plt.get_cmap('bwr'))

cv2.imshow('image with colormap', image_bgr)
cv2.waitKey(0)

产生图像:

这篇关于将MatplotLib或自定义颜色图应用于OpenCV图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆