# https://blog.csdn.net/qq_33883462/article/details/81050795from PIL import Imageimport numpy as np import matplotlib.pyplot as plt import cv2from io import StringIOimport PIL.Image as pimgdef fig2data (fig): """ 把 plt.figure 保存为 numpy 文件。 @brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it @param fig a matplotlib figure @return a numpy 3D array of RGBA values """ # draw the renderer fig.canvas.draw ( ) # Get the RGBA buffer from the figure w,h = fig.canvas.get_width_height() buf = np.fromstring ( fig.canvas.tostring_argb(), dtype=np.uint8 ) buf.shape = ( w, h,4 ) # canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode buf = np.roll ( buf, 3, axis = 2 ) return bufdef fig2img(fig): """ 把 plt.figure 保存为 PIL.Image 文件 @brief Convert a Matplotlib figure to a PIL Image in RGBA format and return it @param fig a matplotlib figure @return a Python Imaging Library ( PIL ) image """ # put the figure pixmap into a numpy array buf = fig2data (fig)# print("buf")# print(type(buf))# print(buf.shape) w, h, d = buf.shape return Image.frombytes("RGBA", (w,h), buf.tostring())# fig = plt.figure(figsize=(2,2), dpi=128)fig = plt.figure(figsize=(4,4), dpi=64)npy_path = '/data1/huangyongye/github/sbir/data/sketchy_coord_original/airplane/n02691156_10151-1.npy'coord = np.load(npy_path)# 根据最后的一位划分笔画cut_ids = filter(lambda i: coord[:, -1][i] == 1, range(len(coord)))left = 0right = 0count = 0for right in cut_ids: x = coord[left:right+1, 0] y = 800 - coord[left:right+1, 1] plt.plot(x, y, 'k-', label=str(count)) plt.axis("off") left = right + 1 count += 1# 把 plt 的输出结果转为 numpy 格式img_arr = fig2data(fig)print(img_arr.shape)# 把 plt 的输出结果转为 PIL.Image 格式img = fig2img(fig)print(type(img))img