大家好!我目前正在将一个 MATLAB 项目转换为 Python 2.7。我正在尝试转换行
h = [ im(:,2:cols) zeros(rows,1) ] - [ zeros(rows,1) im(:,1:cols-1) ];
当我尝试转换它时
h = np.concatenate((im[1,range(2,cols)], np.zeros((rows, 1)))) -
np.concatenate((np.zeros((rows, 1)),im[1,range(2,cols - 1)] ))
IDLE 返回不同的错误,如
ValueError: all the input arrays must have same number of dimensions
我是 Python 的新手,如果您能推荐其他方法,我将不胜感激。太感谢了!这是我要转换的函数。
function [gradient, or] = canny(im, sigma, scaling, vert, horz)
xscaling = vert; yscaling = horz;
hsize = [6*sigma+1, 6*sigma+1]; % The filter size.
gaussian = fspecial('gaussian',hsize,sigma);
im = filter2(gaussian,im); % Smoothed image.
im = imresize(im, scaling, 'AntiAliasing',false);
[rows, cols] = size(im);
h = [ im(:,2:cols) zeros(rows,1) ] - [ zeros(rows,1) im(:,1:cols-1) ];
而且我还会询问主要用于 Python 的索引和数组中的“:”运算符的等价物。 : 运算符是否有任何等效项?
我开始的Python转换代码:
def canny(im=None, sigma=None, scaling=None, vert=None, horz=None):
xscaling = vert
yscaling = horz
hsize = (6 * sigma + 1), (6 * sigma + 1) # The filter size.
gaussian = gauss2D(hsize, sigma)
im = filter2(gaussian, im) # Smoothed image.
print("This is im")
print(im)
print("This is hsize")
print(hsize)
print("This is scaling")
print(scaling)
#scaling = 0.4
#scaling = tuple(scaling)
im = cv2.resize(im,None, fx=scaling, fy=scaling )
[rows, cols] = np.shape(im)
最佳答案
假设您的数据在列表列表中。试试这个:
a = [[2, 9, 4], [7, 5, 3], [6, 1, 8]]
im = np.array(a, dtype=float)
rows = 3
cols = 3
h = (np.hstack([im[:, 1:cols], np.zeros((rows, 1))])
- np.hstack([np.zeros((rows, 1)), im[:, :cols-1]]))
相当于 MATLAB 的 horzcat (即 [A B]
)是 np.hstack相当于vertcat ([A; B]
) 是 np.vstack .
Array indexing在 numpy 中非常接近 MATLAB,除了在 numpy 中索引从 0 开始,范围 p:q 表示“p 到 q-1”。
还有,数组的存储顺序是row-major默认情况下,您可以根据需要使用列优先顺序(参见 this )。在 MATLAB 中,数组按列优先顺序存储。要 checkin Python,请键入例如 np.isfortran(im)
。如果它返回 true,则该数组具有与 MATLAB 相同的顺序(Fortran 顺序),否则它是行优先的(C 顺序)。当您想要优化循环,或者当您将数组传递给 C 或 Fortran 例程时,这一点很重要。
理想情况下,尽量将所有内容尽快放入 np.array 中,并且不要使用列表(它们占用更多空间并且处理速度更慢)。还有一些怪癖:例如,1.0/0.0
抛出异常,但是 np.float64(1.0)/np.float64(0.0)
返回 inf
,就像在 MATLAB 中一样。
评论中的另一个例子:
d1 = [ im(2:rows,2:cols) zeros(rows-1,1); zeros(1,cols) ] - ...
[ zeros(1,cols); zeros(rows-1,1) im(1:rows-1,1:cols-1) ];
d2 = [ zeros(1,cols); im(1:rows-1,2:cols) zeros(rows-1,1); ] - ...
[ zeros(rows-1,1) im(2:rows,1:cols-1); zeros(1,cols) ];
对于这一个,您可以使用 np.block 而不是 np.vstack 和 np.hstack .
im = np.ones((10, 15))
rows, cols = im.shape
d1 = (np.block([[im[1:rows, 1:cols], np.zeros((rows-1, 1))],
[np.zeros((1, cols))]]) -
np.block([[np.zeros((1, cols))],
[np.zeros((rows-1, 1)), im[:rows-1, :cols-1]]]))
d2 = (np.block([[np.zeros((1, cols))],
[im[:rows-1, 1:cols], np.zeros((rows-1, 1))]]) -
np.block([[np.zeros((rows-1, 1)), im[1:rows, :cols-1]],
[np.zeros((1, cols))]]))
关于python - MATLAB 到 Python 转换 : vectors, 数组,索引元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53617093/