Getting an RGBA array from a matplotlib image

时间秒杀一切 提交于 2019-12-13 03:37:29

问题


I was using imshow to plot an array with a custom colormap and boundarynorm. However, this is going to be an automated script and I want to save the image produced by imshow without the axes. So I wasn't sure imshow was the best way to do this since its going to be running in the background. Is there an alternative where I can just set the colormap and boundarynorm and produce a rgba array that I can give to imsave? Or am I just left with hacking the image that imshow produce and saving that?


回答1:


You can use as_rgba_str to get the image data from the image. Here's an example:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2, 1000)
X, Y = np.meshgrid(x, x)
data = np.sin((X-2)**3 + Y**4)

im = plt.imshow(data)

x = im.make_image()
h, w, d = x.as_rgba_str()
n = np.fromstring(d, dtype=np.uint8).reshape(h, w, 4)

plt.figure()
plt.imshow(n[:,:,0], cmap="gray", origin='lower')

plt.show()

The original image:

The R channel from the RGBA data (note all the blue sections are black since these have no red in them):



来源:https://stackoverflow.com/questions/31393769/getting-an-rgba-array-from-a-matplotlib-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!