2011-11-21 23 views
39

在numpy/scipy我有一個圖像存儲在一個數組。我可以顯示它,我想要使用savefig而不是保存任何邊界,座標軸,標籤,標題,...只是純粹的圖像,沒有別的。scipy:savefig沒有框架,座標軸,只有內容

我想避免像PyPNGscipy.misc.imsave包,他們有時也會出現問題(它們並不總是安裝好了,只爲了我

回答

56

基本savefig()假設:

import matplotlib.pyplot as plt 

爲了使圖無框架:

fig = plt.figure(frameon=False) 
fig.set_size_inches(w,h) 

爲了使c ontent補全數字

ax = plt.Axes(fig, [0., 0., 1., 1.]) 
ax.set_axis_off() 
fig.add_axes(ax) 

然後畫上自己的倒影:

ax.imshow(your_image, aspect='normal') 
fig.savefig(fname, dpi) 

aspect參數更改像素大小,以確保他們填寫fig.set_size_inches(…)指定的數字大小。爲了體驗如何玩這類遊戲,請閱讀matplotlib's documentation,特別是關於軸心,軸心和藝術家的主題。

+3

沒了,我還是有一些小的透明邊框,和我要的是在ALL_ _No邊境,清純的形象 –

+0

也許,那是因爲我忘了在圖像不是方形的情況:P。剛編輯添加'aspect'參數。現在怎麼樣? – matehat

+1

grrr,不,還是一樣的。圖像周圍有一個小而透明的邊框,每個邊上幾個像素差不多就是 –

19

你可以找到圖像的軸內(使用get_window_extent)的BBOX,並使用bbox_inches參數保存圖像的那部分:

import numpy as np 
import matplotlib.pyplot as plt 

data=np.arange(9).reshape((3,3)) 
fig=plt.figure() 
ax=fig.add_subplot(1,1,1) 
plt.axis('off') 
plt.imshow(data) 

extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) 
plt.savefig('/tmp/test.png', bbox_inches=extent) 

我從喬金頓here學會了這招。

+0

只是'plt.axis('off')'幫助。其他答案沒有太大的幫助。 – imsrgadich

39

更簡單的解決方案似乎是:

fig.savefig('out.png', bbox_inches='tight', pad_inches=0) 
+1

這對我來說很好。此外,pad_inches可以很容易地更改爲所需的大小。謝謝! – Curious2learn

+0

+1對我很好:) 這實際上比接受的答案簡單 –

+8

我仍然有這個白色邊距。 –

4

我在我的情況下,嘗試了幾種選項,最好的解決辦法是這樣的:

fig.subplots_adjust(bottom = 0) 
fig.subplots_adjust(top = 1) 
fig.subplots_adjust(right = 1) 
fig.subplots_adjust(left = 0) 

然後保存你的身材與savefig

4

我會建議heron13的答案,以及從here借用的輕微添加,以便在將bbox設置爲緊密模式後刪除填充,因此:

fig.axes.get_xaxis().set_visible(False) 
fig.axes.get_yaxis().set_visible(False) 
fig.savefig('out.png', bbox_inches='tight', pad_inches=0) 
+0

我得到一個錯誤,說get_xaxis()和get_yaxis()不存在。任何想法爲什麼會發生? –

+0

做一個軸()對象,然後使用ax.xaxis和ax.yaxis – perigon

3

我同時使用librosa,我想提取的情節內容,沒有任何其他信息,做一些可視化有同樣的問題。所以這是我的方法。 unutbu的答案也有助於我工作。

figure = plt.figure(figsize=(500, 600), dpi=1) 
    axis = plt.subplot(1, 1, 1) 
    plt.axis('off') 
    plt.tick_params(axis='both', left='off', top='off', right='off', bottom='off', labelleft='off', labeltop='off', 
        labelright='off', labelbottom='off') 

    # your code goes here. e.g: I used librosa function to draw a image 
    result = np.array(clip.feature_list['fft'].get_logamplitude()[0:2]) 
    librosa.display.specshow(result, sr=api.Clip.RATE, x_axis='time', y_axis='mel', cmap='RdBu_r') 


    extent = axis.get_window_extent().transformed(figure.dpi_scale_trans.inverted()) 
    plt.savefig((clip.filename + str("_.jpg")), format='jpg', bbox_inches=extent, pad_inches=0) 
    plt.close() 
+0

這讓我在正確的軌道上,但我有兩個問題:1)我不得不把DPI設置爲一個數字大於1,以避免字體我的jupyter筆記本錯誤;和2)還是會有小邊界,所以我必須手動改變程度B-盒到'extent.get_points()* np.array([[1.1],[9]])'。 –

+0

感謝滿足可能有助於其他人的答案。 – GPrathap