2014-03-13 28 views
0

經過大約4周的學習,試驗等後,我終於有了一個腳本,可以做我想做的事情。它根據我創建的特定投影矩陣改變圖像的視角。當我爲一個圖像運行腳本時,它工作正常,但是我想在一個圖中繪製六個圖像。當我嘗試這樣做時,出現內存錯誤。python內存密集型腳本

所有圖像的寬度爲2448px,高度爲2048px。我的腳本:

files = {'cam1': 'c1.jpg', 
     'cam2': 'c2.jpg', 
     'cam3': 'c3.jpg', 
     'cam4': 'c4.jpg', 
     'cam5': 'c5.jpg', 
     'cam6': 'c6.jpg'} 

fig, ax = plt.subplots() 

for camname in files: 
    img = Image.open(files[camname]) 
    gray_img = np.asarray(img.convert("L")) 
    img = np.asarray(img) 
    height, width, channels = img.shape 

    usedP = np.array(P[camname][:,[0,1,3]]) 
    usedPinv = np.linalg.inv(usedP) 
    U, V = np.meshgrid(range(gray_img.shape[1]), 
         range(gray_img.shape[0])) 
    UV = np.vstack((U.flatten(), 
        V.flatten())).T 
    ones = np.ones((UV.shape[0],1)) 
    UV = np.hstack((UV, ones)) 

    # create UV_warped 
    UV_warped = usedPinv.dot(UV.T).T 

    # normalize vector by dividing by the third column (which should be 1) 
    normalize_vector = UV_warped[:,2].T 
    UV_warped = UV_warped/normalize_vector[:,None] 

    # masks 
    # pixels that are above the horizon and where the V-projection is therefor positive (X in argus): make 0, 0, 1 
    # pixels that are to far: make 0,0,1 
    masks = [UV_warped[:,0]<=0, UV_warped[:,0]>2000, UV_warped[:,1]>5000, UV_warped[:,1]<-5000] # above horizon: => [0,0,1] 
    total_mask = masks[0] | masks[1] | masks[2] | masks[3] 
    UV_warped[total_mask] = np.array([[0.0, 0.0, 1.0]]) 

    # show plot 
    X_warped = UV_warped[:,0].reshape((height, width)) 
    Y_warped = UV_warped[:,1].reshape((height, width)) 
    gray_img = gray_img[:-1, :-1] 

    # add colors 
    rgb = img[:,:-1,:].reshape((-1,3))/255.0 # we have 1 less faces than grid cells 
    rgba = np.concatenate((rgb, np.ones((rgb.shape[0],1))), axis=1) 

    plotimg = ax.pcolormesh(X_warped, Y_warped, img.mean(-1)[:,:], cmap='Greys') 
    plotimg.set_array(None) 
    plotimg.set_edgecolor('none') 
    plotimg.set_facecolor(rgba) 

ax.set_aspect('equal') 
plt.show() 

我有一種感覺,numpy.meshgrid相當內存密集型的,但我不知道。有人看到我的記憶快速消失嗎? (順便說一句,我有一臺筆記本電腦,內存爲12Gb,只有其他程序可以使用這種筆記本電腦的一小部分)

+0

作爲一個整體,尤其是在內存密集型應用程序中,Python比編譯語言如C/C++慢得多。像Python這樣的解釋性語言在內存管理上效率不高。 – Signus

+0

你說得對。但是,在這個時候,改用C/C++並不是一種選擇。 – Yorian

回答

2

您可能想用this library來分析您的代碼。

它會告訴你你的腳本在哪裏使用內存。

+0

感謝您的回覆,但是,當涉及到使用命令提示符時,我不是一個英雄......我嘗試了但我還沒有正常工作 – Yorian

+0

不要放棄! :) – Germano

+0

感謝您的回覆,我想我發現了這個問題。該腳本使用似乎使用大量內存的float64類型加載圖像。 – Yorian

1

我通常使用profilecProfile模塊進行配置,因爲它使測試各個代碼段相當容易。

Python Profilers

2

有一個問題#1約here內存分析器。此外,我在過去一直使用this answer中的技巧作爲一種快速的方式來獲得代碼內存失控的想法。我只是將resource.getrusage()結果全部打印出來。它並不乾淨,並不總是有效,但它是標準庫的一部分,而且很容易實現。