簡體   English   中英

matplotlib.pyplot:在保存圖像時刪除空白並保持相同大小

[英]matplotlib.pyplot: remove white space and keep same size while saving the image

我知道有些人以前曾問過這個問題,但是他們提供的解決方案似乎無法奏效。 我只提供以下鏈接,也許它們對您有所幫助。

Matplotlib圖:刪除軸,圖例和空白

如何設置matplotlib圖形的邊距?

如問題標題中所述,我使用以下代碼來處理此問題。

plt.imshow(img)
plt.axis('off')
plt.savefig('seg_missi5.png', bbox_inches='tight')
plt.show()

我想要保存的圖像沒有空白,並且尺寸與原始圖像相同。

我試過使用print img.shape來查看img的大小,它顯示(342, 548, 3) print img.shape (342, 548, 3) ,與原始圖像相同,但是保存的圖像卻沒有。 如果尺寸為438 x 675 ,則更大,並帶有空白。

您可以嘗試使用pad_inches=0

plt.savefig('seg_missi5.png', bbox_inches='tight', pad_inches=0) 

默認大小為0.1。 您可以從http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.savefig獲取更多信息

可以說,matplotlib可能不是實現這一目標的最佳工具(盡管肯定有可能)。 我建議使用Python圖像庫作為替代。 使用此庫,您可以像這樣保存圖像:

from PIL import Image

im = Image.fromarray(np.uint8(img))
im.save('outfile.png', "PNG")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM