1. 程式人生 > 其它 >在python中儲存指定大小圖片,去除空白區域

在python中儲存指定大小圖片,去除空白區域

方法一:在plt.savefig()中新增bbox_inches = 'tight'與pad_inches=0

 1 import matplotlib.pyplot as plt
 2 from PIL import Image
 3 import os
 4 
 5 def save_img1(img, img_name):
 6     plt.figure(figsize=(1024, 1024), dpi=1)  # 指定解析度為1024 * 1024
 7     img = Image.open(img)
 8     plt.imshow(img, cmap='gray')
 9     plt.axis('
off') 10 11 # 圖片的路徑 12 result_path = r'./images/' 13 save_img_path = os.path.join(result_path, img_name) 14 plt.savefig(save_img_path, bbox_inches='tight', pad_inches=0) # 儲存影象

存在的問題:指定圖片大小為1024 * 1024,但因為在plt.savefig中使用了bbox_inches='tight'來去除空白區域,使得圖片輸出大小設定失效,實際大小小於1024 * 1024.若選擇不去除空白區域,那麼其大小為1024 * 1024.

注:bbox_inches='tight'實參指定將圖表多餘的空白區域裁減掉

 

方法二:採用plt.gca()以及subplot_adjust + margin(0,0)

 1 import matplotlib.pyplot as plt
 2 from PIL import Image
 3 import os
 4 
 5 def save_img2(img, img_name):
 6 
 7     plt.figure(figsize=(1024, 1024), dpi=1)
 8     img = Image.open(img)
 9     plt.imshow(img, cmap='
gray') 10 11 plt.axis('off') 12 plt.gca().xaxis.set_major_locator(plt.NullLocator()) 13 plt.gca().yaxis.set_major_locator(plt.NullLocator()) 14 plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0) 15 plt.margins(0, 0) 16 17 # 圖片的路徑 18 result_path = r'./images/' 19 save_img_path = os.path.join(result_path, img_name) 20 plt.savefig(save_img_path, format='png', transparent=True, dpi=1, pad_inches=0)

方法二能夠使輸出圖片的大小為1024 * 1024,且去除了空白區域.

 

參考連結:matplotlib 使用 plt.savefig() 輸出圖片去除旁邊的空白區域