File size: 3,288 Bytes
24aaa76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Test pass 2: page list and 1280 px detector copies of the Kazakh real-document benchmark, handwritten config (150 pages).
Reads data.csv (columns image_path, text; UTF-8, every field quoted) as data with the csv module. The reference text of each page is
written verbatim to refs/<id>.txt for the scorer; it is not printed. Pages as a viewer shows them (tp2_tob_img.load_page), resized to
a long side of 1280 px exactly as tp2_tob_prep.py (cv2 INTER_AREA when shrinking, INTER_LINEAR when enlarging), JPEG q95.

usage: tp2_kzb_prep.py --src DATA/data/raw/kz_benchmark_hw --outdir DIR
"""
import argparse
import collections
import csv
import json
import os
import sys
import time

import cv2
import numpy as np

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import tp2_tob_img as ti  # noqa: E402

csv.field_size_limit(1 << 30)
COLS = ["id", "kategori", "belge", "lisans", "image_orig", "image_1280", "width", "height", "scale", "exif_orientation", "ref_md"]
ap = argparse.ArgumentParser()
ap.add_argument("--src", required=True)
ap.add_argument("--outdir", required=True)
a = ap.parse_args()
t0 = time.time()
base = os.path.join(a.src, "real_handwritten_data")
os.makedirs(os.path.join(a.outdir, "refs"), exist_ok=True)
rows = []
orient = collections.Counter()
modes = collections.Counter()
with open(os.path.join(base, "data.csv"), encoding="utf-8", newline="") as f:
    for r in csv.DictReader(f):
        rel = r["image_path"]
        assert rel.startswith("images/") and ".." not in rel, rel
        pid = os.path.splitext(os.path.basename(rel))[0]
        src = os.path.join(base, rel)
        from PIL import Image
        with Image.open(src) as im0:
            modes[im0.format + ":" + im0.mode] += 1
        im, ori = ti.load_page(src)
        W, H = im.size
        s = ti.MAX_SIDE / float(max(W, H))
        nw, nh = int(round(W * s)), int(round(H * s))
        arr = cv2.cvtColor(np.asarray(im), cv2.COLOR_RGB2BGR)
        small = cv2.resize(arr, (nw, nh), interpolation=cv2.INTER_AREA if s < 1 else cv2.INTER_LINEAR)
        dst = os.path.join(a.outdir, "pages_1280", pid + ".jpg")
        os.makedirs(os.path.dirname(dst), exist_ok=True)
        cv2.imwrite(dst, small, [cv2.IMWRITE_JPEG_QUALITY, 95])
        ref = os.path.join(a.outdir, "refs", pid + ".txt")
        open(ref, "w", encoding="utf-8").write(r["text"])
        rows.append({"id": pid, "kategori": "kz_hw", "belge": pid, "lisans": "", "image_orig": src, "image_1280": dst, "width": W,
                     "height": H, "scale": "%.6f" % s, "exif_orientation": ori, "ref_md": ref})
        orient[ori] += 1
with open(os.path.join(a.outdir, "pages_kzb.tsv"), "w", encoding="utf-8") as f:
    f.write("\t".join(COLS) + "\n")
    for r in rows:
        f.write("\t".join(str(r[c]).replace("\t", " ").replace("\n", " ") for c in COLS) + "\n")
info = {"pages": len(rows), "exif_orientation": {str(k): v for k, v in orient.items()}, "format_mode": dict(modes),
        "size_min": min((r["width"] * r["height"], r["width"], r["height"]) for r in rows)[1:],
        "size_max": max((r["width"] * r["height"], r["width"], r["height"]) for r in rows)[1:], "seconds": round(time.time() - t0, 1)}
json.dump(info, open(os.path.join(a.outdir, "kzb_prep.json"), "w"), indent=1)
print(json.dumps(info))