Matplotlib 奇怪地显示 RGB 像素

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

我有一组从图像中收集的 RGB 像素,但是当我尝试保存并显示它们时,它们以 3 种不同的颜色出现非常奇怪。似乎它没有将我的数组读取为 RGB 值列表。

我有一个简化版的代码,其中包含一个简短的 RGB 值列表:

import matplotlib.pyplot as plt
import numpy as np

img = np.array([[255, 255, 255], [127, 255, 127], [239, 255,  15], [127 ,  0,   0]])

plt.imshow(img)
plt.savefig('testtt.png', dpi=400)

这给了我这个: enter image description here

有谁知道如何解决这个问题或者可能出了什么问题?或者,如果有人知道从数组中显示 RGB 像素的更好方法,请告诉我。旁注:我试图避免使用 OpenCV

python numpy matplotlib pixel rgb
2个回答
0
投票

二维数组将被解释为要进行颜色映射的值。这就是为什么你看到 4 行 3 种颜色。

要将数组解释为 4 个 rgb 值,您可以绘制一个 3D 数组:

import matplotlib.pyplot as plt
import numpy as np

img = np.array([[255, 255, 255], [127, 255, 127], [239, 255, 15], [127, 0, 0]])
plt.imshow([img]) # note the extra brackets
plt.show()

为了说明原始情节发生了什么,seaborn 的热图可以自动添加一些注释和颜色条。

import seaborn as sns

sns.heatmap(img, annot=True, fmt='d', cmap='viridis')
plt.imshow([img])

PS:要将 RGB 值显示为

NxM
像素数组,这些值应形成 3D
NxMx3
数组:

img = np.array([[[255, 255, 255], [127, 255, 127]], [[239, 255, 15], [127, 0, 0]]])
plt.imshow(img)


0
投票

所以,你创建了一个列表数组

img = np.array([[255, 255, 255],[127, 255, 127],[239, 255,  15],[127 ,  0,   0]])

但是没有告诉 python 将其视为 RGB 图像,因此它创建了一个四行三列的数组。然后当你在这里绘制它时:

plt.imshow(img)

它简单地应用了 viridis 颜色托盘中的颜色,并将其显示为视觉数组,其中每个值都从该托盘中获得一种颜色。

如评论中所述,您需要明确告诉python将此数组视为图像:

imshow(img, origin='upper', interpolation='nearest')

对于直接逐像素平移

© www.soinside.com 2019 - 2024. All rights reserved.