欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

解決plt.savefig()保存到本地的圖片上下左右會有白邊

 更新時(shí)間:2023年09月14日 15:49:10   作者:qy_w  
這篇文章主要介紹了解決plt.savefig()保存到本地的圖片上下左右會有白邊的問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

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í)需要將輸出的圖片緊密排布,還要去掉坐標(biāo)軸,同時(shí)設(shè)置輸出圖片大小。

但是發(fā)現(xiàn)matplotlib使用plt.savefig()保存的圖片

周圍有一圈空白。那么如何去掉該空白呢?

首先,關(guān)閉坐標(biāo)軸顯示:

plt.axis('off')

但是,這樣只是關(guān)閉顯示而已,透明的坐標(biāo)軸仍然會占據(jù)左下角位置,導(dǎo)致輸出的圖片偏右。要想完全去掉坐標(biāo)軸,需要改為以下代碼:

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’,也可以達(dá)到

去除空白的效果; 但是,這樣會導(dǎo)致對圖片輸出大小的設(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) ?# 原圖為彩色圖,可將第二個(gè)參數(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é)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論