Opencv:将Jetmap或colormap转换为灰度,然后反转applyColorMap()

时间:2018-08-13 14:29:59

标签: python opencv

我要转换为颜色图

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读取它不会神奇地为我们提供灰度级,那我该怎么做?

1 个答案:

答案 0 :(得分:3)

您可以创建颜色映射的逆图,即从颜色映射值到关联的灰度值的查找表。如果使用查找表,则需要原始色图的准确值。在这种情况下,很可能需要以无损格式保存错误的彩色图像,以免更改颜色。可能有一种更快的方法可以在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))