Bug: Default direction classifier rotates long upright lines by 180° (2 to 3 % of the words of a document)
TL;DR: with default settings, some long upright lines are rotated by the direction classifier and come out as garbage. On two English articles this costs 2 to 3 % of the words. The classifier squeezes every line to 192x48 px, so on a long line it has nothing to read. Giving it the middle of the line instead fixes it (diff below).
use_cls=False: 'message fatigue and (mis)perceptions that messages were only for'
default : 'm ms ss s smss mng mssnr'
This follows #409 and #436, where a lost line was traced to a wrong direction call and use_cls=False was the advice.
Cause. TextClassifier.resize_norm_img resizes a line to 48 px high and at most 192 px wide. A line of body text is about 30 times wider than high, so it gets squeezed 7.5 times and the verdict is close to random. Above cls_thresh the line is rotated and read upside down. It goes both ways: long lines that really are upside down are often missed too (second column below).
Numbers. RapidOCR() with default settings on a 15-page CC BY article rendered at 216 dpi. The text layer of the PDF is the ground truth, the score is the share of its 8,882 words found by the OCR:
| classifier | upright pages | pages rotated by 180° |
|---|---|---|
| off | 99.0 % | 7.1 % |
| on (default, v2.0 model) | 96.0 % | 59.3 % |
| on, middle of the line (diff below) | 99.0 % | 98.2 % |
on, Cls.ocr_version=PP-OCRv5 |
99.0 % | 97.4 % |
A second article (18 pages, 10,885 words) gives 96.9 % / 66.6 % by default and 99.0 % / 98.5 % with the change.
Proposed change, for the v2.0 model only:
--- a/python/rapidocr/ch_ppocr_cls/main.py
+++ b/python/rapidocr/ch_ppocr_cls/main.py
@@ -33,6 +33,10 @@ CLS_SHAPE_BY_OCR_VERSION = {
class TextClassifier:
def __init__(self, cfg: Dict[str, Any]):
self.cls_image_shape = CLS_SHAPE_BY_OCR_VERSION[cfg["ocr_version"]]
+ # The v2.0 classifier cannot read a line squeezed to its input width.
+ # PP-LCNet textline_ori (PP-OCRv5) is trained on squeezed lines and
+ # must keep receiving them.
+ self.crop_long_lines = cfg["ocr_version"] == OCRVersion.PPOCRV4
self.cls_batch_num = cfg["cls_batch_num"]
self.cls_thresh = cfg["cls_thresh"]
self.postprocess_op = ClsPostProcess(cfg["label_list"])
@@ -83,6 +87,14 @@ class TextClassifier:
def resize_norm_img(self, img: np.ndarray) -> np.ndarray:
img_c, img_h, img_w = self.cls_image_shape
h, w = img.shape[:2]
+ if self.crop_long_lines:
+ # Classify the middle of a long line at the model's own aspect
+ # ratio instead of the whole line squeezed into img_w.
+ keep_w = int(math.ceil(h * img_w / float(img_h)))
+ if w > keep_w:
+ left = (w - keep_w) // 2
+ img = img[:, left : left + keep_w]
+ w = keep_w
ratio = w / float(h)
if math.ceil(img_h * ratio) > img_w:
resized_w = img_w
Notes:
- #734 (PP-OCRv5 classifier by default) solves this on the backends that have the new model, and the last row of the table supports it. The v2.0 model is still the only classifier for torch, and what
PP-OCRv4selects, hence this change. - With the PP-OCRv5 model the same crop makes things worse (97.4 % down to 92.6 % on rotated pages), so it should stay limited to v2.0.
- I checked Chinese with rendered lines of 4 to 44 characters (264 lines, upright and upside down): 9 wrong calls today, all on lines of 36 characters or more, none with the change.
Reproduce (first three pages, about a minute; rapidocr 3.9.2, onnxruntime 1.30.0, Python 3.12, Windows 11, CPU):
import re
import urllib.request
from collections import Counter
from pathlib import Path
import numpy
import pypdfium2 as pdfium
from rapidocr import RapidOCR
# CC BY article (PMC Open Access subset); its text layer is the ground truth
URL = "https://pmc-oa-opendata.s3.amazonaws.com/PMC9487863.1/PMC9487863.1.pdf"
path = Path("PMC9487863.pdf")
if not path.exists():
urllib.request.urlretrieve(URL, path)
pdf = pdfium.PdfDocument(path)
reader = RapidOCR()
def words(text):
return Counter(re.findall(r"\w+", text.lower()))
for use_cls in (False, True):
found = total = 0
for page in (pdf[0], pdf[1], pdf[2]):
text = re.sub(chr(0xFFFE) + r"\s*", "", page.get_textpage().get_text_range()) # U+FFFE: line-end hyphen
image = numpy.array(page.render(scale=3).to_pil().convert("RGB")) # 216 dpi
reference, got = words(text), words(" ".join(reader(image, use_cls=use_cls).txts))
found += sum((reference & got).values())
total += sum(reference.values())
print(f"use_cls={use_cls}: {found / total:.1%} of the words found")
use_cls=False: 98.2% of the words found
use_cls=True: 91.9% of the words found
I can share the script behind the full table (rotated pages, patched classifier) and open a PR if this direction is fine with you.
Feel free to submit your PR.