简单的图像特征camparision花费了太多时间

Git*_*esh 3 optimization matlab image-processing vectorization computer-vision

我有以下matlab代码用于比较图像的直方图特征; 功能基本上是3维阵列

for i=1:1:26
    for j=1:1:26
        s1=sum(image1(i,j,:));
        s2=sum(image2(i,j,:));
        if(s1>2 && s2>2)
            for k=1:1:31
                if image1(i,j,k)~=0 && image2(i,j,k)~=0  
                    d = d + ((image1(i,j,k) - image2(i,j,k))^2)/ (image1(i,j,k) + image2(i,j,k));
                end
            end
            count=count+1;
        end
    end
end
Run Code Online (Sandbox Code Playgroud)

代码给出了令人满意的结果,但问题是在我的机器上matlab花了很多时间(1秒),我真的需要优化它,任何形式的帮助或建议以其他方式做到欢迎

Div*_*kar 7

这是一种vectorized方法 -

%// Sum elements of image1 & image2 along the third dimension corresponding 
%// to s1 and s2 in the original loopy code
s1v = sum(image1,3);
s2v = sum(image2,3);

%// Pre-calculate all image1,image2 operations that lead to the calculation
%// of d in the original code
allvals = ((image1 - image2).^2)./(image1 + image2);

%// Calculate the first conditional values for the corresponding IF conditional
%// statement in original post - "if(s1>2 && s2>2)"
cond1 = s1v>2 & s2v>2

%// Sum all satisfying first conditional values for getting "count"
count = sum(cond1(:))

%// Calculate the second conditional values for the corresponding IF conditional
%// statement in original post - "if image1(i,j,k)~=0 && image2(i,j,k)~=0"
cond2 = image1~=0 & image2~=0;

%// Map both cond1 and cond2 onto allvals to select specific elements from
%// it and then sum those up for the final output, d
d = sum(cond1(:).'*reshape(cond2.*allvals,[],size(allvals,3)))
Run Code Online (Sandbox Code Playgroud)

最后一行可以bsxfun像这样计算-

d = sum(allvals(bsxfun(@and,cond1,cond2)))
Run Code Online (Sandbox Code Playgroud)

  • @Divakar速度提高了200倍......谢谢 (3认同)