matplotlib plt.figure 转 numpy array

思路:利用plt.savefig向BytesIO缓存中保存文件,再用PIL读取缓存中的文件转为numpy

from PIL import Image
from io import BytesIO

img = np.ones((256,256,3), dtype=np.uint8)
plt.figure()
plt.imshow(img, cmap='gray')
buffer = BytesIO()
plt.savefig(buffer, format='png')
new_img = np.asarray(Image.open(buffer)) # new_img就是figure的数组
plt.close()
buffer.close()

猜你喜欢

转载自blog.csdn.net/baoxin1100/article/details/112917517