built-in 2D convolution vs for-loop convolution differences?

4 vues (au cours des 30 derniers jours)
Matthew Lang
Matthew Lang le 8 Mai 2013
Commenté : Burak Karadeniz le 20 Mar 2021
Can someone tell me what's up with the following code? Why do I get different results implementing my own convolution w/ for loops vs the conv2 function?
x = 0:.1:pi;
A = rand(100,100);
M = sin(x).^2'*sin(x).^2;
figure(1);
subplot(3,2,1);imagesc(x,x,M);colorbar('vert');title('Convolution kernel');
subplot(3,2,2);imagesc(A);colorbar('vert');title('Data matrix');
res = conv2(A,M,'valid');
subplot(3,2,3);imagesc(res);colorbar('vert');title('conv2(A,M)');
res2 = zeros(size(res));
for ii = 1:size(A,1)-size(M,1)+1
for jj = 1:size(A,2)-size(M,2)+1
res2(ii,jj) = sum(sum(M.*A(ii:ii+size(M,1)-1,jj:jj+size(M,2)-1)));
end
end
subplot(3,2,4);imagesc(res2);colorbar('vert');title('for loop conv2(A,M)');
subplot(3,2,5);imagesc(res-res2);colorbar('vert');title('difference');
subplot(3,2,6);imagesc(100*(res-res2)./res);colorbar('vert');title('% error');

Réponse acceptée

Iman Ansari
Iman Ansari le 8 Mai 2013
Hi. You need to rotate your kernel 180 degree:
x = 0:.1:pi;
A = rand(100,100);
M = sin(x).^2'*sin(x).^2;
figure(1);
subplot(3,2,1);imagesc(x,x,M);colorbar('vert');title('Convolution kernel');
subplot(3,2,2);imagesc(A);colorbar('vert');title('Data matrix');
res = conv2(A,M,'valid');
subplot(3,2,3);imagesc(res);colorbar('vert');title('conv2(A,M)');
res2 = zeros(size(res));
M=rot90(M,2);
for ii = 1:size(A,1)-size(M,1)+1
for jj = 1:size(A,2)-size(M,2)+1
res2(ii,jj) = sum(sum(M.*A(ii:ii+size(M,1)-1,jj:jj+size(M,2)-1)));
end
end
subplot(3,2,4);imagesc(res2);colorbar('vert');title('for loop conv2(A,M)');
subplot(3,2,5);imagesc(res-res2);colorbar('vert');title('difference');
subplot(3,2,6);imagesc(100*(res-res2)./res);colorbar('vert');title('% error');
  2 commentaires
Matthew Lang
Matthew Lang le 8 Mai 2013
Ahh! Perfect! Thank you.
Burak Karadeniz
Burak Karadeniz le 20 Mar 2021
Thank you very much

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by