如何找出质心在 MATLAB 中的网格化图像中的位置

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

I hope this image helps. 我从相机拍摄了一张图像并在其上生成了网格。我怎么知道我的质心在哪个网格中?我需要生成一个我可以进一步使用的变量或数字。例如,质心位于第三个框中,它生成 3,我可以使用串行通信将其发送到 Arduino 以进行进一步操作。我希望你明白了。 ROI 在这种情况下有帮助吗?如果是,我该如何使用它?

图像中已经生成质心和边界框 使用此代码。

    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

在此之后,我使用此代码为图像生成网格。

[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

如果你想得到网格的行数和列数,你应该用预定义的网格行和列宽绘制网格:

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

获取网格行号和列号(假设你只有一个质心):

% 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);

要查看它是否正确,您可以计算网格的边界框并绘制它:

% 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

您可以将网格行和列绘制为质心旁边的文本:

% 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')