1. # https://blog.csdn.net/qq_33883462/article/details/81050795
    2. from PIL import Image
    3. import numpy as np
    4. import matplotlib.pyplot as plt
    5. import cv2
    6. from io import StringIO
    7. import PIL.Image as pimg
    8. def fig2data (fig):
    9. """
    10. 把 plt.figure 保存为 numpy 文件。
    11. @brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it
    12. @param fig a matplotlib figure
    13. @return a numpy 3D array of RGBA values
    14. """
    15. # draw the renderer
    16. fig.canvas.draw ( )
    17. # Get the RGBA buffer from the figure
    18. w,h = fig.canvas.get_width_height()
    19. buf = np.fromstring ( fig.canvas.tostring_argb(), dtype=np.uint8 )
    20. buf.shape = ( w, h,4 )
    21. # canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
    22. buf = np.roll ( buf, 3, axis = 2 )
    23. return buf
    24. def fig2img(fig):
    25. """
    26. 把 plt.figure 保存为 PIL.Image 文件
    27. @brief Convert a Matplotlib figure to a PIL Image in RGBA format and return it
    28. @param fig a matplotlib figure
    29. @return a Python Imaging Library ( PIL ) image
    30. """
    31. # put the figure pixmap into a numpy array
    32. buf = fig2data (fig)
    33. # print("buf")
    34. # print(type(buf))
    35. # print(buf.shape)
    36. w, h, d = buf.shape
    37. return Image.frombytes("RGBA", (w,h), buf.tostring())
    38. # fig = plt.figure(figsize=(2,2), dpi=128)
    39. fig = plt.figure(figsize=(4,4), dpi=64)
    40. npy_path = '/data1/huangyongye/github/sbir/data/sketchy_coord_original/airplane/n02691156_10151-1.npy'
    41. coord = np.load(npy_path)
    42. # 根据最后的一位划分笔画
    43. cut_ids = filter(lambda i: coord[:, -1][i] == 1, range(len(coord)))
    44. left = 0
    45. right = 0
    46. count = 0
    47. for right in cut_ids:
    48. x = coord[left:right+1, 0]
    49. y = 800 - coord[left:right+1, 1]
    50. plt.plot(x, y, 'k-', label=str(count))
    51. plt.axis("off")
    52. left = right + 1
    53. count += 1
    54. # 把 plt 的输出结果转为 numpy 格式
    55. img_arr = fig2data(fig)
    56. print(img_arr.shape)
    57. # 把 plt 的输出结果转为 PIL.Image 格式
    58. img = fig2img(fig)
    59. print(type(img))
    60. img