2016-04-08 133 views
1

我正在手動將MATLAB代碼轉換爲Python,並且卡在一行。MATLAB to Python代碼轉換 - imclose()問題

MATLAB代碼:

cashew_BW = threshad(cashew_GRAY(:,:,1),T); 
cashew_BW = ~cashew_BW; 
cashew_BW = imclose(cashew_BW, true(5)); 
cashew_BW = ~cashew_BW 

的Python轉換的代碼:

T = 112 
se = [[1,1,1,1,1]]*5 
cashew_BW = pymorph.threshad(cashew_GRAY, T, f2=None) 
cashew_BW = np.logical_not(cashew_BW) 
cashew_BW = 1*(cashew_BW) 
cashew_BW = pymorph.close(cashew_BW, se) 
cashew_BW = np.logical_not(cashew_BW) 
cashew_BW = 1*(cashew_BW) 

錯誤:

Traceback (most recent call last): 
    File "check1.py", line 22, in <module> 
    cashew_BW = pymorph.close(cashew_BW, se) 
    File "/home/keerthi/anaconda2/lib/python2.7/site-packages/pymorph-0.96-py2.7.egg/pymorph/mmorph.py", line 1303, in close 
    return erode(dilate(f,Bc),Bc) 
    File "/home/keerthi/anaconda2/lib/python2.7/site-packages/pymorph-0.96-py2.7.egg/pymorph/mmorph.py", line 1580, in dilate 
    x,v = mat2set(B) 
    File "/home/keerthi/anaconda2/lib/python2.7/site-packages/pymorph-0.96-py2.7.egg/pymorph/mmorph.py", line 4392, in mat2set 
    if len(A.shape) == 1: A = A[newaxis,:] 
AttributeError: 'list' object has no attribute 'shape' 

如何糾正呢?

回答

0

矩陣在MATLAB中的工作方式類似於numpy數組,但python列表不同。來自MATLAB,這是不明顯的,所以我建議閱讀更多關於Python列表。例如,行

se = [[1,1,1,1,1]]*5 

不會回到[5,5,5,5,5]而是創建

[[1, 1, 1, 1, 1], 
[1, 1, 1, 1, 1], 
[1, 1, 1, 1, 1], 
[1, 1, 1, 1, 1], 
[1, 1, 1, 1, 1]] 

與蟒蛇列表中的默認行爲是創建5倍列表。 您看到的錯誤是因爲您通過se,python列表(len(a)獲取大小),當pymorph.close預計numpy arraya.shape獲取形狀/大小)。你應該總是轉換爲numpy的陣列,以獲得與MATLAB一致的行爲,你的情況,

se = 5*np.array([1,1,1,1,1]) 

會給[5,5,5,5,5],並應避免錯誤pymorph.close作爲本身的類型是numpy的數組。

+0

我只用np.array([1,1,1,1,1])來檢查,我得到一個錯誤:'太多的索引數組' –

+0

我假設錯誤是在將'se'傳遞給'pymorph .close'?從文檔它應該是形式'{3x3十字架''所以也許嘗試像'se = pymorph.secross(r = 1)'看看這是否工作... –