learning-notes
learning-notes copied to clipboard
如何在使用 matplotlib 显示或保存图像时,只保存图像内容而没有周围的坐标和空白?
例如我们使用下面的代码保存图像:
import numpy as np
import matplotlib.pyplot as plt
a = np.arange(9).reshape(3, 3)
plt.imshow(a)
plt.savefig('orig.png')
这样保存的图像如下图所示:
怎么才能去掉坐标并去除周围的空白区域呢?
搜了很多方法,一些都或多或少地留有空白(空白有可能是透明的),最后使用 @Richard Yu Liu 的方法解决了这个问题,代码如下:
import numpy as np
import matplotlib.pyplot as plt
a = np.arange(9).reshape(3, 3)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
ax.set_frame_on(False)
plt.imshow(a)
plt.savefig('result.png', bbox_inches='tight', pad_inches=0)
采用这种方法保存的图像是只有中间的图像内容的:
参考资料:
哦呦呦 ,真厉害