matlab - 简单的图像特征比较花费太多时间

标签 matlab image-processing optimization computer-vision vectorization

我有以下用于比较图像直方图特征的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

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

最佳答案

这是一个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)))

最后一行可以用 bsxfun 代替这样计算 -

d = sum(allvals(bsxfun(@and,cond1,cond2)))

关于matlab - 简单的图像特征比较花费太多时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29346464/

相关文章:

matlab - 如何在 MATLAB 中创建分段内联函数?

Python OpenCV 找到图像中的所有三角形

python-3.x - 分割图像上的重叠预测

optimization - SIMD 指令降低 CPU 频率

python - Matlab - 使用 h5py 在 Python 中读取 .mat 7.3 时间序列数组

matlab - 我正在尝试编写代码以将传输信号与接收信号交叉关联以确定样本延迟数

python-3.x - 如何使用 OpenCV 查找图像中三角形的方向

c# - 使用 yield 如何节省时间或内存?

python - 选择具有共享元素的集合的算法

c++ - 分水岭算法——CT肺部分割