<分区>
我想使用 RGB 值在屏幕上打印一种颜色,输出应该只是一种颜色。例如,如果我给出红色的 RGB 值,我希望输出显示红色。但是当我尝试这段代码时,它不起作用。我错过了什么?
import matplotlib.pyplot as plt
plt.imshow([(255, 0, 0)])
plt.show()
<分区>
我想使用 RGB 值在屏幕上打印一种颜色,输出应该只是一种颜色。例如,如果我给出红色的 RGB 值,我希望输出显示红色。但是当我尝试这段代码时,它不起作用。我错过了什么?
import matplotlib.pyplot as plt
plt.imshow([(255, 0, 0)])
plt.show()
最佳答案
问题是您正在尝试显示具有 1
行和 3
列的二维颜色数组。从左到右的像素值分别是255
、0
和0
。正如@Ben K. 在评论中正确指出的那样,这样做可以将强度值缩放到 0..1 范围内并使用当前颜色图显示。这就是您的代码显示一个黄色像素和两个紫色像素的原因。
如果您希望指定 RGB 值,您应该创建一个 3D 数组,包含 m
行、n
列和 3
颜色 channel (每个 RGB 分量一个色 channel )。
下面的代码片段生成一个随机的调色板索引数组并显示结果:
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>
关于python - 使用 imshow 打印一种颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44497352/