matlab – Save values ​​with the "for" command

Question:

My question:

How can I store the values ​​of the 'for' command of objects that have an area greater than 50? I need to store the numbers of these objects because later I will calculate the distance between two of them, would anyone know how to store these values?

Code:

original = imread('A.jpg');
verde = original(:,:,2) > 250;
imshow(verde);
[B,L] = bwboundaries(verde, 'noholes');
stats = regionprops(L, 'Area');
qtd_verde = sum([stats.Area] > 50);
imshow(original);

hold on
for k = 1:length(B)
    area = stats(k).Area;

    if area > 50
        boundary = B{k};
        plot(boundary(:,2), boundary(:,1), 'black', 'LineWidth', 2);
        text(boundary(1,2), boundary(1,1), sprintf('%.0f',k),...
            'Color', 'white',...
            'FontSize', 12,...
            'FontWeight', 'bold',...
            'BackgroundColor', 'black');


    end
end
hold off

@EDIT

I managed to solve it by selecting the geometric shape that interested me, in this case a rectangle, soon only the two objects will appear 'always'. But if someone knows how to solve the previous problem, it would be very interesting and would help me a lot!

original = imread('A.jpg');
verde = original(:,:,2) > 218;
imshow(verde);
[B,L] = bwboundaries(verde, 'noholes');
MN = [3 15];
SE = strel('rectangle', MN);
Iopenned = imopen(L,SE);
imshow(Iopenned);
%=============
[J,H] = bwboundaries(Iopenned, 'noholes');
stats = regionprops(Iopenned, 'Area');
qtd_verde = sum([stats.Area] > 50)
imshow(original);
title(sprintf('\\fontsize{16}{Existem %d objetos verdes nessa imagem}', qtd_verde));

hold on
for k = 1:length(J)
    boundary = J{k};
    plot(boundary(:,2), boundary(:,1), 'black', 'LineWidth', 2);
    text(boundary(1,2), boundary(1,1), sprintf('%.0f',k),...
        'Color', 'white',...
        'FontSize', 12,...
        'FontWeight', 'bold',...
        'BackgroundColor', 'black');



end
hold off

Answer:

I'm not sure if my method works with your system, as I don't know exactly what you need to keep, as I can't run your code (I don't have your image, if you comment, I can change it accordingly). However, even if you have a cell , it is possible to use this method (use the cell(m,n,p) ), just make the declaration and copies properly.

I made an initial declaration of a jj counter and a savedindex array to store the data. After the for loop, I cut the remaining zeros from the matrix.

b=rand(50,1); %data qq pra testar

jj=1; %temp index
savedindex=zeros(numel(b),1); %Declara a matriz
for ii=1:numel(b);

    if b(ii)>0.5,

        %faz o que vc precisa e...

        %Salva o indice
        savedindex(jj)=ii;
        jj=jj+1;%aumenta pra proxima iteracão
    end

end

savedindex=savedindex(1:(jj-1),1);%recorta os zeros não utilizados da matriz 
Scroll to Top