extractSubGrid static method

Matrix extractSubGrid({
  1. required Matrix binaryImage,
  2. required Rect rect,
})

Extracts a sub-grid from a larger binary image matrix.

This static method creates a new Matrix object representing a portion of the input binary image, as specified by the given rectangle.

Parameters:

  • binaryImage: The source Matrix from which to extract the sub-grid.
  • rect: A Rect object specifying the region to extract. The rectangle's coordinates are relative to the top-left corner of the binaryImage.

Returns: A new Matrix object containing the extracted sub-grid.

Note:

  • If the specified rectangle extends beyond the boundaries of the source image, the out-of-bounds areas in the resulting sub-grid will be false.
  • The method uses integer coordinates, so any fractional values in the rect will be truncated.

Implementation

static Matrix extractSubGrid({
  required final Matrix binaryImage,
  required final Rect rect,
}) {
  final int startX = rect.left.toInt();
  final int startY = rect.top.toInt();
  final int subImageWidth = rect.width.toInt();
  final int subImageHeight = rect.height.toInt();

  final Matrix subImagePixels = Matrix(subImageWidth, subImageHeight, false);

  for (int x = 0; x < subImageWidth; x++) {
    for (int y = 0; y < subImageHeight; y++) {
      final int sourceX = startX + x;
      final int sourceY = startY + y;

      if (sourceX < binaryImage.cols && sourceY < binaryImage.rows) {
        subImagePixels.cellSet(x, y, binaryImage.cellGet(sourceX, sourceY));
      }
    }
  }

  return subImagePixels;
}