正如标题所述,我正试图将fig
分转换为PIL.Image
分.目前,我可以先将fig
保存到磁盘,然后使用Image.open()
打开该文件,但这个过程比预期的要长,我希望通过跳过本地保存步骤,速度会快一点.
以下是我目前掌握的情况:
# build fig
figsize, dpi = self._calc_fig_size_res(img_height)
fig = plt.Figure(figsize=figsize)
canvas = FigureCanvas(fig)
ax = fig.add_subplot(111)
ax.imshow(torch.from_numpy(S).flip(0), cmap = cmap)
fig.subplots_adjust(left = 0, right = 1, bottom = 0, top = 1)
ax.axis('tight'); ax.axis('off')
# export
fig.savefig(export_path, dpi = dpi)
# open image as PIL object
img = Image.open(export_path)
我在构建fig后try 过这样做(在导出阶段之前):
pil_img = Image.frombytes('RGB', canvas.get_width_height(), canvas.tostring_rgb())
但它并没有显示整个图像.它看起来像是左上角的一个片段,但它可能只是数据的一个奇怪的表示形式——我正在处理 spectral 图,所以图像相当抽象.