I build and run a FastAPI document API for a UAE insurer. It reads more than 30 document types, in Arabic and English, and the busiest routes take about 8,000 uploads a day. Most of the accuracy did not come from a better model. It came from fixing the image before the OCR engine ever saw it.
This post is the list of OpenCV techniques that earned their place, why each one is there, and where a trained YOLO detector fits.
Detection and extraction are separate API calls. If the document is wrong, the system says so before it pays for an LLM call.
No single mask works on every photo, so the card finder runs four and picks the result that best matches the ID-1 card shape (width to height about 1.586) and the expected number of cards.
- Colour distance. Take the median colour of the page border as "background", measure LAB distance from it, blur, and Otsu threshold.
- Edges. CLAHE, blur, Canny, dilate, then a big morphological close. Cards are dense with fine patterns, so edges pile up on them.
- Texture. Sobel gradient magnitude, normalised by percentile, then Otsu. This works under uneven light where colour distance fails.
- Dark mat. Inverted Otsu for light cards on a dark table, with row and column projections to split cards lying side by side.
findContours, convex hull, minAreaRect, and boxPoints give a four-point box. Blobs that fill the page are thrown away.
- If two cards touch, erode until they separate, then dilate each one back.
- GrabCut grows the box from the text-dense centre to the real card edge.
getPerspectiveTransform and warpPerspective turn an angled phone photo into a flat card.
- A portrait crop is rotated to landscape. If the crop still does not classify, it is retried at 90, 180, and 270 degrees, with a cap on extra OCR calls so cost stays bounded.
- Laplacian variance on a crop tells you whether there is any print on it. A blank card-shaped rectangle is not a card.
- Line counting with Canny and a wide horizontal close finds full-width lines. Letters and credit notes have them, cards do not, so those pages skip the card path completely.
One preprocessing recipe for everything makes some documents worse.
- Vehicle certificates. Check brightness and contrast first, then pick a dark, bright, or low-contrast path. Bilateral filter for noise, because it keeps edges. Deskew only between 0.5 and 10 degrees, since larger angles are usually a misread, not a tilt. CLAHE, then an unsharp mask. Finally crop the band where the chassis number lives, upscale it 2x, and sharpen it.
- Police reports. Bold fonts make OCR merge digits, so 6 becomes 8. Invert, erode with a small elliptical kernel, and invert back. Thinner strokes give cleaner digits.
- Trade licences. CLAHE only. Anything heavier damaged the rendered PDF.
- Signatures. Adaptive threshold on the lower half of the form, dilate and close to join the strokes, then score each contour by area, solidity, and height to tell a signature from printed text.
The motor detector became a scored decider. It adds up Arabic and English keyword evidence, checks the machine-readable zone on ID cards with its check digits, rejects photos that are too poor to read, and names the common wrong uploads. On 3,740 real uploads, correct decisions went from 76.5% to 98.9%, and wrong documents accepted went from 48 to 1.
A chassis number (VIN, ISO 3779) never contains I, O, or Q. A confusion matrix swaps them for the likely digit, candidates are checked by length and position, and Vision's per-word confidence breaks ties. Registration-card chassis extraction went from 89.9% to 98.0%.
Classical OpenCV is fast, needs no GPU, and you can explain every decision. It also needs a lot of hand-tuned rules for strange photos. So I also fine-tuned a YOLO model (Ultralytics) to detect cards and documents.
The training ran on Kaggle:
- Collect and anonymise sample images, then label the card and document boxes.
- Train on Kaggle's free GPUs in a notebook, starting from pretrained weights.
- Validate on a held-out set, checking precision and recall per class.
- Export the weights and use the model as a detection step that crops the document before OCR.
The two approaches complement each other. YOLO handles messy photos well. OpenCV is the cheap, explainable fallback.
- Most OCR errors are image errors. Fix the pixels first.
- Use a different cleanup recipe per document type.
- Reject the wrong document before the LLM call, and say why.
- Measure on real uploads. The 98.9% number is what convinced the business, not a demo.