# 加載相關庫及圖檔
from google.colab import drive
import matplotlib.pyplot as plt
import numpy as np
drive.mount('/content/drive')
from glob import glob
mask_pth=glob('/content/drive/My Drive/Colab Notebooks/data_nifti/rgb_B2_patch02/PNG/'+'*.png')[3]
## plt儲存去除白邊 并且按照pixel*pixel格式輸出 (figsize和dpi共同控制)
# fig = plt.gcf()
# fig.set_size_inches(16,16) #dpi = 100, output = 1600*1600 pixels inch (width,height)=(16,16)
plt.figure(figsize=(16,16),dpi=100)
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
plt.margins(0,0)
mask_ins=plt.imread(mask_pth)
plt.imshow(mask_ins)
plt.savefig('/content/example.png',pad_inches=0) # dpi=100 和上文相對應 pixel尺寸/dpi=inch尺寸
plt.show() # 此處順序不能弄反 imshow(),savefig(),show()
#plt.clf() #plt.clf()的作用:用于批量存儲圖檔時 每一次顯示圖檔并儲存以後,釋放圖窗,接受下一個圖檔顯示和存儲
此段代碼的主要作用:
1)消除plt圖檔儲存時的白邊
2)按照像素尺寸和dpi分辨率要求,儲存圖檔
最終圖檔效果:
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5iZzIGN5IDOjVWY5UWMzImYxUTO1IjZlRWM1MWN1QDZ18CX0JXZ252bj91Ztl2Lc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)