matlab卷积conv2,matlab 二维卷积conv2的等效代码

im = imread('lenna.png');

imshow(im);

m = [2 1 0; 1 0 -1; 0 -1 -2]    % a diagonal edge detection mask

im = rgb2gray(im);

im = im2double(im);

General convolution algorithm

The standard way to do a convolution in most languages, using nested loops. This is very slow in Matlab, largely because of array bounds checking.

Note that the +nmr +nmc in the index calculation for im are there only because the output array starts at (1,1). They would be omitted in a language that supported general array bounds.

[nxr, nxc] = size(im);     % nxr: number of im rows, etc.

[nmr, nmc] = size(m);

nyr = nxr - nmr + 1;      % get valid output region

nyc = nxc - nmc + 1;

y1 = zeros(nyr, nyc);      % preallocate output array

tic

for yr = 1:nyr            % loop over output elements

for yc = 1:nyc

sum = 0;

for mr = 1:nmr    % loop over mask elements

for mc = 1:nmc

sum = sum + im(yr-mr+nmr, yc-mc+nmc) * m(mr, mc);

end

end

y1(yr, yc) = sum;  % store result

end

end

toc

imshow(y1, []);       % show final result

Better code in Matlab

A better way of doing it in Matlab, but without using a library function. This does all the multiplications for each mask element together, adding them together a whole array at a time. It's much faster in this language, and gives the same results, as you can see from the final line of the calculation.

This is the kind of method you might employ with parallel processing hardware, if it is available. The key to understanding this is to realise that xpart is a shifted copy of the original input, which is multiplied by one mask element and added in to the output. You need to understand how the : operator in Matlab lets you get a subarray.

[nxr, nxc] = size(im);     % nxr: number of im rows, etc.

[nmr, nmc] = size(m);

nyr = nxr - nmr + 1;       % get valid output region

nyc = nxc - nmc + 1;

y2 = zeros(nyr, nyc);      % preallocate output array

tic

for mr = 1:nmr              % loop over mask elements

for mc = 1:nmc

xpart = im(nmr-mr+1:nxr-mr+1, nmc-mc+1:nxc-mc+1);

y2 = y2 + xpart * m(mr, mc);

end

end

toc

% Compare final result

max_difference = max(max(abs(y2-y1)))

Using Matlab's built-in function

This is the standard Matlab function. Again, it returns the same answer. It's faster still. Note that tic and toc probably aren't giving very accurate reports now, as the time elapsed is very small, and they measure clock time rather than CPU time.

ticy3 = conv2(im, m, 'valid'); % Mask is SECOND argumenttocmax_difference = max(max(abs(y3-y1)))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值