Checkbox detection, tested on 768 boxes from IRS forms
99.5%
of scanned boxes right, YOLO at 144 dpi
Render at 144 dpi, not the default 72
| Tool | Scans | Phone photos |
|---|---|---|
| natural-pdf, 144 dpi | 382 | 370 |
| natural-pdf, defaults | 350 | 278 |
| docling, defaults | 163 | 179 |
| Our script (made for these forms) | 375 | 346 |
natural-pdf renders each page at 72 dpi, where an IRS box is about 8 pixels wide. Its auto 2x pass only enlarges them. We tried one other setting:
boxes = page.detect_checkboxes(resolution=144)
At the defaults, it got 90 of 184 checked boxes on photos.
We drew the marks, and we tuned our script on 3 other IRS forms. Its numbers are a best case.
Square digit boxes fool detectors too: natural-pdf and our script took 1040 PIN boxes for check boxes.
Pen marks on photos need the pixels
| Mark | Defaults | 144 dpi |
|---|---|---|
| Typed check (filled-in PDF) | 39 of 70 | 63 of 70 |
| Tick | 28 of 48 | 47 of 48 |
| X | 15 of 44 | 41 of 44 |
| Scribbled in | 8 of 22 | 19 of 22 |
| Empty | 188 of 200 | 200 of 200 |
X marks and scribbles did worst at the defaults. Blur and strokes that cross the border hide a small square. More pixels bring it back.
A free checkbox detector in Python
It flattens a phone photo to the page, keeps long straight lines, and finds small closed squares. A box with 11% or more ink inside counts as checked.
pip install opencv-python-headless numpy
python checkbox.py form.jpg > boxes.csv
Each row is one box: its corners in pixels, checked 1 or 0, and the
ink share. It expects boxes about 8 points wide, like IRS forms. For
other sizes, change BOX.
Show the code (152 lines)
"""Find check boxes on a form image and say if each one is ticked. OpenCV only. Free to use, no warranty.
Brasspage, Nov 2026.
Usage: python checkbox.py form.jpg [more.jpg ...] > boxes.csv
Needs: pip install opencv-python-headless numpy
Output rows: file, x0, y0, x1, y1 (pixels of the input image), checked (1 or 0), ink (0 to 1).
How it works: a phone photo is first flattened to the page (the largest 4-corner shape). Long straight
lines are kept, so pen strokes that cross a box do not hide it. Small closed squares about the size of a
form box are boxes. A box counts as checked when enough ink sits inside it.
"""
import csv
import sys
import cv2
import numpy as np
PAGE_W = 1700 # work at about 200 dpi for a letter page
BOX = (14, 40) # box side in pixels at PAGE_W: 8 pt boxes are about 22
INK = 0.11 # share of dark pixels inside the box that means checked
FULL = 0.4 # a closed square with no hole needs this much ink inside to count as a box
def flatten(gray):
"""Warp a photo to the page. Returns page image and the 3x3 matrix back to the input pixels."""
h, w = gray.shape
b = max(h, w) // 50
edge = np.concatenate(
[gray[:b].ravel(), gray[-b:].ravel(), gray[:, :b].ravel(), gray[:, -b:].ravel()]
)
quad = None
s = 1000 / max(h, w)
small = cv2.GaussianBlur(cv2.resize(gray, None, fx=s, fy=s), (5, 5), 0)
edges = cv2.dilate(cv2.Canny(small, 30, 90), np.ones((3, 3), np.uint8))
cs, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Paper to the edge means a scan: then a big frame printed on the form is not the page.
for c in (
sorted(cs, key=cv2.contourArea, reverse=True)[:5]
if np.median(edge) < 0.8 * np.median(gray)
else []
):
a = cv2.approxPolyDP(cv2.convexHull(c), 0.02 * cv2.arcLength(c, True), True)
_, _, bw, _ = cv2.boundingRect(a)
if (
len(a) == 4
and cv2.contourArea(a) > 0.3 * small.size
and bw < 0.98 * small.shape[1]
):
quad = a.reshape(4, 2).astype(np.float32) / s
break
if quad is None: # the page is the image
k = PAGE_W / w
return cv2.resize(
gray, (PAGE_W, int(h * k)), interpolation=cv2.INTER_AREA
), np.diag([1 / k, 1 / k, 1.0])
sm, df = quad.sum(1), quad[:, 1] - quad[:, 0]
src = np.float32(
[quad[sm.argmin()], quad[df.argmin()], quad[sm.argmax()], quad[df.argmax()]]
)
ph = int(PAGE_W * np.linalg.norm(src[3] - src[0]) / np.linalg.norm(src[1] - src[0]))
dst = np.float32([[0, 0], [PAGE_W, 0], [PAGE_W, ph], [0, ph]])
M = cv2.getPerspectiveTransform(src, dst)
return cv2.warpPerspective(
gray, M, (PAGE_W, ph), flags=cv2.INTER_AREA
), np.linalg.inv(M)
def boxes(page):
"""Boxes on the flat page: [(x0, y0, x1, y1, ink)]."""
ink = cv2.adaptiveThreshold(
page, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 31, 12
)
k = 17 # a line must run this far; most pen strokes and letter parts do not
lines = cv2.morphologyEx(
ink, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_RECT, (k, 1))
)
lines |= cv2.morphologyEx(
ink, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_RECT, (1, k))
)
cs, tree = cv2.findContours(lines, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
found = []
for c, (_, _, _, parent) in zip(cs, tree[0] if cs else []):
x, y, w, h = cv2.boundingRect(c)
if not (BOX[0] <= w <= BOX[1] and BOX[0] <= h <= BOX[1] and 0.8 < w / h < 1.25):
continue
# A hole (the white inside of a drawn square) must be square: a round hole (O, D, 0) is a letter.
# An outline with no hole counts only if it is square and full of ink: a box scribbled over.
if cv2.contourArea(c) < 0.85 * w * h:
continue
if parent != -1:
x, y, w, h = (
max(0, x - 2),
max(0, y - 2),
w + 4,
h + 4,
) # the hole plus the printed border
# A box has all 4 sides drawn: check each edge strip of the line mask.
t = max(2, w // 8)
sides = [
lines[y : y + t, x : x + w],
lines[y + h - t : y + h, x : x + w],
lines[y : y + h, x : x + t],
lines[y : y + h, x + w - t : x + w],
]
if (
min((s.max(axis=0 if i < 2 else 1) > 0).mean() for i, s in enumerate(sides))
< 0.8
):
continue
m = max(3, w // 5) # stay off the printed border
share = float((ink[y + m : y + h - m, x + m : x + w - m] > 0).mean())
if parent == -1 and share < FULL:
continue
found.append([x, y, x + w, y + h, share])
found.sort(key=lambda b: -(b[2] - b[0]))
keep = [] # the inner and outer edge of one box are one box
for b in found:
if all(
min(b[2], k[2]) - max(b[0], k[0]) < 0.5 * (b[2] - b[0])
or min(b[3], k[3]) - max(b[1], k[1]) < 0.5 * (b[3] - b[1])
for k in keep
):
keep.append(b)
return keep
def read(path):
gray = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
if gray is None:
raise ValueError(f"{path}: not an image I can read")
page, back = flatten(gray)
out = []
for x0, y0, x1, y1, ink in boxes(page):
p = cv2.perspectiveTransform(np.float32([[[x0, y0]], [[x1, y1]]]), back)[:, 0]
out.append(
[
*np.round(p.min(0)).astype(int),
*np.round(p.max(0)).astype(int),
int(ink >= INK),
round(ink, 3),
]
)
return out
if __name__ == "__main__":
w = csv.writer(sys.stdout)
w.writerow(["file", "x0", "y0", "x1", "y1", "checked", "ink"])
for f in sys.argv[1:]:
for row in read(f):
w.writerow([f, *row])
docling marks the label, not the box
docling's layout model has two check box labels, selected and unselected. In Markdown, a box becomes a list item with its words:
- [ ] Individual/sole proprietor
- [ ] C corporation
- [x] M S corporation
- [x] Partnership
- [x] Trust/estate
It did best on the SS-4: 111 of 132 boxes right from scans. It found none on 1040 page 2 or the 8822, and took about 20 seconds a page on our Mac.
Fillable PDF? Read the field instead
A fillable PDF stores each answer, so no detector is needed. pypdf reads it:
from pypdf import PdfReader
for name, field in PdfReader("form.pdf").get_fields().items():
if field.get("/FT") == "/Btn":
print(name, field.get("/V"))
/Off is empty. A checked box reads its own on name: the
seven W-9 line 3a boxes read /1 to /7. Names
are long field names that end in c1_1[3], not the words
you see. A printed and scanned form has no fields.
OCR reads the words, not the marks
We ran our pdf-ocr Actor's code on the 15 scans. On this W-9, S corporation, Partnership and Trust/estate were checked:
[_] Individual/sole proprietor EB C corporation E# S corporation r= Partnership BB Trust/estate
The labels came through. The boxes became signs, and empty and checked ones look alike. Use a box detector for the marks.
Paid cloud tools that read check boxes
| Service | Price |
|---|---|
| AWS Textract, Forms | $50 |
| Google Document AI, Form Parser | $30 |
| Azure Document Intelligence, Layout | $10 |
All three return a selected or not selected state. We did not test them. Apple Vision on macOS 26 has no check box output.
Sources
- wendys-llc/checkbox-detector (the natural-pdf model, Apache-2.0)
-
docling-core Markdown serializer
(the
- [x]lines) - Textract selection elements and pricing
- Document AI Form Parser and pricing
- Azure Layout model and pricing
- Apple Vision DocumentObservation.Container
How we tested
- Real fillable IRS forms from irs.gov: W-9, SS-4, 1040 (2025) pages 1 and 2, and 8822. 128 check boxes a set, each page filled 3 times. US government forms carry no copyright.
- Each box left empty, or given a typed check (the PDF's own mark), a pen X, a tick, or a scribble. 184 checked and 200 empty boxes in each set of 15 pages.
- Each page as a gray scan (turned up to 0.8 degrees, noise) and as a simulated phone photo (on a desk, tilted, uneven light, blur), 3024 by 4032. Not real photos.
- A box counts as right when a tool finds it and says checked or empty right. docling marks the box with its label, so a docling item counts when it starts at the box.
-
natural-pdf 0.7.0,
detect_checkboxes()with its defaults, then once withresolution=144, the only other setting we tried. Each image went in a one-page PDF 8.5 inches wide. docling 2.150.1 with its defaults. - Our script: settings picked on W-4, 8822-B and 4506-T pages, never on the test forms. After its first test run we fixed one bug: on scans it took a big printed frame for the page edge.
- Our Actor's code at commit 46586e16 (Nov 17), with its default settings, on the 15 scans. Mac with Apple M5 Max, macOS 26.6.
Printed forms and scans, no install
Run it yourself. Our Apify Actor turns scanned PDFs and images into Markdown. $0.006 a scanned page. It reads printed words, not check marks.
Or send us the scan. Tack, our AI, does the job for $29, up to 50 pages. First page free.
Questions people ask
What is the best free checkbox detection model?
In our test, the YOLO12n model in natural-pdf (Apache-2.0), run at 144 dpi, read 382 of 384 boxes right from scans and 370 from phone photos. docling read 163 and 179.
Can OpenCV detect checkboxes?
Yes. Our free script keeps long straight lines, finds small squares and counts the ink inside. It read 375 of 384 boxes right from our scans, tuned on 3 other forms.
Can OCR detect checkboxes?
Not well. Our OCR Actor read the labels, but the boxes came out as signs such as [_], EB and r=, and empty and checked boxes looked alike.
How do I read checkboxes from a fillable PDF?
Read the form fields with pypdf. An empty box reads /Off, and a checked box reads its own on name: /1 to /7 on the W-9 line 3a boxes. A printed and scanned form has no fields.
Why does checkbox detection miss marks on photos?
At 72 dpi a form box is about 8 pixels, and blur and pen strokes hide it. On our photos, natural-pdf read 15 of 44 X marks right at 72 dpi and 41 at 144.
Related guides
- Signature detection in Python: 3 free tools on IRS forms
- Free OMR software: bubble sheet scanners tested on 20 sheets
- Docling OCR engines: EasyOCR vs Tesseract vs RapidOCR
- OpenCV OCR in Python: text detection and recognition, tested
- Photo to Excel: free table OCR tested on 12 phone photos
- Free zonal OCR in Python: 7 ways tested on 24 filled forms