2012-06-19 31 views
0

我有两个图像,我想比较并根据特定像素的值进行不同的操作。问题是速度很慢,我需要加快操作速度,代码可以做些什么?如何在MATLAB中优化两个for循环

currentFrame = rgbimage; %rgbimage is an 800x450x3 matrix 

for i = 1:size(currentFrame, 1) 

    for j = 1 : size(currentFrame,2) 

     if currentFrame(i,j) > backgroundImage(i,j) %backgroundimage is an equally sized image which i would like to compare with 
      backgroundImage(i,j, :) = double(backgroundImage(i,j, :) +1); 

     elseif currentFrame(i,j) < backgroundImage(i,j) 
      backgroundImage(i,j, :) = double(backgroundImage(i,j, :) -1);   
     end 


    end 

end 

diff = abs(double(currentFrame) - double(backgroundImage)); %difference between my backgroundimage and my current frame 
fusion = zeros(size(currentFrame)); % A fusion image 

for i=1:size(backgroundImage,1) 
    for j = 1:size(backgroundImage,2) 

      if diff(i,j) > 20 

      fusion(i,j, :) = double(currentFrame(i,j, :)); 

      else 
      fusion(i,j, :) = 0; 

      end 
    end 
end 

感谢您的帮助!

回答

1

你并不需要循环 - 你可以做的东西,如:

indexes = currentFrame > backgroundImage; 
backgroundImage(indexes) = backgroundImage(indexes) + 1; 

BTW。在你的代码中使用currentFrame(i,j) > backgroundImage(i,j),你只是比较三个颜色维度中的第一个。这是打算?

+0

没有它没有打算,我可以''currentFrame(i,j, :)> backgroundImage(i,j,:)'而不是? – Jonas

+0

工作原理 - 但给你一个1x1x3维的逻辑向量。那么你需要澄清if。 (只有一种颜色更大时,就足够了吗?) – bdecaf

+0

它可以工作,但当我在计算融合图像时,我会做同样的事情时遇到问题。在某些区域颜色会变得非常混乱(从一开始这是一个非常暗的图像,但现在我得到的颜色就像清晰的蓝色/绿色/粉红色),下面是代码:fusion = zeros(size(currentFrame)); index = diff> 20; fusion(indexes)= double(rgbimage(indexes));' – Jonas

1

您可以在一次操作中比较矩阵。例如,

D = diff > 20; 

矩阵d将containe d(I,J)= 1,其中的diff(I,J)> 20,否则为零。

然后你可以使用它来设置其它的矩阵:

fusion = zeros(size(currentFrame)); 
fusion(diff > 20) = double(currentFrame(diff > 20)); 

,并与第一循环一样。

+0

非常感谢,快得多,我使用你的代码和'bdecaf',但他先发布,所以他得到了“正确的答案” – Jonas