The goal is an OCR system that reads photos of paper forms whose values are written in a table, usually by hand. Photos can be blurry, skewed or unevenly lit, and there are several versions of the form.
The system has to run offline on a phone or in a web browser, and fast (about 1 s per photo, like a phone camera's text feature). So the pipeline only uses plain OpenCV calls and small pretrained ONNX models, which also exist as OpenCV.js / onnxruntime-web and their mobile versions.
extract_table.py reads the table of each photo into one JSON file:
photo ─► quality gate ─► grid lines ─► cells ─► ink check ─► read ─► names ─► JSON
The photo is used as taken: nothing is straightened, cropped or enhanced, and every position in the JSON is in the photo's pixels.
| Step | Where | What it does |
|---|---|---|
| Quality gate | preprocessing/quality_gate.py |
Measures sharpness, noise, the number of ruled lines and what the PP-OCRv5 text detector finds. Pass, or fail with the reasons (e.g. "blurry"). |
| Grid lines, cells | preprocessing/grid_lines.py |
Finds the table's ruled lines, faint ones too; each keeps its own slope, so tilted and skewed photos work. Faint lines that were left out are added back where the gap between two lines is unusually wide. Every line runs from border to border of the table, and each cell is a 4-corner shape where the lines cross. |
| Ink check | extract_table.py |
A cell holds text if enough of its inside is dark. Empty cells are not read. |
| Read | extract_table.py |
Each cell with ink is cut out along its corners and read by the PP-OCRv5 mobile recognizer. |
| Names | extract_table.py |
Top rows and left columns whose cells mostly contain letters are headers; they give every other cell its column and row name. |
More detail and the design decisions behind each step are in docs/architecture.md; what to work on next is in docs/next_steps.md. The docstring at the top of each script explains its step in full.
ocr_experiment/
├── extract_table.py reads the table of each photo into JSON
├── preprocessing/ one script per step: grid_lines.py, quality_gate.py, the helpers
│ they use (table_crop.py, text_boxes.py, denoise.py) and earlier experiments
├── docs/ architecture.md (how it works and why), next_steps.md (what to do next)
├── templates/ per-form-version templates (line positions, field names); not used yet
├── data/ not in git (may contain patient data), except images_selection/
│ ├── images/ all real form photos
│ └── images_selection/ 12 test photos and expected.csv (rows and columns of each)
├── results/ not in git: JSON and debug images
├── .github/ pull_request_template.md
├── requirements.txt libraries the scripts use
└── pyproject.toml candidate libraries for later, and ruff settings
Use Python 3.12 or newer, in a virtual environment of your choice, and install the libraries from the project folder:
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
With conda instead: conda create -n <name> python=3.13, conda activate <name>,
then the same pip install.
rapidocr downloads its models the first time it runs, so that needs internet.
The photos in data/ are not in git and have to be shared separately. Run every
command from the project folder, so the scripts find data/ and results/.
python extract_table.py data/images_selection # the whole pipeline
python preprocessing/grid_lines.py data/images_selection # only the grid
python preprocessing/quality_gate.py data/images_selection # only the gate
Each prints one line per photo, and compares the rows and columns found with
data/images_selection/expected.csv (photo,n_rows,n_cols,turn, filled in by
hand; an empty value is not checked). extract_table.py saves
results/extract_table/<photo>.json:
{
"photo": "data/images_selection/xxx.png",
"quality": {"ok": true, "reasons": [], "sharpness": 2100.0, "noise": 3.1, "lines": 30, "text_boxes": 84, "text_score": 0.69},
"n_rows": 11, "n_cols": 13,
"row_lines": [[[12, 40], [380, 30]]], "col_lines": [[[15, 42], [20, 300]]],
"cells": [
{"id": 20, "row": 3, "col": 5,
"corners": [[110, 95], [140, 94], [141, 120], [111, 121]], "box": [110, 94, 141, 121],
"row_name": "0-11 months", "col_name": "Tested", "header": false,
"has_text": true, "ink": 0.12, "value": "12", "confidence": 0.91, "flags": []}
],
"seconds": {"detector": 0.42, "gate": 0.01, "grid": 0.04, "ink": 0.01, "read": 0.4, "names": 0.0, "total": 0.88}
}corners are top-left, top-right, bottom-right, bottom-left. row_lines and
col_lines are given by their two ends on the table's borders. A photo that
fails the gate only gets quality and seconds.
Debug images go to results/debug_<function name>/: e.g.
results/debug_find_grid/ has each photo with its grid drawn (detected lines
in green, added lines in blue), and results/debug_extract_table/ adds the
values read.
Setting the gate's thresholds. The thresholds in quality_gate.py are first
guesses. To set them from real photos:
python preprocessing/quality_gate.py data/images --random 500 --quiet --sample 40measures 500 photos picked at random (the same 500 every run) and writesresults/debug_check_quality/to_label.csv: 40 of them, spread from the lowest to the highest text score.- Look at those photos and fill in
readablewith 1 or 0. python preprocessing/quality_gate.py data/images --random 500 --quiet --labels <that csv>prints, for each measure, the threshold that best separates the two groups.
- Patient data: photos, values read from them and results may contain patient information. They stay out of git (except the shared test selection) and shouldn't be sent to online services.
- Earlier experiments: the other scripts in
preprocessing/tried to clean up the photo before finding the table (deskew, colour channel, contrast, deblur, table crop, cell grid). They are kept as a record and are not part of the pipeline; the scripts that compared them are in the git history. - Libraries:
requirements.txtlists what the scripts use. Candidates for later are grouped inpyproject.toml(install one group withpip install --group <name>, pip 25.1 or newer). When a script starts using a new library, also add it torequirements.txt. - Code checks:
ruff check .finds problems, andruff format .fixes the layout.
Commit messages follow Conventional Commits:
type(scope): brief description
- type:
feat,fix,docs,refactor,chore,style,perf,test,build,ciorrevert. A breaking change gets a!before the colon. - scope: the area changed, in short kebab case (e.g.
table-extraction,quality-gate,grid). - description: imperative, lowercase, no full stop at the end.
- Keep it short: the subject line alone, or with one or two short lines under it. No list of changed files.
Example: feat(table-extraction): add quality gate, grid lines and table-to-json extraction
Pull requests:
- Title: same format as a commit message.
- Description: GitHub fills it in from
.github/pull_request_template.md: Summary,
What's in it, Results so far (numbers on the test selection, compared with
before), Known gaps and next steps, How to test, and a check that
docs/next_steps.mdanddocs/architecture.mdare up to date. - No patient data in commits or pull requests: no photos other than the shared test selection, no values read from photos, no results.