2014-04-29 47 views
-1

我有兩個向量,一個存儲x座標,另一個存儲y座標。當我嘗試在循環中訪問它們時,它將在循環的每次迭代中返回相同的座標。Matlab,向量中的元素

任何人都可以幫助我修復我的循環嗎?

N2=8; 
     info2 = repmat(struct, ceil(size(Z, 1)/N2), ceil(size(Z, 2)/N2)); %creates another array of structs consisting of an m-by-n tiling 
     for row1 = 1:N2:size(Z, 1)%loop through each pixel in the 8x8 window 
      for col1 = 1:N2:size(Z, 2) 
       x = (row1 - 1)/N2 + 1; 
       y = (col1 - 1)/N2 + 1; 

       imgWindow2 = Z(row1:min(end,row1+N2-1), col1:min(end,col1+N2-1)); 
       average2 = mean(imgWindow2(:)); 
       window2(x,y).average=average2; 


       % if the intensity of the 8x8 window is greater than 
       % 210 then considered suspicious- calculate GLCM- 
       if average2>100 
        % display('greater than 100'); 

       %best direction is 0 
        offsets0 = [0 1]; 
        glcms = graycomatrix(imgWindow2,'Offset',offsets0); 
        stats = graycoprops(glcms,'all'); %normalize GLCM so that values are between 0 and 1 

        correlation=[stats.Correlation]; 
        contrast=[stats.Contrast]; 
        homogeneity=[stats.Homogeneity]; 
        energy=[stats.Energy]; 


        %if these conditions are met then this window 
        %contains an ROI 
        if (homogeneity > 0.9) 
         if (contrast<0.2) 
          if (energy>0.6) 


           for i=1:length(coordsX) 
            coordsX(i)=row1; 
            for j=1:length(coordsY) 
            coordsY(j)=col1; 
            end 
           end                         


           for ii=1:length(coordsX) 
           coX=coordsX(ii); 
           for jj=1: length(coordsY) 
            coY=coordsY(jj) 
            Z1 = insertShape(Z, 'rectangle', [coX coY 8 8]); 
            figure(2); 
           end 
           end 


          end 
         end 
        end 

回答

0

有兩個問題與嵌套for循環:

  1. 您使用相同的索引i兩次,所以你在循環中重置最外層循環索引值,不是一個好主意
  2. 您最內層的循環索引爲coordsX,但在循環內部您訪問coordsY。在這裏,你很幸運,因爲coordsXcoordsY看起來有相同的大小。大多數情況下,你會得到一個錯誤。

修復建議:

for ii=1:length(coordsX) 
    coX=coordsX(ii); 
    for jj=1: length(coordsY) 
     coY=coordsY(jj) 
     Z1 = insertShape(Z, 'rectangle', [coX coY 8 8]); 
     figure(2); 
    end 
end 

請注意,我用iijj作爲指標,而不是ij,它通常用於在MATLAB複數。

+0

謝謝,我已經嘗試過此修復,但只有一個矩形出現在圖像上。每次在相同位置的矩形中打開圖像幾次。你知道我可以如何顯示每個座標上有多個矩形的圖像嗎? – user1853871

+0

可能還需要使用'hold on'來確保前一個矩形保留在圖上。 – am304

+0

好的謝謝。但是,陣列中的所有x和y座標都是相同的值。 – user1853871