Convert matplotlib's show() image into an array

Sometimes, it is necessary to convert the data graph drawn by matplotlib into data for further processing.

There are two methods:

method one:

 It is generally divided into two steps: 1. Convert the plt or fig object to an argb string object; 2. Convert the argb string object image to an array or Image.

import matplotlib.pyplot as plt 
import matplotlib.cm as cm
import numpy as np

from matplotlib.backends.backend_agg import FigureCanvasAgg    
# 引入 Image
import PIL.Image as Image

    # 将plt转化为numpy数据
    canvas = FigureCanvasAgg(plt.gcf())
    print(type(canvas))
    # 绘制图像
    canvas.draw()
    # 获取图像尺寸
    w, h = canvas.get_width_height()
    # 解码string 得到argb图像
    buf = np.fromstring(canvas.tostring_argb(), dtype=np.uint8)

    # 重构成w h 4(argb)图像
    buf.shape = (w, h, 4)
    # 转换为 RGBA
    buf = np.roll(buf, 3, axis=2)
    # 得到 Image RGBA图像对象 (需要Image对象的同学到此为止就可以了)
    image = Image.frombytes("RGBA", (w, h), buf.tostring())
    # 转换为numpy array rgba四通道数组
    image = np.asarray(image)
    # 转换为rgb图像
    rgb_image = image[:, :, :3]

Method Two:

Use the savefig() method of matplotlib to save the picture in the memory first, and then use the PIL or openCV method to read the picture.

import matplotlib.pyplot as plt 
import pylab
import imageio
import skimage.io
import cv2
from io import BytesIO
import PIL    

    #申请缓冲地址
    buffer_ = BytesIO()#using buffer,great way!
    #保存在内存中,而不是在本地磁盘,注意这个默认认为你要保存的就是plt中的内容
    plt.savefig(buffer_,format = 'png')
    buffer_.seek(0)
    #用PIL或CV2从内存中读取
    dataPIL = PIL.Image.open(buffer_)
    #转换为nparrary,PIL转换就非常快了,data即为所需
    data = np.asarray(dataPIL)
    #释放缓存    
    buffer_.close()
    cv2.imshow('image', data)
    cv2.waitKey()

reference:

Python: Convert Matplotlab's figure to numpy's arrary method - Programmer Sought

Python - convert matplotlib image to numpy.array or PIL.Image 

Guess you like

Origin blog.csdn.net/nature1949/article/details/124928719