使用 imshow 打印一种颜色 [关闭]

2023-12-28

我想使用 RGB 值在屏幕上打印颜色,并且输出应该只是单一颜色。例如,如果我给出红色的 RGB 值,我希望输出显示红色。但是当我尝试这段代码时,它不起作用。我缺少什么?

import matplotlib.pyplot as plt
plt.imshow([(255, 0, 0)])
plt.show()

The output is:plot output


问题是您正在尝试使用以下命令显示 2D 颜色数组1行和3列。从左到右的像素值分别是255, 0and 0。正如 @Ben K. 在评论中正确指出的那样,通过这样做,强度值将缩放到范围 0..1 并使用当前颜色图显示。这就是为什么您的代码显示一个黄色像素和两个紫色像素。

如果您想指定 RGB 值你应该创建一个 3D 数组 of m rows, n列和3颜色通道(每个 RGB 分量一个彩色通道)。

Demo

下面的代码片段生成调色板索引的随机数组并显示结果:

In [14]: import numpy as np

In [15]: import matplotlib.pyplot as plt

In [16]: from skimage import io

In [17]: palette = np.array([[255,   0,   0], # index 0: red
    ...:                     [  0, 255,   0], # index 1: green
    ...:                     [  0,   0, 255], # index 2: blue
    ...:                     [255, 255, 255], # index 3: white
    ...:                     [  0,   0,   0], # index 4: black
    ...:                     [255, 255,   0], # index 5: yellow
    ...:                     ], dtype=np.uint8)
    ...: 

In [18]: m, n = 4, 6

In [19]: indices = np.random.randint(0, len(palette), size=(4, 6))

In [20]: indices
Out[20]: 
array([[2, 4, 0, 1, 4, 2],
       [1, 1, 5, 5, 2, 0],
       [4, 4, 3, 3, 0, 4],
       [2, 5, 0, 5, 2, 3]])

In [21]: io.imshow(palette[indices])
Out[21]: <matplotlib.image.AxesImage at 0xdbb8ac8>

您还可以生成随机颜色图案而不是使用调色板:

In [24]: random_colors = np.uint8(np.random.randint(0, 255, size=(m, n, 3)))

In [24]: random_colors
Out[27]: 
array([[[137,  40,  84],
        [ 42, 142,  25],
        [ 48, 240,  90],
        [ 22,  27, 205],
        [253, 130,  22],
        [137,  33, 252]],

       [[144,  67, 156],
        [155, 208, 130],
        [187, 243, 200],
        [ 88, 171, 116],
        [ 51,  15, 157],
        [ 39,  64, 235]],

       [[ 76,  56, 135],
        [ 20,  38,  46],
        [216,   4, 102],
        [142,  60, 118],
        [ 93, 222, 117],
        [ 53, 138,  39]],

       [[246,  88,  20],
        [219, 114, 172],
        [208,  76, 247],
        [  1, 163,  65],
        [ 76,  83,   8],
        [191,  46,  53]]], dtype=uint8)

In [26]: io.imshow(random_colors)
Out[26]: <matplotlib.image.AxesImage at 0xe6c6a90>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 imshow 打印一种颜色 [关闭] 的相关文章

随机推荐