image_quality_gate: reject blurry or dark photos before OCR, and say why
Any app that asks for a photo of a document has the same problem. The user takes a picture of a receipt, an ID card or a page. It is blurry, or too dark, or there is a reflection across the middle. The app uploads it anyway, the OCR returns nonsense, and the user finds out a minute later, or never.
The cheap fix is to check the photo on the device, right after it is taken, and to say something specific: "the photo is blurry, hold the phone still and try again" is useful, "invalid image" is not.
image_quality_gate does that check. It rejects bad photos before OCR, upload or document scanning, and it tells you exactly why. It is pure Dart, web-safe, and has one dependency, package:image.
What it does
One call, one report. ImageQualityGate(config).evaluate(bytes) returns a QualityReport with passed, a list of typed QualityIssues and all the raw QualityMetrics. Each issue carries its code, the metric it came from, the measured value, the threshold, whether that threshold is a minimum or a maximum, and a severity: error rejects, warning only informs. evaluateImage(Image) does the same for an image you have already decoded.
The checks.
- Sharpness. Variance of the Laplacian, with Tenengrad (Sobel gradient energy) as an optional second metric.
- Exposure. Mean luminance too dark or too bright, plus the fractions of clipped highlights and shadows.
- Glare. The fraction of saturated near-white pixels, optionally only those in connected blobs, so scattered specks are ignored.
- Low contrast. RMS contrast.
- Resolution. Minimum width, height and megapixels, and an aspect-ratio range.
- Document fill. A heuristic that flags a document that is too small in the frame.
Presets. QualityConfig.receipt, idCard, document and photo.
Region of interest. Full frame, centre crop, relative rectangle or pixel rectangle.
Off the UI isolate. evaluateInIsolate, from image_quality_gate_io.dart, runs the work on a background isolate with Isolate.run. The main library imports neither dart:io nor dart:isolate, which is why it also works on the web.
Messages. Built-in messages in English, French and Arabic for every issue code, and you can override any of them.
How to use it
Add it from GitHub:
dependencies: image_quality_gate: git: https://github.com/AbdeldjalilChougui/image_quality_gate Check a photo and show the reasons:
import 'dart:typed_data'; import 'package:image_quality_gate/image_quality_gate.dart'; void check(Uint8List bytes) { const gate = ImageQualityGate(QualityConfig.receipt); final report = gate.evaluate(bytes); if (!report.passed) { final messages = QualityMessages.forLocale('fr'); for (final issue in report.errors) { print(messages.forIssue(issue)); // e.g. "Photo floue. Tenez le téléphone immobile et recommencez." print('${issue.metric} = ${issue.value} (${issue.kind.name} ${issue.threshold})'); } } print(report.metrics.laplacianVariance); } On native platforms, run it on a background isolate:
import 'package:image_quality_gate/image_quality_gate_io.dart'; Future<bool> isUsable(Uint8List bytes) async => (await evaluateInIsolate(bytes, QualityConfig.document)).passed; Custom thresholds, a region of interest and your own wording:
final config = QualityConfig.idCard.copyWith( roi: const RegionOfInterest.centre(widthFraction: 0.9, heightFraction: 0.7), glare: const GlareCheck(maxFraction: 0.002), disable: {QualityCheck.documentFill}, ); final messages = QualityMessages.forLocale('ar', overrides: { QualityIssueCode.glare: 'أمِل البطاقة قليلًا لإزالة الانعكاس.', }); A decode failure throws UndecodableImageException. evaluate applies the EXIF orientation first, so width, height and the region of interest match what the user saw on screen.
How it measures
Luminance is Rec. 601 luma (0.299 R + 0.587 G + 0.114 B) on a 0 to 255 scale, whatever the bit depth of the source. The README has a table with the definition of every metric. Two design points are worth knowing.
Sharpness is measured at native resolution. Downscaling is a low-pass filter. A mild blur on a 12 MP photo shrinks to a fraction of a pixel on a 500 px copy, and the blur signal disappears. One test in the package shows this. So by default the Laplacian is measured on a 600 x 600 window at native resolution, taken from the centre of the region of interest. You can measure the whole region downscaled instead, with SharpnessCheck(window: null, workingSize: ...).
Everything else is one pass. A single pass reads every pixel in the region. It gathers the exposure, contrast and glare statistics, and it builds an area-averaged copy whose long side is QualityConfig.workingSize (512 by default). Glare blobs and the document-fill heuristic run on that copy.
Where the presets come from
The README is direct about this: no published standard gives thresholds for these metrics on phone photos. Each value is either taken from a source or is an engineering choice, and the README lists which is which. For example:
- Laplacian variance 100 (
idCard,document,photo) is the default used in Adrian Rosebrock's "Blur detection with OpenCV" (PyImageSearch, 2015), with the same kernel as OpenCV'scv2.Laplacian. -
documentasks for at least 2 MP and 1000 px per side. Tesseract's documentation recommends at least 300 DPI, and an A4 page at 150 DPI is 1240 x 1754 px. The preset allows phone captures a little under that. -
idCardasks for at least 0.6 MP and an aspect ratio from 1.25 to 2. An ID-1 card (ISO/IEC 7810) is 85.60 x 53.98 mm, about 0.64 MP at 300 DPI. - The exposure, glare, contrast and document-fill values are engineering choices.
Treat all of them as starting points and tune them on your own photos.
Things to know
- The thresholds were not validated on real photos. The synthetic tests check that the presets order images correctly (sharp before blurred, dark before bright). They do not check that the thresholds are right for real photos. No real-photo corpus was used.
- Thresholds depend on content and scale. A page with little text has a lower Laplacian variance than a busy one at the same focus. A threshold tuned for one camera resolution does not carry over to another.
- Only the centre window is checked for sharpness by default. A photo that is sharp in the centre and blurred at the edges (a tilted document, a shallow depth of field) passes. Use a region of interest or
window: nullif that matters. - Glare cannot tell a reflection from a white object that is overexposed. It finds saturated near-white areas.
- Document fill is a heuristic. It is not document detection or perspective estimation. A busy background inflates it and a blank page deflates it, which is why the presets report it as a warning, not an error.
- Aspect ratio ignores orientation. It is long side over short side.
- Decoding is the slow part.
evaluatedepends onpackage:image's decoders, which are pure Dart and slow on large JPEGs. The README's benchmark, on a generated 12 MP JPEG compiled withdart compile exeon a 2016 Intel Core i7-6700HQ laptop, measured about 7.1 s forimg.decodeImageand about 0.64 s forevaluateImagewith all checks. The machine was busy during the run, so the README presents these numbers as upper bounds.
In practice, the README gives three pieces of advice. Cap the capture size, for example with image_picker's maxWidth: 2400, because a photo of a receipt gains nothing from 48 MP. Use evaluateInIsolate so the UI isolate never waits for the decode. And if a platform codec gives you decoded pixels faster, build an Image and call evaluateImage, keeping in mind that decoding at reduced size lowers the sharpness metrics, so thresholds need re-tuning.
Why I built it
A bad photo is cheapest to fix at the moment it is taken, when the user still has the document in hand. After the upload, it costs a failed OCR, a support message or a lost form.
The checks themselves are classic image measurements. What I wanted around them was the part an app needs: a report that says which check failed, with the measured value and the threshold, so the app can show a precise message in the user's language; presets that state where each number comes from, so nobody mistakes an engineering choice for a standard; and a library with no dart:io, so the same gate runs in a Flutter app, on the web and in a Dart script.
Get the code
The source, the README with the metric definitions and the preset sources, the benchmark and the tests are on GitHub: https://github.com/AbdeldjalilChougui/image_quality_gate. It's MIT licensed. Issues and pull requests are welcome, especially threshold feedback from real photos.
Originally published at abdeldjalilchougui.biz.