在Python中显示RGB矩阵图像

4 投票
2 回答
39755 浏览
提问于 2025-04-18 00:47

我有一个像这样的RGB矩阵:

image=[[(12,14,15),(23,45,56),(,45,56,78),(93,45,67)],
       [(r,g,b),(r,g,b),(r,g,b),(r,g,b)],
       [(r,g,b),(r,g,b),(r,g,b),(r,g,b)],
       ..........,
       [()()()()]
      ]

我想显示一个包含这个矩阵的图像。

我用这个函数来显示灰度图像:

def displayImage(image):
    displayList=numpy.array(image).T
    im1 = Image.fromarray(displayList)
    im1.show()

参数(image)里有这个矩阵

有没有人能帮我怎么显示这个RGB矩阵?

2 个回答

4

Matplotlib自带的一个函数叫做imshow,可以帮助你实现这个功能。

import matplotlib.pyplot as plt
def displayImage(image):
    plt.imshow(image)
    plt.show()
9

imshow 是 matplotlib 库中的一个函数,可以用来显示图像。

关键是你的 NumPy 数组需要有正确的形状:

高度 x 宽度 x 3

(如果是 RGBA 格式的话,则是高度 x 宽度 x 4)

>>> import os
>>> # fetching a random png image from my home directory, which has size 258 x 384
>>> img_file = os.path.expanduser("test-1.png")

>>> from scipy import misc
>>> # read this image in as a NumPy array, using imread from scipy.misc
>>> M = misc.imread(img_file)

>>> M.shape       # imread imports as RGBA, so the last dimension is the alpha channel
    array([258, 384, 4])

>>> # now display the image from the raw NumPy array:
>>> from matplotlib import pyplot as PLT

>>> PLT.imshow(M)
>>> PLT.show()

撰写回答