【问题标题】:Jupyter shows an image / plot, but saves a blank fileJupyter 显示图像/绘图,但保存一个空白文件
【发布时间】:2022-01-03 09:45:46
【问题描述】:

我正在读取图像并保存它。但是,保存的图像是空白的。我正在运行以下代码来创建情节

# Create plot
path = i[1][0][0]
img = np.array(Image.open(path))
plt.figure()
fig, ax = plt.subplots(1)
ax.imshow(img)

这将创建上述情节。然后我运行以下命令来保存这个图像。在保存之前,我想查看图像。但是,它会生成一个空白图像。可能是什么问题 ? 我正在使用 Jupyter notebook 并且也运行了命令 %matplotlib inline。

# Save generated image with detections
plt.axis("off")
plt.gca().xaxis.set_major_locator(NullLocator())
plt.gca().yaxis.set_major_locator(NullLocator())
filename = os.path.basename(path).split(".")[0]
output_path = os.path.join("output2", filename+".png")
plt.savefig(output_path, bbox_inches="tight", pad_inches=0.0)
plt.show()
plt.close()

这会生成一个空白图像。

【问题讨论】:

    标签: python matplotlib plot jupyter-notebook jupyter-lab


    【解决方案1】:
    • 与绘图相关的所有代码(例如axesfigure)必须在同一个单元格中,而不是多个单元格中。
    • answer 中所示,在新单元格中调用图形对象fig 将显示图像,但这似乎无法使此问题中的代码在第二个单元格中运行。
    • matplotlib.pyplot.imreadmatplotlib.axes.Axes.imshow 用于读取和显示图像。
    import matplotlib.pyplot as plt
    import maptplotlib.ticker as tkr
    
    fig, ax = plt.subplots()
    
    path = 'd:/data/dragon.jpg'
    im = plt.imread(path)
    ax.imshow(im)
    
    ax.axis("off")
    ax.xaxis.set_major_locator(tkr.NullLocator())
    ax.yaxis.set_major_locator(tkr.NullLocator())
    
    fig.savefig('d:/data/test.jpg', bbox_inches="tight", pad_inches=0.0)
    plt.show()
    plt.close()
    
    • Jupyter Lab 中的代码
    • 图像未关闭,因为它是内联(非交互式)绘制的,但它确实保存正确。
      • 在单元格中运行 %matplotlib qt 以切换到交互式 - 全局到笔记本
      • 在单元格中运行 %matplotlib inline 以切换回内联 - 全局到笔记本

    • 用于测试的原始图像

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-25
      • 1970-01-01
      • 2019-06-27
      相关资源
      最近更新 更多