Add training-kit/segment_ppocr_lines.py
Browse files
training-kit/segment_ppocr_lines.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Split long RTL OCR lines into CTC-safe Persian word-group crops."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import cv2
|
| 10 |
+
import numpy as np
|
| 11 |
+
from PIL import Image
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def zero_runs(mask: np.ndarray) -> list[tuple[int, int]]:
|
| 15 |
+
runs = []
|
| 16 |
+
start = None
|
| 17 |
+
for index, value in enumerate(mask.tolist() + [False]):
|
| 18 |
+
if value and start is None:
|
| 19 |
+
start = index
|
| 20 |
+
elif not value and start is not None:
|
| 21 |
+
runs.append((start, index))
|
| 22 |
+
start = None
|
| 23 |
+
return runs
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def word_intervals(image: Image.Image, count: int) -> list[tuple[int, int]] | None:
|
| 27 |
+
if count == 1:
|
| 28 |
+
return [(0, image.width)]
|
| 29 |
+
gray = np.asarray(image.convert("L"))
|
| 30 |
+
_, ink = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
|
| 31 |
+
projection = (ink > 0).sum(axis=0)
|
| 32 |
+
active = np.flatnonzero(projection > max(1, image.height // 80))
|
| 33 |
+
if active.size == 0:
|
| 34 |
+
return None
|
| 35 |
+
left, right = int(active[0]), int(active[-1]) + 1
|
| 36 |
+
gaps = [
|
| 37 |
+
(a, b) for a, b in zero_runs(projection[left:right] <= max(1, image.height // 100))
|
| 38 |
+
if b - a >= 2 and a > 0 and b < right - left
|
| 39 |
+
]
|
| 40 |
+
if len(gaps) < count - 1:
|
| 41 |
+
return None
|
| 42 |
+
chosen = sorted(
|
| 43 |
+
((a + left, b + left) for a, b in sorted(gaps, key=lambda run: run[1] - run[0], reverse=True)[: count - 1]),
|
| 44 |
+
key=lambda run: run[0],
|
| 45 |
+
)
|
| 46 |
+
cuts = [left] + [(a + b) // 2 for a, b in chosen] + [right]
|
| 47 |
+
intervals = [(cuts[i], cuts[i + 1]) for i in range(len(cuts) - 1)]
|
| 48 |
+
return list(reversed(intervals))
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def groups(words: list[str], intervals: list[tuple[int, int]], max_chars: int):
|
| 52 |
+
current_words: list[str] = []
|
| 53 |
+
current_boxes: list[tuple[int, int]] = []
|
| 54 |
+
for word, box in zip(words, intervals):
|
| 55 |
+
candidate = " ".join(current_words + [word])
|
| 56 |
+
if current_words and len(candidate) > max_chars:
|
| 57 |
+
yield " ".join(current_words), current_boxes
|
| 58 |
+
current_words, current_boxes = [], []
|
| 59 |
+
if len(word) > max_chars:
|
| 60 |
+
return
|
| 61 |
+
current_words.append(word)
|
| 62 |
+
current_boxes.append(box)
|
| 63 |
+
if current_words:
|
| 64 |
+
yield " ".join(current_words), current_boxes
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def process_list(source: Path, destination: Path, image_dir: Path, root: Path, max_chars: int) -> tuple[int, int]:
|
| 68 |
+
output = []
|
| 69 |
+
rejected = 0
|
| 70 |
+
for line_index, raw in enumerate(source.read_text(encoding="utf-8").splitlines()):
|
| 71 |
+
relative, text = raw.split("\t", 1)
|
| 72 |
+
words = text.split()
|
| 73 |
+
with Image.open(root / relative) as opened:
|
| 74 |
+
image = opened.convert("RGB")
|
| 75 |
+
intervals = word_intervals(image, len(words))
|
| 76 |
+
if intervals is None:
|
| 77 |
+
rejected += 1
|
| 78 |
+
continue
|
| 79 |
+
for group_index, (label, boxes) in enumerate(groups(words, intervals, max_chars)):
|
| 80 |
+
x0 = max(0, min(x[0] for x in boxes) - 3)
|
| 81 |
+
x1 = min(image.width, max(x[1] for x in boxes) + 3)
|
| 82 |
+
crop = image.crop((x0, 0, x1, image.height))
|
| 83 |
+
path = image_dir / f"{line_index:07d}-{group_index:03d}.png"
|
| 84 |
+
crop.save(path)
|
| 85 |
+
output.append(f"{path.relative_to(root)}\t{label}")
|
| 86 |
+
destination.write_text("\n".join(output) + "\n", encoding="utf-8")
|
| 87 |
+
return len(output), rejected
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def main() -> None:
|
| 91 |
+
parser = argparse.ArgumentParser()
|
| 92 |
+
parser.add_argument("--data-root", type=Path, required=True)
|
| 93 |
+
parser.add_argument("--pilot-dir", type=Path, required=True)
|
| 94 |
+
parser.add_argument("--max-chars", type=int, default=25)
|
| 95 |
+
args = parser.parse_args()
|
| 96 |
+
for split in ("train", "val"):
|
| 97 |
+
image_dir = args.pilot_dir / "images" / f"segments-{split}"
|
| 98 |
+
image_dir.mkdir(parents=True, exist_ok=True)
|
| 99 |
+
kept, rejected = process_list(
|
| 100 |
+
args.pilot_dir / f"{split}_list.txt",
|
| 101 |
+
args.pilot_dir / f"{split}_segments.txt",
|
| 102 |
+
image_dir,
|
| 103 |
+
args.data_root,
|
| 104 |
+
args.max_chars,
|
| 105 |
+
)
|
| 106 |
+
print(f"{split}: segments={kept} rejected_lines={rejected}")
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
if __name__ == "__main__":
|
| 110 |
+
main()
|