使用imshow绘制RGB图像时如何解释和调整颜色条?

问题描述 投票:0回答:1

我有一个像这样的 2x2x3 numpy 数组

import matplotlib.pyplot as plt
import numpy as np

red = np.array([[0, 50], [100, 200]])
green = np.array([[0, 185], [100, 255]])
blue = np.array([[0, 129], [0, 255]])

combined = np.stack((red, green, blue), -1)
# [[[  0,   0,   0],
#   [ 50, 185, 129]],
#  [[100, 100,   0],
#   [200, 255, 255]]]

我可以用颜色绘制数组。

plt.figure()
im = plt.imshow(
  X=combined,
  vmin=0, 
  vmax=255, 
  interpolation='none',
  aspect='equal',
)
plt.colorbar()
plt.show()

enter image description here

我也可以只绘制红色通道,就像这样

reds = combined.copy()
reds[:, :, 1:] = 0

plt.figure()
im = plt.imshow(
  X=reds,
  vmin=0, 
  vmax=255, 
  interpolation='none',
  aspect='equal',
)
plt.colorbar()
plt.show()

enter image description here

但是我正在为两个问题苦苦挣扎..

  1. 第一个绘图事件中的颜色条是否有效。我不知道如何解释它。
  2. 如何将第二个图中的颜色条从 0(黑色)更改为 255(红色)?显然我希望颜色条值和比例与实际的绘图行为相匹配。
python matplotlib
1个回答
0
投票

您可以使用

LinearSegmentedColormap()
并将其传递给
cmap
:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LinearSegmentedColormap


def get_colorbar(X):
    cmap = LinearSegmentedColormap.from_list('black_and_red', ((0, 0, 0), (1, 0, 0)))
    plt.figure()
    im = plt.imshow(
        X=X,
        cmap=cmap,
        vmin=0,
        vmax=255,
        interpolation='none',
        aspect='equal',
    )
    plt.colorbar()
    plt.show()


red = np.array([[0, 50], [100, 200]])
green = np.array([[0, 185], [100, 255]])
blue = np.array([[0, 129], [0, 255]])
combined = np.stack((red, green, blue), -1)
get_colorbar(combined[:, :, 0])


enter image description here

  • 第一个图中的颜色条也是有效的。
© www.soinside.com 2019 - 2024. All rights reserved.