detectionResize function

DetectionResize detectionResize(
  1. int srcWidth,
  2. int srcHeight, {
  3. int sideLimit = 4000,
  4. int? pixelLimit,
  5. int multiple = 32,
})

Computes the detection input size for an srcWidth x srcHeight page: longest side scaled down to at most sideLimit, each side rounded to a multiple of multiple (and never below it). Pages already within the limit are only rounded, never upscaled.

pixelLimit, when set, also caps the area (width x height, before rounding) - for a memory-bound backend, where detection's working set grows with the pixel count rather than the longest side.

Implementation

DetectionResize detectionResize(
  int srcWidth,
  int srcHeight, {
  int sideLimit = 4000,
  int? pixelLimit,
  int multiple = 32,
}) {
  final longest = srcWidth > srcHeight ? srcWidth : srcHeight;
  var ratio = longest > sideLimit ? sideLimit / longest : 1.0;
  if (pixelLimit != null) {
    final pixels = srcWidth * ratio * srcHeight * ratio;
    if (pixels > pixelLimit) ratio *= math.sqrt(pixelLimit / pixels);
  }
  int round(double v) {
    final m = (v / multiple).round() * multiple;
    return m < multiple ? multiple : m;
  }

  final w = round(srcWidth * ratio);
  final h = round(srcHeight * ratio);
  return DetectionResize(
    width: w,
    height: h,
    scaleX: srcWidth / w,
    scaleY: srcHeight / h,
  );
}