Menu

Preparing ID card photos for OCR with OpenCV: find the card, flatten it, and reject blur and glare
📰

Preparing ID card photos for OCR with OpenCV: find the card, flatten it, and reject blur and glare

DEV Community: computervision·Ali Ahmed·about 17 hours ago
#IKW7Yyij
Reading 0:00
15s threshold

OCR on a phone photo of an ID card fails mostly because of the photo : the card is tilted, so text is skewed; it's blurry; or glare washes out a field. Before running OCR, find the card's four corners, warp it to a flat rectangle at the ID-1 aspect ratio (85.6 × 54 mm), and score sharpness and glare , rejecting or re-capturing bad frames. The code below does that with OpenCV. It's tested on a synthetic image, and it's the classic approach; production systems usually replace corner detection with a trained model, but the steps after it stay the same.

Step 1: find the card

On a reasonably contrasting background, the card is the largest four-sided contour:

```python title="find_card.py"

import cv2

import numpy as np

def find_card(image: np.ndarray) -> np.ndarray | None:

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

edges = cv2.Canny(cv2.GaussianBlur(gray, (5, 5), 0), 50, 150)

contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

for contour in sorted(contours,…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.