cjo*_*sen 5 matplotlib scikit-image colormap
我想将其打印为灰度图像。我可以使用以下方法进行转换scikit-image:
from skimage.io import imread
from matplotlib import pyplot as plt
from skimage.color import rgb2gray
img = imread('image.jpg')
plt.grid(which = 'both')
plt.imshow(rgb2gray(img), cmap=plt.cm.gray)
Run Code Online (Sandbox Code Playgroud)
我得到:
这显然不是我想要的。
我的问题是:有没有办法使用scikit-image或使用原始图像numpy和/或mathplotlib数字化图像,以便我得到一个 3D 数组(第一维:X 索引,第二维:Y 索引,第三维:根据颜色图的值)。然后我可以轻松地将颜色图更改为在灰度打印时结果更好的东西?
下面的示例演示了一种撤消颜色value -> RGB图映射的简单方法。
def unmap_nearest(img, rgb):
""" img is an image of shape [n, m, 3], and rgb is a colormap of shape [k, 3]. """
d = np.sum(np.abs(img[np.newaxis, ...] - rgb[:, np.newaxis, np.newaxis, :]), axis=-1)
i = np.argmin(d, axis=0)
return i / (rgb.shape[0] - 1)
Run Code Online (Sandbox Code Playgroud)
此函数通过获取每个像素的 RGB 值并在颜色图中查找最佳匹配颜色的索引来工作。索引和广播的一些技巧允许有效的向量化(以在临时数组上花费的内存为代价):
img[np.newaxis, ...] 将图像从形状 [n, m, 3] 转换为 [1, n, m, 3]
rgb[:, np.newaxis, np.newaxis, :] 将颜色图从形状 [k, 3] 转换为 [k, 1, 1, 3]。
k和n, m每个颜色分量的像素之间的差异。sum(abs(..), axis=-1) 取所有颜色分量(最后一个维度)的差异和总和的绝对值,以获得所有像素和颜色映射条目(形状数组 [k, n, m])之间的总差异。i = np.argmin(d, axis=0)查找沿第一维的最小元素的索引。结果是每个像素 [n, m] 的最佳匹配颜色图条目的索引。return i / (rgb.shape[0] - 1) 最后返回由颜色图大小标准化的索引,以便结果在 0-1 范围内。这种方法有一个警告:
.
import numpy as np
import matplotlib.pyplot as plt
from skimage.color import rgb2gray
def unmap_nearest(img, rgb):
""" img is an image of shape [n, m, 3], and rgb is a colormap of shape [k, 3]. """
d = np.sum(np.abs(img[np.newaxis, ...] - rgb[:, np.newaxis, np.newaxis, :]), axis=-1)
i = np.argmin(d, axis=0)
return i / (rgb.shape[0] - 1)
cmap = plt.cm.jet
rgb = cmap(np.linspace(0, 1, cmap.N))[:, :3]
original = (np.arange(10)[:, None] + np.arange(10)[None, :])
plt.subplot(2, 2, 1)
plt.imshow(original, cmap='gray')
plt.colorbar()
plt.title('original')
plt.subplot(2, 2, 2)
rgb_img = cmap(original / 18)[..., :-1]
plt.imshow(rgb_img)
plt.title('color-mapped')
plt.subplot(2, 2, 3)
wrong = rgb2gray(rgb_img)
plt.imshow(wrong, cmap='gray')
plt.title('rgb2gray')
plt.subplot(2, 2, 4)
reconstructed = unmap_nearest(rgb_img, rgb)
plt.imshow(reconstructed, cmap='gray')
plt.colorbar()
plt.title('reconstructed')
plt.show()
Run Code Online (Sandbox Code Playgroud)