简体   繁体   English

将numpy数组转换为RGB图像数组

[英]Transform numpy array to RGB image array

Consider the following code: 考虑以下代码:

import numpy as np
rand_matrix = np.random.rand(10,10)

which generates a 10x10 random matrix. 生成10x10随机矩阵。

Following code to display as colour map: 以下代码显示为颜色图:

import matplotlib.pyplot as plt
plt.imshow(rand_matrix)
plt.show()

I would like to get the RGB numpy array (no axis) from the object obtained from plt.imshow 我想从从plt.imshow获得的对象获取RGB numpy数组(无轴)

In other words, if I save the image generated from plt.show, I would like to get the 3D RGB numpy array obtained from: 换句话说,如果保存从plt.show生成的图像,我想从以下位置获取3D RGB numpy数组:

import matplotlib.image as mpimg
img=mpimg.imread('rand_matrix.png')

But without the need to save and load the image, which is computationally very expensive. 但是无需保存和加载图像,这在计算上非常昂贵。

Thank you. 谢谢。

You can save time by saving to a io.BytesIO instead of to a file: 您可以通过保存到io.BytesIO而不是文件来节省时间:

import io
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from PIL import Image

def ax_to_array(ax, **kwargs):
    fig = ax.figure
    frameon = ax.get_frame_on()
    ax.set_frame_on(False)
    with io.BytesIO() as memf:
        extent = ax.get_window_extent()
        extent = extent.transformed(fig.dpi_scale_trans.inverted())
        plt.axis('off')
        fig.savefig(memf, format='PNG', bbox_inches=extent, **kwargs)
        memf.seek(0)
        arr = mpimg.imread(memf)[::-1,...]
    ax.set_frame_on(frameon) 
    return arr.copy()

rand_matrix = np.random.rand(10,10)
fig, ax = plt.subplots()
ax.imshow(rand_matrix)
result = ax_to_array(ax)
# view using matplotlib
plt.show()
# view using PIL
result = (result * 255).astype('uint8')
img = Image.fromarray(result)
img.show()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM