Opencv(Jetmap或colormap为灰度,反向applyColorMap())

仓廪实则知礼节,衣食足则知荣辱。这篇文章主要讲述Opencv:Jetmap或colormap为灰度,反向applyColorMap()相关的知识,希望能为你提供帮助。
要转换为色彩映射,我做

import cv2 im = cv2.imread('test.jpg', cv2.IMREAD_GRAYSCALE) im_color = cv2.applyColorMap(im, cv2.COLORMAP_JET) cv2.imwrite('colormap.jpg', im_color)

然后,
cv2.imread('colormap.jpg') # ??? What should I do here?

显然,以灰度(使用, 0)读取它不会神奇地给我们灰度,所以我该怎么做?
答案【Opencv(Jetmap或colormap为灰度,反向applyColorMap())】您可以创建颜色映射的反转,即从颜色映射值到关联灰度值的查找表。如果使用查找表,则需要原始色彩映射的精确值。在这种情况下,假彩色图像很可能需要以无损格式保存,以避免颜色被改变。可能有更快的方法在numpy数组上进行映射。如果无法保留精确值,则需要在逆映射中进行最近邻居查找。
import cv2 import numpy as np# load a color image as grayscale, convert it to false color, and save false color version im_gray = cv2.imread('test.jpg', cv2.IMREAD_GRAYSCALE) cv2.imwrite('gray_image_original.png', im_gray) im_color = cv2.applyColorMap(im_gray, cv2.COLORMAP_JET) cv2.imwrite('colormap.png', im_color) # save in lossless format to avoid colors changing# create an inverse from the colormap to gray values gray_values = np.arange(256, dtype=np.uint8) color_values = map(tuple, cv2.applyColorMap(gray_values, cv2.COLORMAP_JET).reshape(256, 3)) color_to_gray_map = dict(zip(color_values, gray_values))# load false color and reserve space for grayscale image false_color_image = cv2.imread('colormap.png')# apply the inverse map to the false color image to reconstruct the grayscale image gray_image = np.apply_along_axis(lambda bgr: color_to_gray_map[tuple(bgr)], 2, false_color_image)# save reconstructed grayscale image cv2.imwrite('gray_image_reconstructed.png', gray_image)# compare reconstructed and original gray images for differences print('Number of pixels different:', np.sum(np.abs(im_gray - gray_image) > 0))


    推荐阅读