matlab二维卷积函数,matlab中的二维卷积 – 代码优化

这是我们在图像处理功课中的练习.我的代码工作正常.我想得到一些代码优化方面的帮助.

function C = convolve_slow(A,B)

(file name is accordingly convolve_slow.m )

This routine performs convolution between an image A and a mask B.

Input: A - a grayscale image (values in [0,255])

B - a grayscale image (values in [0,255]) serves as a mask in the convolution.

Output: C - a grayscale image (values in [0,255]) - the output of the convolution.

C is the same size as A.

Method: Convolve A with mask B using zero padding. Assume the origin of B is at

floor(size(B)/2)+1.

Do NOT use matlab convolution routines (conv,conv2,filter2 etc).

Make the routine as efficient as possible: Restrict usage of for loops which are expensive (use matrix multiplications and matlab routines such as dot etc).

To simplify and reduce ifs, you should pad the image with zeros before starting your convolution loop.

Do not assume the size of A nor B (B might actually be larger than A sometimes).

这是我们的解决方案

function [ C ] = convolve_slow( A,B )

%This routine performs convolution between an image A and a mask B.

% Input: A - a grayscale image (values in [0,255])

% B - a grayscale image (values in [0,255]) serves as a mask in the convolution.

% Output: C - a grayscale image (values in [0,255]) - the output of the convolution.

% C is the same size as A.

%

% Method: Convolve A with mask B using zero padding. Assume the origin of B is at floor(size(B)/2)+1.

% init C to size A with zeros

C = zeros(size(A));

% make b xy-reflection and vector

vectB = reshape(flipdim(flipdim(B,1),2)' ,[] , 1);

% padding A with zeros

paddedA = padarray(A, [floor(size(B,1)/2) floor(size(B,2)/2)]);

% Loop over A matrix:

for i = 1:size(A,1)

for j = 1:size(A,2)

startAi = i;

finishAi = i + size(B,1) - 1;

startAj = j;

finishAj = j + size(B,2) - 1;

vectPaddedA = reshape(paddedA(startAi :finishAi,startAj:finishAj)',1,[]);

C(i,j) = vectPaddedA* vectB;

end

end

end

因为我是Image Processing和Matlab的新手.你可以帮助我进行代码优化,特别是基于矩阵的操作.有可能不使用循环吗?

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值