cropFromRoiMat function

  1. @visibleForTesting
Mat cropFromRoiMat(
  1. Mat src,
  2. RectF roi
)

Crops a rectangular region from a cv.Mat using normalized coordinates.

Operates directly on cv.Mat objects for efficient OpenCV pipeline integration.

The src parameter is the source image to crop from.

The roi parameter defines the crop region with normalized coordinates where (0, 0) is the top-left corner and (1, 1) is the bottom-right corner of the source image. Coordinates are clamped to valid image bounds.

Returns a cropped cv.Mat containing the specified region. The returned Mat shares memory with src via cv.Mat.region, so src must remain valid while the result is in use. Caller is responsible for disposing the returned Mat.

Example:

final roi = RectF(0.2, 0.3, 0.8, 0.7);
final cropped = cropFromRoiMat(sourceMat, roi);
// Use cropped...
cropped.dispose();

Implementation

@visibleForTesting
cv.Mat cropFromRoiMat(cv.Mat src, RectF roi) {
  final int w = src.cols;
  final int h = src.rows;

  final int x1 = (roi.xmin * w).round().clamp(0, w - 1);
  final int y1 = (roi.ymin * h).round().clamp(0, h - 1);
  final int x2 = (roi.xmax * w).round().clamp(x1 + 1, w);
  final int y2 = (roi.ymax * h).round().clamp(y1 + 1, h);

  final int cropW = x2 - x1;
  final int cropH = y2 - y1;

  final cv.Rect rect = cv.Rect(x1, y1, cropW, cropH);
  return src.region(rect);
}