File size: 16,520 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 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 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 | """Detector data: pages resized to a long side of 1280 px, line boxes and polygons, baselines, YOLO label files, page index TSVs.
school_notebooks_ru (MIT licence, COCO annotations). Finding from an overlay of one val page: the polygons of the category
text_line are thin traces along each written line (about 1-3 px high), not line areas. The word polygons (categories
pupil_text, pupil_comment, teacher_comment) carry the text. So a text line is built here as follows:
- the trace gives the line's baseline (centre line of the thin polygon);
- every word is assigned to the trace that passes closest to the word's centre (distance below 0.7 word height, at least
6 px; the trace must cover the word's x position within 70 px, its end heights are extended flat);
- the line polygon is the convex hull of its words and its trace, the line box its bounds;
- words with no trace nearby are grouped into extra lines by vertical proximity (baseline = straight line at 25 % above the
bottom of the words);
- traces without words are dropped (counted in the log).
Reference page text of a page = line texts (words sorted left to right) with lines sorted top to bottom. Test pages are never read.
Usage: python -m linedet.det_prep school --out <root> ; python -m linedet.det_prep pagexml --pages <tsv> --out <dir>
"""
import argparse
import json
import multiprocessing as mp
import os
import zipfile
import cv2
import numpy as np
from .common import DATA, write_tsv
SCHOOL = DATA + "/data/raw/school_notebooks_ru"
MAX_SIDE = 1280
_zip = None
_NAMES_LOWER = {}
def _init_zip():
global _zip
_zip = zipfile.ZipFile(SCHOOL + "/images.zip")
def _load(split, fname):
if split == "train":
real = _NAMES_LOWER.get(("images/" + fname).lower())
if real is None:
return None
buf = np.frombuffer(_zip.read(real), dtype=np.uint8)
return cv2.imdecode(buf, cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION)
return cv2.imread("%s/val_test_images/%s/%s" % (SCHOOL, split, fname), cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION)
def _poly(seg):
return np.array(seg[0], dtype=np.float64).reshape(-1, 2)
def baseline_from_polygon(poly, n=9):
"""Baseline of a line polygon: principal axis of the polygon, then in the rotated frame the point 25 % above the bottom
edge of the polygon at n positions along the axis. For the thin school traces this is their centre line. Returns [[x, y]]
from left to right in the original frame."""
from shapely.geometry import LineString, Polygon
p = np.asarray(poly, dtype=np.float64)
if len(p) < 3:
(xa, ya), (xb, yb) = p.min(0), p.max(0)
return [[float(xa), float((ya + yb) / 2)], [float(xb), float((ya + yb) / 2)]]
c = p.mean(0)
u, s, vt = np.linalg.svd(p - c, full_matrices=False)
ax = vt[0]
if ax[0] < 0:
ax = -ax
ang = float(np.clip(np.arctan2(ax[1], ax[0]), -np.pi / 4, np.pi / 4))
cs, sn = np.cos(ang), np.sin(ang)
R = np.array([[cs, sn], [-sn, cs]])
q = (p - c) @ R.T
try:
pg = Polygon(q).buffer(0)
except Exception:
pg = None
x0, x1 = q[:, 0].min(), q[:, 0].max()
pts = []
if pg is None or pg.is_empty:
yb = (q[:, 1].max() + q[:, 1].min()) / 2
return (np.array([(x0, yb), (x1, yb)]) @ R + c).round(1).tolist()
for x in np.linspace(x0 + 0.04 * (x1 - x0), x1 - 0.04 * (x1 - x0), n):
seg = pg.intersection(LineString([(x, q[:, 1].min() - 5), (x, q[:, 1].max() + 5)]))
if seg.is_empty:
continue
b = seg.bounds
pts.append((x, b[3] - 0.25 * (b[3] - b[1])))
if len(pts) < 2:
yb = q[:, 1].max() - 0.25 * (q[:, 1].max() - q[:, 1].min())
pts = [(x0, yb), (x1, yb)]
return (np.array(pts) @ R + c).round(1).tolist()
def build_lines(traces, words):
"""traces: list of polygons (N,2) in page pixels. words: list of (polygon (N,2), text). Returns list of dicts
{poly, baseline, words:[(x0, text)], y} and counts."""
from shapely.geometry import MultiPoint
traces = [t for t in traces if len(t) >= 3]
bls = [np.array(baseline_from_polygon(t)) for t in traces]
assigned = [[] for _ in traces]
loose = []
for wp, text in words:
x0, y0 = wp.min(0)
x1, y1 = wp.max(0)
cx, cy, h = (x0 + x1) / 2, (y0 + y1) / 2, max(y1 - y0, 1.0)
best, bd = None, 1e9
for j, bl in enumerate(bls):
if cx < bl[0, 0] - 70 or cx > bl[-1, 0] + 70:
continue
d = abs(cy - float(np.interp(cx, bl[:, 0], bl[:, 1])))
if d < bd:
best, bd = j, d
if best is not None and bd < max(0.7 * h, 6.0):
assigned[best].append((wp, text))
else:
loose.append((wp, text, cx, cy, h, x0))
lines = []
empty = 0
for j, ws in enumerate(assigned):
if not ws:
empty += 1
continue
pts = np.concatenate([w[0] for w in ws] + [np.array(traces[j])])
hull = MultiPoint(pts.tolist()).convex_hull
if hull.geom_type != "Polygon":
xa, ya = pts.min(0)
xb, yb = pts.max(0)
poly = np.array([[xa, ya], [xb, ya], [xb, yb], [xa, yb]])
else:
poly = np.array(hull.exterior.coords)[:-1]
lines.append({"poly": poly, "baseline": bls[j], "words": sorted([(float(w[0][:, 0].min()), w[1]) for w in ws]),
"y": float(bls[j][:, 1].mean())})
# loose words: vertical clusters
loose.sort(key=lambda r: r[3])
clusters = []
for r in sorted(loose, key=lambda r: (r[3], r[5])):
placed = False
for cl in clusters[::-1][:6]:
same_row = abs(r[3] - np.mean([q[3] for q in cl])) < 0.6 * r[4]
xs1 = max(q[0][:, 0].max() for q in cl)
xs0 = min(q[0][:, 0].min() for q in cl)
near = (r[5] - xs1) < 4.0 * r[4] and (xs0 - r[0][:, 0].max()) < 4.0 * r[4]
if same_row and near:
cl.append(r)
placed = True
break
if not placed:
clusters.append([r])
for cl in clusters:
pts = np.concatenate([q[0] for q in cl])
hull = MultiPoint(pts.tolist()).convex_hull
if hull.geom_type != "Polygon":
continue
poly = np.array(hull.exterior.coords)[:-1]
xs0, xs1 = pts[:, 0].min(), pts[:, 0].max()
yb = pts[:, 1].max() - 0.25 * (pts[:, 1].max() - pts[:, 1].min())
lines.append({"poly": poly, "baseline": np.array([[xs0, yb], [xs1, yb]]), "words": sorted([(float(q[5]), q[1]) for q in cl]),
"y": float(yb)})
return lines, {"traces": len(traces), "traces_without_words": empty, "loose_word_lines": len(clusters), "loose_words": len(loose)}
def _work(args):
split, img, traces_p, words_p, out_root = args
im = _load(split, img["file_name"])
if im is None:
return {"id": img["id"], "error": "image not found: " + img["file_name"]}
h, w = im.shape[:2]
note = "" if (w, h) == (img["width"], img["height"]) else "size mismatch: image %dx%d annotation %dx%d" % (w, h, img["width"], img["height"])
s = MAX_SIDE / float(max(w, h))
nw, nh = int(round(w * s)), int(round(h * s))
im2 = cv2.resize(im, (nw, nh), interpolation=cv2.INTER_AREA)
pid = "school_%s_%d" % (split, img["id"])
ip = "%s/%s/images/%s.jpg" % (out_root, split, pid)
os.makedirs(os.path.dirname(ip), exist_ok=True)
cv2.imwrite(ip, im2, [cv2.IMWRITE_JPEG_QUALITY, 90])
traces = [_poly(p) * s for p in traces_p]
words = [(_poly_list(p) * s, t) for p, t in words_p]
lines, stats = build_lines(traces, words)
lines.sort(key=lambda L: L["y"])
boxes = []
for L in lines:
x0, y0 = L["poly"].min(0)
x1, y1 = L["poly"].max(0)
boxes.append([float(max(x0, 0)), float(max(y0, 0)), float(min(x1, nw)), float(min(y1, nh))])
lp = "%s/%s/labels/%s.txt" % (out_root, split, pid)
os.makedirs(os.path.dirname(lp), exist_ok=True)
with open(lp, "w") as f:
for x0, y0, x1, y1 in boxes:
if x1 - x0 < 4 or y1 - y0 < 4:
continue
f.write("0 %.6f %.6f %.6f %.6f\n" % ((x0 + x1) / 2 / nw, (y0 + y1) / 2 / nh, (x1 - x0) / nw, (y1 - y0) / nh))
ref_lines = [" ".join(t for _, t in L["words"]) for L in lines]
return {"id": pid, "image": ip, "width": nw, "height": nh, "scale": s, "boxes": boxes, "polys": [L["poly"].round(1).tolist() for L in lines],
"baselines": [L["baseline"].round(1).tolist() for L in lines], "ref_lines": ref_lines, "note": note, "stats": stats}
def _poly_list(p):
return np.array(p, dtype=np.float64).reshape(-1, 2)
def run_school(out_root, workers):
global _NAMES_LOWER
z = zipfile.ZipFile(SCHOOL + "/images.zip")
_NAMES_LOWER = {n.lower(): n for n in z.namelist() if not n.startswith("__MACOSX")}
z.close()
summary = {}
for split in ("train", "val"):
d = json.load(open("%s/annotations_%s.json" % (SCHOOL, split), encoding="utf-8"))
cats = {c["id"]: c["name"] for c in d["categories"]}
traces, words = {}, {}
for a in d["annotations"]:
cn = cats[a["category_id"]]
if cn == "text_line":
traces.setdefault(a["image_id"], []).append(a["segmentation"])
elif cn in ("pupil_text", "pupil_comment", "teacher_comment"):
tr = (a.get("attributes") or {}).get("translation")
if tr:
words.setdefault(a["image_id"], []).append((_poly(a["segmentation"]).tolist(), tr))
jobs = [(split, im, traces.get(im["id"], []), words.get(im["id"], []), out_root) for im in d["images"]]
with mp.Pool(workers, initializer=_init_zip) as pool:
res = pool.map(_work, jobs, chunksize=4)
ok = [r for r in res if "error" not in r]
err = [r for r in res if "error" in r]
rows = [(r["id"], r["image"], r["width"], r["height"], "%.6f" % r["scale"], len(r["boxes"]), json.dumps(r["boxes"]), json.dumps(r["polys"]),
json.dumps(r["baselines"]), json.dumps(r["ref_lines"], ensure_ascii=False), r["note"]) for r in ok]
write_tsv("%s/pages_school_%s.tsv" % (out_root, split),
["id", "image", "width", "height", "scale", "n_lines", "boxes_json", "polys_json", "baselines_json", "ref_lines_json", "note"], rows)
tot = {k: sum(r["stats"][k] for r in ok) for k in ("traces", "traces_without_words", "loose_word_lines", "loose_words")}
summary[split] = {"pages": len(ok), "errors": len(err), "size_mismatch_notes": sum(1 for r in ok if r["note"]), "lines_kept": sum(len(r["boxes"]) for r in ok), **tot}
print(split, summary[split], flush=True)
for r in err[:5]:
print(r)
json.dump(summary, open(out_root + "/school_build_summary.json", "w"), indent=1)
# ---------------------------------------------------------------------------------------------------- generator pages
def _gen_work(args):
jp, split, out_root = args
try:
d = json.load(open(jp, encoding="utf-8"))
except Exception as e:
return {"error": "bad json %s: %s" % (jp, e)}
ip0 = jp[:-5] + ".jpg"
if not os.path.exists(ip0):
return {"error": "no image for " + jp}
im = cv2.imread(ip0, cv2.IMREAD_COLOR)
h, w = im.shape[:2]
s = MAX_SIDE / float(max(w, h))
nw, nh = int(round(w * s)), int(round(h * s))
im2 = cv2.resize(im, (nw, nh), interpolation=cv2.INTER_AREA if s < 1 else cv2.INTER_LINEAR)
pid = os.path.basename(jp)[:-5]
ip = "%s/%s/images/%s.jpg" % (out_root, split, pid)
os.makedirs(os.path.dirname(ip), exist_ok=True)
cv2.imwrite(ip, im2, [cv2.IMWRITE_JPEG_QUALITY, 90])
lines = sorted(d.get("lines", []), key=lambda L: L.get("reading_order", 0))
boxes, polys, bls, texts = [], [], [], []
for L in lines:
if not L.get("box") or not L.get("polygon") or not L.get("baseline"):
continue
x0, y0, x1, y1 = [float(v) * s for v in L["box"]]
boxes.append([x0, y0, x1, y1])
polys.append((np.array(L["polygon"], dtype=np.float64) * s).round(1).tolist())
bls.append((np.array(L["baseline"], dtype=np.float64) * s).round(1).tolist())
texts.append(L.get("text") or "")
lp = "%s/%s/labels/%s.txt" % (out_root, split, pid)
os.makedirs(os.path.dirname(lp), exist_ok=True)
with open(lp, "w") as f:
for x0, y0, x1, y1 in boxes:
x0, y0, x1, y1 = max(x0, 0), max(y0, 0), min(x1, nw), min(y1, nh)
if x1 - x0 < 4 or y1 - y0 < 4:
continue
f.write("0 %.6f %.6f %.6f %.6f\n" % ((x0 + x1) / 2 / nw, (y0 + y1) / 2 / nh, (x1 - x0) / nw, (y1 - y0) / nh))
return {"id": pid, "image": ip, "width": nw, "height": nh, "scale": s, "boxes": boxes, "polys": polys, "baselines": bls, "ref_lines": texts,
"page_type": d.get("info", {}).get("page_type", ""), "language": d.get("language", ""), "note": ""}
def run_gen(split, out_root, workers, limit=0):
import glob
jps = sorted(glob.glob("%s/data/processed/r5/synth/pages/%s/*/*.json" % (DATA, split)))
if limit:
jps = jps[:limit]
with mp.Pool(workers) as pool:
res = pool.map(_gen_work, [(j, split, out_root) for j in jps], chunksize=4)
ok = [r for r in res if "error" not in r]
err = [r for r in res if "error" in r]
rows = [(r["id"], r["image"], r["width"], r["height"], "%.6f" % r["scale"], len(r["boxes"]), json.dumps(r["boxes"]), json.dumps(r["polys"]),
json.dumps(r["baselines"]), json.dumps(r["ref_lines"], ensure_ascii=False), r["note"]) for r in ok]
write_tsv("%s/pages_gen_%s.tsv" % (out_root, split),
["id", "image", "width", "height", "scale", "n_lines", "boxes_json", "polys_json", "baselines_json", "ref_lines_json", "note"], rows)
print(split, "pages", len(ok), "errors", len(err), "lines", sum(len(r["boxes"]) for r in ok), flush=True)
for r in err[:5]:
print(r)
def write_pagexml(path, image_path, w, h, lines):
"""lines: list of (polygon [[x,y]..], baseline [[x,y]..]). One TextRegion covers the page."""
def pts(a):
return " ".join("%d,%d" % (round(x), round(y)) for x, y in a)
out = ['<?xml version="1.0" encoding="UTF-8"?>',
'<PcGts xmlns="http://schema.primaresearch.org/PAGE/gts/pagecontent/2013-07-15">',
'<Page imageFilename="%s" imageWidth="%d" imageHeight="%d">' % (image_path, w, h),
'<TextRegion id="r0"><Coords points="0,0 %d,0 %d,%d 0,%d"/>' % (w, w, h, h)]
for i, (poly, bl) in enumerate(lines):
out.append('<TextLine id="l%d"><Baseline points="%s"/><Coords points="%s"/></TextLine>' % (i, pts(bl), pts(poly)))
out.append("</TextRegion></Page></PcGts>")
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
f.write("\n".join(out))
def _xml_job(a):
pid, image, w, h, polys, bls, out_dir = a
lines = [(p, b) for p, b in zip(polys, bls) if len(p) >= 3 and len(b) >= 2]
p = "%s/%s.xml" % (out_dir, pid)
write_pagexml(p, image, w, h, lines)
return p
def run_pagexml(pages_tsv, out_dir, workers):
from .common import read_manifest
rows = read_manifest(pages_tsv)
jobs = [(r["id"], r["image"], int(r["width"]), int(r["height"]), json.loads(r["polys_json"]), json.loads(r["baselines_json"]), out_dir) for r in rows]
with mp.Pool(workers) as pool:
paths = pool.map(_xml_job, jobs, chunksize=8)
with open(out_dir + "/list.txt", "w") as f:
f.write("\n".join(paths) + "\n")
print("wrote", len(paths), "PageXML files to", out_dir)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("what", choices=["school", "pagexml", "gen"])
ap.add_argument("--split", default="train")
ap.add_argument("--limit", type=int, default=0)
ap.add_argument("--out", default=DATA + "/data/processed/r5_linedet_det/school2")
ap.add_argument("--pages", default="")
ap.add_argument("--workers", type=int, default=12)
a = ap.parse_args()
if a.what == "school":
run_school(a.out, a.workers)
elif a.what == "pagexml":
run_pagexml(a.pages, a.out, a.workers)
elif a.what == "gen":
run_gen(a.split, a.out if a.out != DATA + "/data/processed/r5_linedet_det/school2" else DATA + "/data/processed/r5_linedet_det/gen", a.workers, a.limit)
if __name__ == "__main__":
main()
|