解決plt.savefig()保存到本地的圖片上下左右會有白邊
plt.savefig()保存到本地的圖片上下左右會有白邊
plt.imshow(datalistall[i])
plt.axis('off')
# plt.gca().xaxis.set_major_locator(plt.NullLocator())
# plt.gca().yaxis.set_major_locator(plt.NullLocator())
plt.margins(0, 0)
plt.savefig('自己改一下要保存的地址', bbox_inches='tight', dpi=300, pad_inches=0.0)
plt.show()測試下來,如果僅僅bbox_inches=‘tight’,最后保存的圖片僅僅把白邊變窄了。還要加上pad_inches=0.0。
中間注釋掉的兩句沒有什么影響。
plt.show()一定要寫在plt.savefig后面,不然的話會保存成一片空白。
plt.savefig() 圖片去除旁邊的空白區(qū)域、并且使用CV2讀取和candy 識別
在作圖時需要將輸出的圖片緊密排布,還要去掉坐標軸,同時設(shè)置輸出圖片大小。
但是發(fā)現(xiàn)matplotlib使用plt.savefig()保存的圖片
周圍有一圈空白。那么如何去掉該空白呢?
首先,關(guān)閉坐標軸顯示:
plt.axis('off')但是,這樣只是關(guān)閉顯示而已,透明的坐標軸仍然會占據(jù)左下角位置,導致輸出的圖片偏右。要想完全去掉坐標軸,需要改為以下代碼:
plt.axis('off')
fig = plt.gcf()
fig.set_size_inches(7.0/3,7.0/3) #dpi = 300, output = 700*700 pixels
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)
fig.savefig(out_png_path, format='png', transparent=True, dpi=300, pad_inches = 0)即可完成去掉空白。
注:如果不采用 subplot_adjust + margin(0,0),而是在fig.savefig()的參數(shù)中添加bbox_inches = ‘tight’,也可以達到
去除空白的效果; 但是,這樣會導致對圖片輸出大小的設(shè)置失效。
import h5py
import matplotlib.pyplot as plt
import numpy as np
import cv2
#
train_imgs = h5py.File("./datafuse/test_images.hdf5", 'r')
img = train_imgs['input_DEM'][0][...]
plt.axis('off')
fig = plt.gcf()
fig.set_size_inches(7.0/3,7.0/3)
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)
plt.imshow(img, cmap='gray')
plt.savefig('DEM.png', pad_inches = 0)
plt.show()
img = cv2.imread('DEM.png', 0) ?# 原圖為彩色圖,可將第二個參數(shù)變?yōu)?,為灰度圖
# # plt.imshow(img, cmap='gray')
# plt.show()
edges = cv2.Canny(img, 100, 200)
plt.subplot(121), plt.imshow(img, cmap='gray')
plt.title('raw'), plt.xticks([]), plt.yticks([])
plt.subplot(122), plt.imshow(edges, cmap='gray')
plt.title('Canny detecetion'), plt.xticks([]), plt.yticks([])
plt.show()總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
TensorFlow實現(xiàn)checkpoint文件轉(zhuǎn)換為pb文件
今天小編就為大家分享一篇TensorFlow實現(xiàn)checkpoint文件轉(zhuǎn)換為pb文件,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02
Python實現(xiàn)檢索指定網(wǎng)段內(nèi)所有的數(shù)據(jù)庫服務(wù)器
這篇文章主要為大家詳細介紹了如何使用Python實現(xiàn)檢索指定網(wǎng)段內(nèi)所有的數(shù)據(jù)庫服務(wù)器,文中的示例代碼講解詳細,感興趣的小伙伴可以了解下2025-02-02
深入理解Python?@dataclass的內(nèi)部原理
文章介紹了Python中dataclass的實現(xiàn)原理,通過自定義裝飾器實現(xiàn)了__init__和__repr__方法,并解釋了__annotations__屬性和exec函數(shù)在其中的作用,感興趣的朋友跟隨小編一起看看吧2025-01-01

