detectDocumentQuad static method
Detects the best document quadrilateral from a grayscale image.
This is the high-level API that chains: Canny edge detection → contour finding → quad extraction → corner sorting.
gray — Single-channel grayscale pixel buffer.
width, height — Image dimensions.
candidateCount — Number of top contour candidates to evaluate.
Returns the best DocumentCorners found, or a default inset quad if no valid document edges are detected.
Implementation
static DocumentCorners detectDocumentQuad(
Uint8List gray,
int width,
int height, {
int candidateCount = 5,
double minAreaRatio = 0.15,
}) {
// Stage 1: Canny edge detection
final edges = CannyEdgeDetector.detect(
gray,
width,
height,
useAutoThreshold: true,
);
// Stage 2: Find contours
final contours = findContours(edges, width, height, minContourLength: 40);
// Stage 3: Evaluate top candidates for best quadrilateral
DocumentCorners? bestQuad;
double bestScore = 0;
final evalCount = math.min(candidateCount, contours.length);
for (int i = 0; i < evalCount; i++) {
final quad = findBestQuadrilateral(
contours[i],
width,
height,
minAreaRatio: minAreaRatio,
);
if (quad != null) {
final score = _scoreQuadrilateral(quad, width, height);
if (score > bestScore) {
bestScore = score;
bestQuad = quad;
}
}
}
// Return best quad or default inset
return bestQuad ??
DocumentScannerService.detectDocumentEdges(
Size(width.toDouble(), height.toDouble()),
);
}