current position:Home>Python - convert Matplotlib image to numpy Array or PIL Image

Python - convert Matplotlib image to numpy Array or PIL Image

2022-01-31 07:37:28 Why

This is my participation 11 The fourth of the yuegengwen challenge 9 God , Check out the activity details :2021 One last more challenge

matplotlib yes python A library that people love and hate in image processing . Recently encountered the need to obtain plt Demand for image data , This paper records that matplotlib Image to numpy.array or PIL.Image Methods .

as everyone knows , This library will cause memory leakage when processing images , I thought I would plt Turn the picture out and use opencv Just save it , But there is no , The complaint is over .

Change your mind

The overall goal is divided into two steps :

  • take plt or fig Object to argb string The object of
  • take argb string The object image is converted to array or Image

Step one

Distinguish objects as plt and fig The situation of , Which one to use depends on the object type

transformation plt The object is argb string Coding object

Code in plt Object to build the image content , Generated plt Images , But not yet. savefig and show:

for example :

 plt.figure()
 plt.imshow(img)
 Copy code 
 #  introduce  FigureCanvasAgg
 from matplotlib.backends.backend_agg import FigureCanvasAgg
 #  introduce  Image
 import PIL.Image as Image
 #  take plt Turn into numpy data 
 canvas = FigureCanvasAgg(plt.gcf())
 #  The plot 
 canvas.draw()
 #  Get image size 
 w, h = canvas.get_width_height()
 #  decode string  obtain argb Images 
 buf = np.fromstring(canvas.tostring_argb(), dtype=np.uint8)
 Copy code 

transformation fig The object is argb string Coding object

With matplotlab Of fig Object as the target , obtain argb string Encoding images

 #  introduce  Image
 import PIL.Image as Image
 #  The plot 
 fig.canvas.draw()
 #  Get image size 
 w, h = fig.canvas.get_width_height()
 #  obtain  argb  Images 
 buf = np.fromstring(fig.canvas.tostring_argb(), dtype=np.uint8)
 Copy code 

Step two

transformation argb string Coding object is PIL.Image or numpy.array Images

At this time argb string It's not common for us uint8 w h rgb Image , Further transformation is needed

 #  Reconstitute w h 4(argb) Images 
 buf.shape = (w, h, 4)
 #  Convert to  RGBA
 buf = np.roll(buf, 3, axis=2)
 #  obtain  Image RGBA Image object  ( need Image That's enough for the students of the object )
 image = Image.frombytes("RGBA", (w, h), buf.tostring())
 #  Convert to numpy array rgba Four channel array 
 image = np.asarray(image)
 #  Convert to rgb Images 
 rgb_image = image[:, :, :3]
 Copy code 

Reference material

copyright notice
author[Why],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201310737256181.html

Random recommended