Search code examples
matlabimage-processinggridcentroid

How can I find out where the centriod is present in a gridded image in MATLAB


I hope this image helps. I have taken an image from the camera and generated grids on it. How can I know in which grid my centroid is present? I need to generate a variable or a number which I can use further. For example the centroid is in the 3rd box it generates 3 and I can send it to Arduino using serial communication for further action. I hope you get the idea. Can ROI be helpful in this case if yes then how can i use it?

Centroid and bounding box are already generated in the image using this code.

    stat = regionprops(Ibw1, 'Centroid', 'BoundingBox')
hold on
for x=1:numel(stat)

  rectangle('Position',stat(x).BoundingBox,'EdgeColor','r','LineWidth',1);

    plot(stat(x).Centroid(1),stat(x).Centroid(2),'r*');

end
hold off

After this I used this code to generate grids to the image.

[rows, columns, ~] = size(I);
for row = 1 : 52 : rows
  line([1, columns], [row, row], 'Color', 'r');
end
for col = 1 : 53 : columns
  line([col, col], [1, rows], 'Color', 'r');
end

Solution

  • If you want to get the grid row and column numbers, you should plot the grid with predefined grid row and column width:

    rowWidth = 52; % Grig row width in pixels
    colWidth = 53; % Grig column width in pixels
    [rows, columns, ~] = size(I);
    for row = 1 : rowWidth : rows
        line([1, columns], [row, row], 'Color', 'r');
    end
    for col = 1 : colWidth : columns
        line([col, col], [1, rows], 'Color', 'r');
    end
    

    To get the the grid row and column numbers (assuming you have only one centroid):

    % Get the row and column of the centroid (in grid units) 
    centroidGridCol = ceil(stat(1).Centroid(1) / colWidth);
    centroidGridRow = ceil(stat(1).Centroid(2) / rowWidth);
    

    To see that it is correct, you can calculate the bounding box of the grid an plot it:

    % Get the bounding box of the grid containing the centroid (in pixel units)
    centroidGridBox(1) = (centroidGridCol - 1) * colWidth;
    centroidGridBox(2) = (centroidGridRow - 1) * rowWidth;
    centroidGridBox(3) = colWidth;
    centroidGridBox(4) = rowWidth;
    
    % Plot the bounding box of the grid containing the centroid
    hold on
    rectangle('Position',centroidGridBox ,'EdgeColor','g','LineWidth',1);
    hold off
    

    You can plot the grid row and column as text next to the centroid:

    % Plot the grid row and column next to the centroid
    text(stat(1).Centroid(1),stat(1).Centroid(2),...
        ['(' num2str(centroidGridCol), ', ', num2str(centroidGridRow) ')'],...
        'color','b')
    

    enter image description here