extractAlignedSquareFromMat function

Mat? extractAlignedSquareFromMat(
  1. Mat src,
  2. double cx,
  3. double cy,
  4. double size,
  5. double theta,
)

Extracts a rotated square region from a cv.Mat using OpenCV's warpAffine.

This function uses SIMD-accelerated warpAffine which is 10-50x faster than pure Dart bilinear interpolation.

Parameters:

  • src: Source cv.Mat image
  • cx: Center X coordinate in pixels
  • cy: Center Y coordinate in pixels
  • size: Output square size in pixels
  • theta: Rotation angle in radians (positive = counter-clockwise)

Returns the cropped and rotated cv.Mat. Caller must dispose. Returns null if size is invalid.

Implementation

cv.Mat? extractAlignedSquareFromMat(
  cv.Mat src,
  double cx,
  double cy,
  double size,
  double theta,
) {
  final int sizeInt = size.round();
  if (sizeInt <= 0) return null;

  // Rotation angle (negated for correct direction, converted to degrees)
  final double angleDegrees = -theta * 180.0 / math.pi;

  // Get rotation matrix centered at the face center
  final cv.Mat rotMat = cv.getRotationMatrix2D(
    cv.Point2f(cx, cy),
    angleDegrees,
    1.0,
  );

  // Adjust translation to crop around the output center
  final double outCenter = sizeInt / 2.0;

  // Modify the translation in the rotation matrix
  final double tx = rotMat.at<double>(0, 2) + outCenter - cx;
  final double ty = rotMat.at<double>(1, 2) + outCenter - cy;
  rotMat.set<double>(0, 2, tx);
  rotMat.set<double>(1, 2, ty);

  // Apply affine transform with SIMD-optimized warpAffine
  final cv.Mat output = cv.warpAffine(
    src,
    rotMat,
    (sizeInt, sizeInt),
    borderMode: cv.BORDER_CONSTANT,
    borderValue: cv.Scalar.black,
  );

  rotMat.dispose();
  return output;
}