1

我正在手动将 MATLAB 代码转换为 Python,但我被困在一行中。

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'

我该如何纠正?

4

1 回答 1

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]]

python 列表的默认行为是创建 5 次列表。您看到的错误是因为您正在传递se一个 python 列表(len(a)以获取大小),而pymorph.close需要一个numpy 数组a.shape以获取形状/大小)。在您的情况下,您应该始终转换为 numpy 数组以获得与 MATLAB 一致的行为,

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

将给出[5,5,5,5,5]并且应该避免错误,pymorph.close因为 se 是 numpy 数组类型。

于 2016-04-08T09:16:20.543 回答