Image Classification
ONNX
onnxruntime
document-orientation
deskew
ocr
image-preprocessing
cpu
File size: 3,025 Bytes
9614d3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
"""Evaluate all four turns of each sampled scan, with or without injected tilt."""

import argparse
from concurrent.futures import ThreadPoolExecutor
import hashlib
import json
from pathlib import Path
import sys
import threading

import numpy as np
from PIL import Image

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from folio_orient import PageOrienter, transpose_cw

HERE = Path(__file__).resolve().parent


def run(args):
    rows = json.loads((HERE / "pages.json").read_text())
    jobs = [
        (r, tilt, k)
        for r in rows
        if args.split in ("both", r["split"])
        for tilt in (False, True)
        for k in range(4)
    ]
    local = threading.local()

    def evaluate(job):
        row, tilted, k = job
        if not hasattr(local, "model"):
            local.model = PageOrienter(args.model)
        im = Image.open(args.pages / row["file"]).convert("L")
        seed = int.from_bytes(hashlib.sha256(row["file"].encode()).digest()[:4], "big")
        tilt = (1.5 + seed % 550 / 100) * (-1 if seed % 2 else 1) if tilted else 0.0
        if tilt:
            im = im.rotate(
                tilt,
                Image.Resampling.BICUBIC,
                expand=False,
                fillcolor=im.getpixel((0, 0)),
            )
        im = transpose_cw(im, (-90 * k) % 360)
        result = local.model.estimate(im, deskew=False)
        return dict(
            file=row["file"],
            book=row["book"],
            page_type=row["page_type"],
            split=row["split"],
            target_cw=90 * k,
            tilt_ccw=tilt,
            **result
        )

    with ThreadPoolExecutor(args.workers) as pool:
        predictions = list(pool.map(evaluate, jobs))
    args.output.write_text(json.dumps(predictions, indent=1) + "\n")
    for split in ("dev", "test"):
        for kind in ("print", "plate_or_cover", "blank_or_showthrough"):
            for tilted in (False, True):
                subset = [
                    r
                    for r in predictions
                    if r["split"] == split
                    and r["page_type"] == kind
                    and bool(r["tilt_ccw"]) == tilted
                ]
                if not subset:
                    continue
                correct = sum(r["target_cw"] == r["quarter_turn_cw"] for r in subset)
                abstain = sum(r["quarter_turn_cw"] is None for r in subset)
                print(
                    split,
                    kind,
                    "tilted" if tilted else "clean",
                    len(subset),
                    correct,
                    abstain,
                    flush=True,
                )


if __name__ == "__main__":
    p = argparse.ArgumentParser()
    p.add_argument("pages", type=Path)
    p.add_argument("model", type=Path)
    p.add_argument("output", type=Path)
    p.add_argument("--workers", type=int, default=2)
    p.add_argument("--split", choices=["dev", "test", "both"], default="both")
    run(p.parse_args())