Most OCR failures we are asked to debug are not recognition failures. The text model is fine; the input is a skewed, shadowed, half-cropped photo of a page. This tutorial builds the capture stage that sits in front of OCR: find the page, flatten it, straighten it, and refuse captures that are not good enough.
1. Decide what the output must be
Fix the contract first: an upright image at a known pixel size (for example A4 at 200 DPI, 1654 x 2339 px), grayscale or colour, with even illumination. A fixed output size means downstream code, and any measurement on the page, behaves the same every time.
2. Find the page quadrilateral
Downscale for speed, then look for the largest convex four-point contour.
import cv2, numpy as np
def find_page_quad(img, work_h=800):
scale = work_h / img.shape[0]
small = cv2.resize(img, None, fx=scale, fy=scale, interpolation=cv2.INTER_AREA)
gray = cv2.cvtColor(small, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (5, 5), 0)
edges = cv2.Canny(gray, 50, 150)
edges = cv2.dilate(edges, np.ones((3, 3), np.uint8), iterations=1)
cnts, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:10]
for c in cnts:
hull = cv2.convexHull(c)
peri = cv2.arcLength(hull, True)
approx = cv2.approxPolyDP(hull, 0.02 * peri, True)
area = cv2.contourArea(approx)
if len(approx) == 4 and area > 0.2 * small.shape[0] * small.shape[1]:
return approx.reshape(4, 2).astype(np.float32) / scale
return None
Common failure: a white page on a white desk gives weak edges. Fall back to a threshold on a saturation or Otsu mask, or ask the user to capture on a darker surface. Do not guess a quad; returning None is a valid answer.
3. Order the corners and warp
def order_corners(pts):
s = pts.sum(axis=1); d = np.diff(pts, axis=1).ravel()
return np.array([pts[np.argmin(s)], pts[np.argmin(d)],
pts[np.argmax(s)], pts[np.argmax(d)]], np.float32) # TL, TR, BR, BL
def dewarp(img, quad, out_w=1654, out_h=2339):
src = order_corners(quad)
dst = np.array([[0,0],[out_w-1,0],[out_w-1,out_h-1],[0,out_h-1]], np.float32)
H = cv2.getPerspectiveTransform(src, dst)
return cv2.warpPerspective(img, H, (out_w, out_h), flags=cv2.INTER_CUBIC)
If the page was shot in landscape, check the aspect ratio of the ordered quad first and swap out_w/out_h, or rotate afterwards. Warping with INTER_CUBIC keeps thin strokes crisper than bilinear.
4. Flatten the illumination
Shadows from a hand or lamp wreck global thresholds. Estimate the background with a large morphological close or blur and divide it out.
def flatten(gray):
bg = cv2.morphologyEx(gray, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (51, 51)))
bg = cv2.medianBlur(bg, 51)
norm = cv2.divide(gray, bg, scale=255)
return norm
For a binary image, apply cv2.adaptiveThreshold to the flattened result. For OCR with a modern neural recogniser, keep the flattened grayscale rather than binarising; binarisation throws away information the model can use.
5. Deskew the residual angle
Perspective correction fixes the page, but text lines can still tilt by a degree or two. Estimate the angle from the text pixels and rotate.
def deskew(gray, max_angle=10):
inv = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
inv = cv2.dilate(inv, cv2.getStructuringElement(cv2.MORPH_RECT, (25, 3)))
pts = cv2.findNonZero(inv)
(_, _), (w, h), ang = cv2.minAreaRect(pts)
if ang > 45: ang -= 90
if abs(ang) > max_angle:
return gray, 0.0
M = cv2.getRotationMatrix2D((gray.shape[1]/2, gray.shape[0]/2), ang, 1.0)
return cv2.warpAffine(gray, M, gray.shape[::-1], flags=cv2.INTER_CUBIC, borderValue=255), ang
The horizontal dilation merges characters into line blobs, so the rectangle follows lines rather than individual glyphs. The angle convention of minAreaRect has changed between OpenCV releases, so test both signs on a synthetic page rotated by a known angle and pin that test in CI. Note that a 180 degree flip is not detectable this way; use an orientation classifier or let your OCR engine report orientation.
6. A quality gate before OCR
Cheap checks reject most bad captures:
def quality(img_gray, quad, frame_shape):
lap_var = cv2.Laplacian(img_gray, cv2.CV_64F).var()
page_frac = cv2.contourArea(quad.astype(np.float32)) / (frame_shape[0]*frame_shape[1])
clipped = (np.mean(img_gray > 250), np.mean(img_gray < 5))
return {"sharpness": lap_var, "page_fraction": page_frac, "white_clip": clipped[0], "black_clip": clipped[1]}
- Sharpness: variance of the Laplacian below your calibrated threshold means blur. Calibrate the threshold on your own good and bad samples at the output size; there is no universal number.
- Page fraction: if the page fills under roughly a third of the frame, effective resolution is too low. Ask for a closer shot.
- Corner proximity: if a detected corner sits on the image border, the page is probably cropped.
- Clipping: large saturated regions indicate glare. Reject and show the user where the glare is.
Return a reason code with every rejection so the capture UI can say what to fix.
7. Putting it together
def capture(img):
quad = find_page_quad(img)
if quad is None:
return {"ok": False, "reason": "no_page"}
page = dewarp(img, quad)
gray = flatten(cv2.cvtColor(page, cv2.COLOR_BGR2GRAY))
gray, angle = deskew(gray)
q = quality(gray, quad, img.shape)
return {"ok": True, "image": gray, "angle": angle, "quality": q}
8. Test it like software
Build a fixture set of 50 to 100 real captures with varied lighting, backgrounds and tilt, plus a few synthetic ones (warp a clean PDF render with known homographies). Track three numbers per release: page-detection rate, corner error against hand-labelled corners in pixels, and downstream OCR character error rate. If a change improves the first two but worsens the third, it is not an improvement.
Where this approach stops
Contour-based quads assume a flat page. Curled book pages, folded receipts and creased forms need a dewarping model (mesh or learned) rather than a single homography. Multi-page tables, stamps and handwriting also change the cleanup you want. If your volume or accuracy target rules out the simple pipeline, that is the point where an experienced OpenCV engineer pays for themselves.
SentientSight builds capture and OCR front-ends for mobile, kiosk and scanner-line deployments. If you have a document workflow that is losing accuracy at the capture step, get in touch via our contact page.