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