built-in 2D convolution vs for-loop convolution differences?
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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');
0 commentaires
Réponse acceptée
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
Plus de réponses (0)
Voir également
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!