2013-02-28 105 views
1

我試着優化下面的代碼,但我無法弄清楚如何提高計算速度。我試過Cthon,但性能就像在Python中。Python,如何優化此代碼

是否有可能在不重寫C/C++中的所有內容的情況下提高性能?

感謝所有幫助

import numpy as np 

heightSequence = 400 
widthSequence = 400 
nHeights = 80 

DOF = np.zeros((heightSequence, widthSequence), dtype = np.float64) 
contrast = np.float64(np.random.rand(heightSequence, widthSequence, nHeights)) 

initDOF = np.zeros([heightSequence, widthSequence], dtype = np.float64) 
initContrast = np.zeros([heightSequence, widthSequence, nHeights], dtype = np.float64) 
initHeight = np.float64(np.r_[0:nHeights:1.0]) 
initPixelContrast = np.array(([0 for ii in range(nHeights)]), dtype = np.float64) 


# for each row 
for row in range(heightSequence): 
    # for each col 
    for col in range(widthSequence): 

     # initialize variables    
     height = initHeight # array ndim = 1 
     c = initPixelContrast # array ndim = 1 

     # for each height    
     for indexHeight in range(0, nHeights): 
      # get contrast profile for current pixel 
      tempC = contrast[:, :, indexHeight] 
      c[indexHeight] = tempC[row, col] 

     # save original contrast    
     # originalC = c 
     # originalHeight = height     

     # remove profile before maximum and after minumum contrast 
     idxMaxContrast = np.argmax(c) 
     c = c[idxMaxContrast:] 
     height = height[idxMaxContrast:] 

     idxMinContrast = np.argmin(c) + 1 
     c = c[0:idxMinContrast] 
     height = height[0:idxMinContrast]    

     # remove some refraction 
     if (len(c) <= 1) | (np.max(c) <= 0): 
      DOF[row, col] = 0     

     else: 

      # linear fitting of profile contrast            
      P = np.polyfit(height, c, 1) 
      m = P[0] 
      q = P[1] 

      # remove some refraction    
      if m >= 0: 
       DOF[row, col] = 0 

      else: 
       DOF[row, col] = -q/m 

    print 'row=%i/%i' %(row, heightSequence) 

# set range of DOF 
DOF[DOF < 0] = 0 
DOF[DOF > nHeights] = 0 
+2

什麼數據?你可以添加一些供參考,以便這段代碼自行運行嗎?例如,您可以用'np.random.rand'生成一些正確形狀的數組。 – YXD 2013-02-28 11:32:53

+5

如果你**不需要**需要C或C++建議,那麼不要添加這樣的標籤。 – 2013-02-28 11:33:39

+0

數據是一堆80個圖像...我將更新代碼以單獨運行,但我需要一些時間來測試一切是否正常xD這只是我整個算法的一小部分,哪裏是瓶頸 – opensw 2013-02-28 11:46:32

回答

4

通過觀察,似乎可以完全擺脫兩個外循環,代碼轉換爲代碼矢量化形式。但是,np.polyfit調用必須由其他表達式替換,但線性擬合的係數很容易找到,也是以矢量化的形式。最後的if-else然後可以變成np.where呼叫。

+0

感謝您的提示,我會盡量遵循您的建議...但我是相當新的python,無論如何,我會試試:) – opensw 2013-02-28 14:01:54

+1

這是同樣的建議,適用於例如使用Matlab:試圖擺脫循環(至少大部分時間) – 2013-02-28 14:04:23

+0

好吧,我完成了關於polyfit算法的部分(我實現了這些公式http://www.codecogs.com/code/maths/approximation python中的/regression/linear.php以非常有效的方式沒有「for row」和「for col」循環)。我最後的問題是用argmax(c)和argmin(c)優化語句。你有一個想法如何在循環之外做這個計算嗎? – opensw 2013-02-28 21:58:43