方法一:在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() 输出图片去除旁边的空白区域