【发布时间】:2018-09-23 14:45:21
【问题描述】:
我需要编写一个二维卷积函数,它会返回与 conv2 相同的结果。
我找到了 conv2 的替代方法,但返回的结果比 conv2 的结果多 2,这会导致错误。
这是我找到的卷积函数from this post:
function [ conv_res ] = convolve_im( im,filter )
[rows,cols] = size(im);
new_img = zeros(rows+2,cols+2);
new_img = cast(new_img, class(im));
new_img(2:end-1,2:end-1) = im;
conv_res = zeros(size(new_img));
conv_res = cast(conv_res, class(im));
for i=2:1:rows+1
for j=2:1:cols+1
value=0;
for g=-1:1:1
for l=-1:1:1
value=value+new_img(i+g,j+l) * filter(g+2,l+2);
end
end
conv_res(i,j)=value;
end
end
conv_res = conv_res(2:end-1,2:end-1);
end
这就是我将结果与 conv2 进行比较的方式:
img = imread('puppy.jpeg');
conv_ok =1;
test_filter=[0 -1 0; -1 4 -1; 0 -1 0];
conv_res = convolve_im(img, test_filter);
ground_res = conv2(img,test_filter, 'valid');
check = abs(ground_res) - abs(conv_res); % Line 24
if sum(abs(check(:,:))) ==0
disp('Convolution for 3x3 works fine.');
else
conv_ok = 0;
disp('Convolution part is wrong for 3x3!!!');
end
这是我得到的运行时错误:
第 24 行的参数不一致(op1 为 211x234,op2 为 213x236)
我该如何解决这个错误?谢谢。
编辑:将 'valid' 更改为 'same' 后,它不再报错,但显示 'Convolution part is wrong for 3x3!!!'
编辑后的测试函数如下:
img = imread('puppy.jpeg');
conv_ok =1;
test_filter=[0 -1 0; -1 4 -1; 0 -1 0]; %laplace filter 3x3
conv_res = convolve_im(img, test_filter);
ground_res = conv2(img,test_filter, 'same');
check = abs(ground_res) - abs(conv_res);
if sum(abs(check(:,:))) ==0
disp('Convolution for 3x3 works fine.');
else
conv_ok = 0;
disp('Convolution part is wrong for 3x3!!!');
end
【问题讨论】:
-
以后你应该参考你从哪里得到代码。我已将您的问题的链接添加到您实际找到它的位置 - 幸运的是,我找到了该链接,因为它是我在之前的答案中使用的代码。
标签: image matlab 2d octave convolution