computeSkewAngle static method

double computeSkewAngle(
  1. Uint8List grayBytes, {
  2. required int width,
  3. required int height,
})

Computes the estimated skew angle in degrees from edge gradients.

Returns the angle in degrees (0.0 = perfectly aligned).

Implementation

static double computeSkewAngle(Uint8List grayBytes, {required int width, required int height}) {
  if (grayBytes.isEmpty || width <= 2 || height <= 2) return 0.0;

  double sumAngle = 0;
  int edgeCount = 0;

  for (int y = 1; y < height - 1; y++) {
    for (int x = 1; x < width - 1; x++) {
      final idx = y * width + x;
      if (idx + width < grayBytes.length && idx - width >= 0) {
        final gx = grayBytes[idx + 1] - grayBytes[idx - 1];
        final gy = grayBytes[idx + width] - grayBytes[idx - width];
        final magnitude = math.sqrt(gx * gx + gy * gy);
        if (magnitude > 30) {
          sumAngle += math.atan2(gy.toDouble(), gx.toDouble()) * (180.0 / math.pi);
          edgeCount++;
        }
      }
    }
  }

  if (edgeCount == 0) return 0.0;
  final avgAngle = sumAngle / edgeCount;
  final skew = (avgAngle % 90.0).abs();
  return skew > 45.0 ? 90.0 - skew : skew;
}