2015-05-18 61 views
0

我已經在python中創建了一個能量函數,我正將它應用於一個png圖像。但是,輸入參數時,我沒有收到返回的能量值。任何人都可以看到這是爲什麼?謝謝!能量函數不返回值

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.image as mpimg 

img=mpimg.imread('Image.png') 
#plt.imshow(img) 
#plt.show() 

im=np.array(img 


def E_generator(beta, eta, h): 
    """Generate energy function E and localized version of E. 
     E = h * \sum{x_i} - beta * \sum{x_i x_j} - eta * \sum{x_i y_i} 
    """ 
    def E(x, y): 
     """Calculate energy for matrices x, y. 
     """ 
     # sum of products of neighboring paris {xi, yi} 
     xxm = np.zeros_like(x) 
     xxm[:-1, :] = x[1:, :] # down 
     xxm[1:, :] += x[:-1, :] # up 
     xxm[:, :-1] += x[:, 1:] # right 
     xxm[:, 1:] += x[:, :-1] # left 
     xx = np.sum(xxm * x) 
     xy = np.sum(x * y) 
     xsum = np.sum(x) 
     return h * xsum - beta * xx - eta * xy 

    return E 

y = np.array(img) 
x = np.array(y) 

E_generator(0,1,1) 

與然後輸出返回: 「.E>」

+2

'E_generator'返回'E'函數。誰叫'E'? – Pynchia

+0

它出來與「E ---功能---等」只是堆棧wouldnt讓我打印整個聲明 – user4476006

回答

2

你的函數E_generator返回一個函數(E);爲了得到你的結果你需要調用這個函數,所以你可以這樣做:

print E_generator(0,1,1)(x, y) 
+0

謝謝!這返回了0的結果,這不是我正在尋找的值...我的圖像陣列出來作爲 '(300,300,3)'我想重塑它只有300x300。我嘗試過'np.reshape(im,300)',但它表示總數組大小必須保持不變。你有什麼建議嗎? – user4476006

+0

假設最後一個尺寸是rgb,你可以沿該軸取平均值img.mean(axis = 2)如果你想要一個'正確'的意思,那麼你將不得不(img [:,:,0] ** 2 + img [:,:,1] ** 2 + img [:,:,2] ** 2)「」0.5如果您不想以某種方式合併顏色,則需要解釋如何縮小你的圖像的尺寸 – paddyg

+0

PS如果你用(0,1,1)生成E然後在x = y = img上運行,那麼它只會返回sum(img) - sum(img * img)matplotlib網站表示它將RGB uint8到float32的縮放比例爲0.0到1.0 – paddyg