首页 > 解决方案 > 从 rgb 数组创建 matplotlib 图

问题描述

我有一个 png 图像,我想将其制作成 matplotlib 图。我可以通过执行以下操作将 png 图像转换为 matplotlib.image.AxesImage 对象(尽管可能有更好的方法):

import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

def rgba2rgb(rgba, background=(255,255,255)):
    row, col, ch = rgba.shape

    if ch == 3:
        return rgba

    assert ch == 4, 'RGBA image has 4 channels.'

    rgb = np.zeros( (row, col, 3), dtype='float32' )
    r, g, b, a = rgba[:,:,0], rgba[:,:,1], rgba[:,:,2], rgba[:,:,3]

    a = np.asarray( a, dtype='float32' )/255

    R, G, B = background

    rgb[:,:,0] = r * a + (1.0 - a) * R
    rgb[:,:,1] = g * a + (1.0 - a) * G
    rgb[:,:,2] = b * a + (1.0 - a) * B

    return np.asarray( rgb, dtype='uint8' )

img = Image.open('image.png')
rgba_arr = np.array(img)
rgb_array = rgba2rgb(rgba_arr)
plt_img = plt.imshow(rgb_array, aspect='auto')

同样,我遇到的主要问题是 plt.imshow 的结果是 matplotlib.image.AxesImage 而不是 matplotlib 图。我怎样才能使这个数字?谢谢。

标签: imagematplotlib

解决方案


推荐阅读