当前位置:  开发笔记 > 编程语言 > 正文

MATLAB中的图像卷积 - 如何比我的手动编码版本快360倍?

如何解决《MATLAB中的图像卷积-如何比我的手动编码版本快360倍?》经验,为你挑选了1个好方法。

我在MATLAB中玩图像处理算法.其中一个基本的是用高斯卷积图像.我在灰度800x600图像上运行了以下测试:

function [Y1, Y2] = testConvolveTime(inputImage)
[m,n] = size(inputImage);

% casting...
inputImage = cast(inputImage, 'single');

Gvec = [1 4 6 4 1]; % sigma=1;

Y1 = zeros(size(inputImage)); % modify it
Y2 = zeros(size(inputImage)); % modify it


%%%%%%%%%%%%%%%%%%% MATLAB CONV %%%%%%%%%%%%%%%%%%%%%
t1 = cputime;

for i=1:m
    Y1(i,:) = conv(inputImage(i,:),Gvec,'same');
end

for j=1:n
    Y1(:,j) = conv(inputImage(:,j),Gvec','same');
end

Y1 = round(Y1 / 16);
e1 = cputime - t1

%%%%%%%%%%%%%%%%%%% HAND-CODED CONV %%%%%%%%%%%%%%%%%%%%%
t2 = cputime;

for i=1:m
    Y2(i,:) = myConv(inputImage(i,:),Gvec)';
end

for j=1:n
    Y2(:,j) = myConv(inputImage(:,j),Gvec');
end

Y2 = round(Y2 / 16);
e2 = cputime - t2

end

这是我编写的实现2个向量的卷积的代码:

% mimic MATLAB's conv(u,v,'same') function
% always returns column vec
function y = myConv(u_in, v_in)

len1 = length(u_in);
len2 = length(v_in);

if (len1 >= len2)
   u = u_in;
   v = v_in;
else
   u = v_in;
   v = u_in;
end

% from here on: v is the shorter vector (len1 >= len2)

len1 = length(u); 
len2 = length(v); 
maxLen = len1 + len2 - 1;

ytemp = zeros(maxLen,1);

% first part -- partial overlap
for i=1:len2-1
    sum = 0;
    for j=1:i
       sum = sum + u(i-j+1)*v(j);
    end
    ytemp(i) = sum;
end

% main part -- complete overlap
for i=len2:len1
    sum = 0;
    for j=1:len2
       sum = sum + u(i-j+1)*v(j);
    end
    ytemp(i) = sum;
end

% finally -- end portion
for i=len1+1:maxLen
    %i-len1+1
    sum = 0;
    for j=i-len1+1:len2
       sum = sum + u(i-j+1)*v(j);
    end
    ytemp(i) = sum;
end

%y = ytemp;

startIndex = round((maxLen - length(u_in))/2 + 1);
y = ytemp(startIndex:startIndex+length(u_in)-1); 
% ^ note: to match MATLAB's conv(u,v,'same'), the output length must be
%   that of the first argument. 
end

这是我的测试结果:

>> [Y1, Y2] = testConvolveTime(A1);

e1 =

    0.5313


e2 =

  195.8906

>> norm(Y1 - Y2)

ans =

     0

标准为0验证数学正确性.我的问题如下:

1)我的手工编码功能如何比使用MATLAB转换器的功能慢360倍?

2)即使MATLAB的转换对于图像处理仍然"慢".如果使用高斯进行卷积需要0.5秒,那么实时运行任何图像处理算法(例如24 FPS)有什么希望?作为参考,我的CPU是Intel N3540 @ 2.16 GHz.w/8GB的RAM.

3)^真正的问题:当我在C++上切换到OpenCV时,这样的操作会变得更快吗?

感谢您的任何见解,非常感谢.



1> Dima..:

1)conv速度快得多,因为它是一个内置的本机函数,而你的函数是用嵌套循环解释MATLAB代码的.

2)尝试imfilter图像处理工具箱.它可能比它更快conv,并且它适用于uint8数组.或者,如果您获得更新版本的MATLAB,并且只需要高斯滤波器,请尝试imgaussfilt.

推荐阅读
牛尾巴2010
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有