matplotlib. pyplot drawing image binary stream acquisition method

  • 2020-09-16 07:32:58
  • OfStack

Sometimes, we need to draw the base 2 data stream, matplotlib does not provide the relevant api, through the source code view and Baidu, get the following method


import matplotlib.pyplot as plt
import numpy as np
import io
x=np.arange(10)
y=x
#plt.plot(x,y)
#canvas = plt.get_current_fig_manager().canvas
#canvas.draw()
fig=plt.figure()
plt.plot(x,y)
canvas=fig.canvas
# The code above and the effect of the code commented out above 1 sample 

# methods 1
buffer = io.BytesIO()
canvas.print_png(buffer)
data=buffer.getvalue()
buffer.close()
# methods 2
buf, size = canvas.print_to_buffer()
image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1)
buffer=io.BytesIO()
image.save(buffer,'PNG')
data=buffer.getvalue()
buffer.close()

with open('hhh.png',mode='wb') as f:
f.write(data)
#f=open('hh.png',mode='wb')
#f.write(data)
#f.close()

If we want to convert a base 2 image into an array,


buffer=io.BytesIO()
buffer.write(data)
img=Image.open(buffer)
img = np.asarray(img)

Related articles: