matlab中的二维卷积 - 代码优化

时间:2012-12-15 21:47:26

标签: matlab image-processing optimization convolution

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

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的新手。你可以帮助我进行代码优化,特别是基于矩阵的操作。是否有可能不使用循环?

2 个答案:

答案 0 :(得分:5)

如果没有明确地编写代码,我可以看到一种方法将其归结为一个主for循环。基本上,通过将A和B的每一列展开到一个向量中(将其存储在MATLAB内部),将矩阵A和B视为列向量。然后,(i,j)的每个A坐标都可以映射到线性索引k(例如,使用函数sub2ind)。然后,对于A体内的每个线性索引(忽略填充),计算与该线性索引周围的子矩阵相对应的线性索引列表(这可能是这里最难的部分)。然后计算A( theseIndices )B(:)的点积。使用此方法,您只需循环遍历A的每个线性索引。

答案 1 :(得分:3)

不知道这是否更快,但至少没有for循环(这并不意味着它在最近的matlab版本中不再需要更快)

function A = tmpConv(A,B)

    filterSize = size(B,1);
    filterSize2 = floor(filterSize/2);
    inputSize = size(A);

    A = padarray(A,[filterSize2 filterSize2]);

    f = repmat(B(:),[1 inputSize(1)*inputSize(2)]);
    A = im2col(A,[filterSize filterSize]);
    A = reshape(sum(A.*f),inputSize);