python matplotlib图成rgba数组

prl900

我想获得一个matplotlib图作为3维RGBA数组。我正在使用以下代码进行转换:

%matplotlib inline

import matplotlib.pyplot as plt
import numpy as np

canvas = np.zeros((20, 20))

img = plt.imshow(canvas, interpolation='none').make_image()
h, w, d = img.as_rgba_str()
print(h,w)
rgba_array = np.fromstring(d, dtype=np.uint8).reshape(h, w, 4)

plt.imshow(rgba_array)

Out[1]: (249, 373)
<matplotlib.image.AxesImage at 0x111fa8b10>

单元输出

为什么宽高比与原始正方形阵列不同?是否可以指定任何参数或替代方法以将图形的rgba数组保留为其原始形状?

prl900

我发现了一种不使用.imshow()函数并且保留大小比例的替代方法:

%matplotlib inline

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

canvas = np.zeros((20, 20))
img = Image.fromarray(np.uint8(plt.cm.gist_earth(canvas)*255))
rgba_array = np.array(img.getdata(), np.uint8).reshape(img.size[1], img.size[0], 4)
print(rgba_array.shape)

plt.imshow(rgba_array)

Out[1]: (20, 20, 4)
<matplotlib.image.AxesImage at 0x112a71710>

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章