2D Convolution algorithm error vs conv2 function

12 visualizzazioni (ultimi 30 giorni)
billy papas
billy papas il 11 Apr 2016
Modificato: Andrei Bobrov il 11 Apr 2016
[r,c] = size(x);
[m,n] = size(y);
h = rot90(y, 2);
center = floor((size(h)+1)/2);
Rep = zeros(r + m*2-2, c + n*2-2);
return
for x1 = m : m+r-1
for y1 = n : n+r-1
Rep(x1,y1) = x(x1-m+1, y1-n+1);
end
end
B = zeros(r+m-1,n+c-1);
for x1 = 1 : r+m-1
for y1 = 1 : n+c-1
for i = 1 : m
for j = 1 : n
B(x1, y1) = B(x1, y1) + (Rep(x1+i-1, y1+j-1) * h(i, j));
end
end
end
end
Con=conv2(Rep,h);
In this code ,after getting result of conv2 , i see that the above algorithm misses many elements of wanted output of convolution.Can someone help to fix this problem?

Risposte (1)

Andrei Bobrov
Andrei Bobrov il 11 Apr 2016
Modificato: Andrei Bobrov il 11 Apr 2016
a =reshape(1:12,4,[]);
b = reshape(1:8,2,[]);
without conv2
[m,n] = size(a);
[m1,n1] = size(b);
mn = [m,n] + 2*([m1,n1]-1);
a0 = zeros(mn);
a0(m1:(end-m1+1),n1:(end-n1+1)) = a;
i0 = reshape(1:numel(a0),mn(1),[]);
ii = i0(1:end-m1+1,1:end-n1+1);
i1 = bsxfun(@plus,(0:m1-1)',(0:n1-1)*mn(1));
idx = bsxfun(@plus,ii(:),i1(:)');
out = reshape(a0(idx)*reshape(rot90(b,2),[],1),m1+m -1,[]);
without conv2, with for loops
[m,n] = size(a);
[m1,n1] = size(b);
mn = [m,n] + 2*([m1,n1]-1);
a0 = zeros(mn);
a0(m1:(end-m1+1),n1:(end-n1+1)) = a;
b1 = rot90(b,2);
b2 = b1(:);
out = zeros(m1+m-1,n+n1-1);
for ii = 1:mn(1)-m1+1
for jj = 1:mn(2)-n1+1
x = a0(ii:ii+m1-1,jj:jj+n1-1);
out(ii,jj) = x(:)'*b2;
end
end
with conv2
out = conv2(a,b)
  1 Commento
billy papas
billy papas il 11 Apr 2016
Thanks for the answer.But would like to optimize my code so that i can work.Your code seems really complex for my knowledge,although it's excellent as implementation.

Accedi per commentare.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by