我有以下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秒),我真的需要优化它,任何形式的帮助或建议以其他方式欢迎
答案 0 :(得分: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)))
最后一行可以用bsxfun
计算,而不是像这样 -
d = sum(allvals(bsxfun(@and,cond1,cond2)))
答案 1 :(得分:3)
加速matlab代码的黄金法则是避免for循环并尽可能使用矢量化代码和矩阵。使用矢量化和逻辑索引可以非常快速地进行计算。我已经在八度音阶中对以下内容进行了测试,它工作正常且非常快 - 您可能需要将〜=替换为〜=用于matlab兼容性。调整n和p以减少测试的痛苦(或删除前4行)并将d初始化为您喜欢的任何内容。
n=26;
p=31;
i1=1.5*rand(n,n,p); i2=1.5*rand(n,n,p);
s1=sum(i1,3); s2=sum(i2,3);
indices=((s1>2) & (s2>2)) & ((i1!=0) &(i2!=0));
d=0;
d=d+sum(sum( ( (i1(indices)-i2(indices)).^2 ) ./ (i1(indices)+i2(indices)) )),
count=sum(sum( (s1 > 2) & (s2 > 2) ) )