built-in 2D convolution vs for-loop convolution differences?
4 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
採用された回答
Iman Ansari
2013 年 5 月 8 日
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 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Creating and Concatenating Matrices についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!