matplotlib绘制图像转换为array

需求:有的时候,后台程序需要通过matplotlib绘制图像,再在前端页面显示。这时需要将绘制图像的array形式传给前端。matplotlib是无法直接将图像转换为array,如果将图像先保存在本地磁盘,在读取会导致速度较慢,可以先将图像数据保存在内存中,然后直接从内存读取

#写入内存
nx.draw(G,pos=pos,with_labels=True)
buffer_ = io.BytesIO()
plt.savefig(buffer_,format = 'png')

#从内存读取,转换为array,通过opencv显示
dataPIL = PIL.Image.open(buffer_)
# 或者直接读取二进制,转换base64
base64_png = base64.b64encode(buffer_.getvalue())
data = np.asarray(dataPIL)
cv2.imshow('image', data)
cv2.waitKey(0)
#释放缓存
plt.close()
buffer_.close()

你可能感兴趣的:(复杂网络分析,matplotlib,python,开发语言)