要转换为颜色图,我做
import cv2
im = cv2.imread('test.jpg', cv2.IMREAD_GRAYSCALE)
im_color = cv2.applyColorMap(im, cv2.COLORMAP_JET)
cv2.imwrite('colormap.jpg', im_color)
Run Code Online (Sandbox Code Playgroud)
然后,
cv2.imread('colormap.jpg')
# ??? What should I do here?
Run Code Online (Sandbox Code Playgroud)
显然,以灰度(使用, 0)读取它不会神奇地给我们灰度,那么我该怎么做呢?
您可以创建颜色图的逆,即从颜色图值到相关灰度值的查找表。如果使用查找表,则需要原始颜色图的精确值。在这种情况下,伪彩色图像很可能需要以无损格式保存,以避免更改颜色。可能有一种更快的方法来映射 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))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8093 次 |
| 最近记录: |