2D Convolution algorithm error vs conv2 function

조회 수: 13 (최근 30일)
billy papas
billy papas 2016년 4월 11일
편집: Andrei Bobrov 2016년 4월 11일
[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?

답변 (1개)

Andrei Bobrov
Andrei Bobrov 2016년 4월 11일
편집: Andrei Bobrov 2016년 4월 11일
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
billy papas
billy papas 2016년 4월 11일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Correlation and Convolution에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by