This is the 9th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Matplotlib is python’s love-hate library for image processing. Recently encountered the need to obtain PLT Image data, this article documented the method of converting matplotlib images to numpy.array or pil.image.

As we all know, this library will have memory leaks when processing images. I thought I would transfer the PLT image to OpencV and save it, but it didn’t. End of complaints.

A change

The overall goal is divided into two steps:

  • Convert PLT or FIG objects to arGB string objects
  • Convert an arGB String Image to array or Image

Step one

The distinction between PLT and FIG depends on the object type

Convert PLT objects to ARGB String encoded objects

The code builds the image content in the PLT object, generating the PLT image, but without savefig and show:

Such as:

 plt.figure()
 plt.imshow(img)
Copy the code
# introduction FigureCanvasAgg from matplotlib. Backends. Backend_agg import FigureCanvasAgg # is introduced into Image import PIL. # Image as Image Canvas = FigureCanvasAgg(plt.gcf())) # draw the image canvas. Draw () # get the image size w, Buf = np.fromString (Canvas.tostring_arGB (), dtype=np.uint8)Copy the code

Convert FIG objects to ARGB String encoded objects

The FIG object of MatplotLab was taken as the target to obtain arGB string encoded images

FIG. Canvas.draw () Buf = np.fromString (fig.canvas.tostring_arGB (), dtype=np.uint8)Copy the code

Step 2

Convert arGB String encoding object to pil. Image or numpy.array Image

At this time, the ARGB string is not the common uint8 W H RGB image, which needs further transformation

Shape = (w, h, 4) # Convert to RGBA buf = Np. roll(buf, 3) Image = image.frombytes ("RGBA", (w, h), Buf.tostring ()) # convert to numpy array image = np.asarray(image) # convert to RGB image = image[:, :, :3]Copy the code

The resources

  • Blog.csdn.net/aa846555831…
  • Blog.csdn.net/jpc20144055…
  • Blog.csdn.net/aa846555831…
  • Blog.csdn.net/jpc20144055…
  • Blog.csdn.net/guyuealian/…
  • Blog.csdn.net/qq_33883462…