python-doctr 1.0.1__py3-none-any.whl → 1.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- doctr/cli/__init__.py +0 -0
- doctr/cli/main.py +506 -0
- doctr/datasets/__init__.py +2 -0
- doctr/datasets/coco_text.py +4 -2
- doctr/datasets/cord.py +2 -1
- doctr/datasets/datasets/base.py +12 -24
- doctr/datasets/datasets/pytorch.py +14 -4
- doctr/datasets/detection.py +2 -1
- doctr/datasets/doc_artefacts.py +2 -1
- doctr/datasets/funsd.py +2 -1
- doctr/datasets/generator/base.py +5 -4
- doctr/datasets/generator/pytorch.py +4 -5
- doctr/datasets/ic03.py +3 -2
- doctr/datasets/ic13.py +4 -2
- doctr/datasets/iiit5k.py +2 -1
- doctr/datasets/iiithws.py +4 -2
- doctr/datasets/imgur5k.py +4 -2
- doctr/datasets/layout.py +123 -0
- doctr/datasets/mjsynth.py +4 -2
- doctr/datasets/ocr.py +2 -1
- doctr/datasets/orientation.py +2 -1
- doctr/datasets/recognition.py +2 -1
- doctr/datasets/sroie.py +2 -1
- doctr/datasets/svhn.py +2 -1
- doctr/datasets/svt.py +3 -2
- doctr/datasets/synthtext.py +2 -1
- doctr/datasets/table_structure.py +97 -0
- doctr/datasets/utils.py +14 -5
- doctr/datasets/vocabs.py +2 -0
- doctr/datasets/wildreceipt.py +4 -2
- doctr/file_utils.py +3 -1
- doctr/io/__init__.py +1 -0
- doctr/io/elements.py +252 -260
- doctr/io/exporters.py +1275 -0
- doctr/io/image/base.py +3 -2
- doctr/io/image/pytorch.py +5 -3
- doctr/models/__init__.py +2 -0
- doctr/models/_utils.py +56 -8
- doctr/models/builder.py +532 -61
- doctr/models/classification/__init__.py +2 -0
- doctr/models/classification/magc_resnet/pytorch.py +1 -1
- doctr/models/classification/mobilenet/pytorch.py +6 -6
- doctr/models/classification/predictor/pytorch.py +6 -2
- doctr/models/classification/resnet/pytorch.py +5 -5
- doctr/models/classification/starnet/__init__.py +1 -0
- doctr/models/classification/starnet/pytorch.py +202 -0
- doctr/models/classification/textnet/pytorch.py +6 -5
- doctr/models/classification/vgg/pytorch.py +3 -2
- doctr/models/classification/vip/layers/pytorch.py +4 -4
- doctr/models/classification/vip/pytorch.py +4 -4
- doctr/models/classification/vit/pytorch.py +3 -3
- doctr/models/classification/vit_det/__init__.py +1 -0
- doctr/models/classification/vit_det/layers/__init__.py +1 -0
- doctr/models/classification/vit_det/layers/pytorch.py +215 -0
- doctr/models/classification/vit_det/pytorch.py +346 -0
- doctr/models/classification/zoo.py +3 -0
- doctr/models/detection/_utils/base.py +23 -7
- doctr/models/detection/core.py +33 -18
- doctr/models/detection/differentiable_binarization/base.py +6 -4
- doctr/models/detection/differentiable_binarization/pytorch.py +3 -3
- doctr/models/detection/fast/base.py +5 -1
- doctr/models/detection/fast/pytorch.py +3 -3
- doctr/models/detection/linknet/base.py +5 -1
- doctr/models/detection/linknet/pytorch.py +3 -3
- doctr/models/detection/predictor/pytorch.py +3 -2
- doctr/models/detection/zoo.py +2 -2
- doctr/models/factory/hub.py +56 -41
- doctr/models/kie_predictor/base.py +16 -1
- doctr/models/kie_predictor/pytorch.py +41 -10
- doctr/models/layout/__init__.py +2 -0
- doctr/models/layout/lw_detr/__init__.py +1 -0
- doctr/models/layout/lw_detr/base.py +309 -0
- doctr/models/layout/lw_detr/layers/__init__.py +1 -0
- doctr/models/layout/lw_detr/layers/pytorch.py +785 -0
- doctr/models/layout/lw_detr/pytorch.py +838 -0
- doctr/models/layout/predictor/__init__.py +1 -0
- doctr/models/layout/predictor/pytorch.py +82 -0
- doctr/models/layout/zoo.py +90 -0
- doctr/models/modules/layers/pytorch.py +139 -3
- doctr/models/predictor/base.py +137 -15
- doctr/models/predictor/pytorch.py +150 -8
- doctr/models/preprocessor/pytorch.py +77 -22
- doctr/models/reading_order/__init__.py +1 -0
- doctr/models/reading_order/base.py +667 -0
- doctr/models/recognition/crnn/pytorch.py +5 -7
- doctr/models/recognition/master/pytorch.py +6 -7
- doctr/models/recognition/parseq/pytorch.py +4 -4
- doctr/models/recognition/predictor/pytorch.py +1 -1
- doctr/models/recognition/sar/pytorch.py +1 -1
- doctr/models/recognition/utils.py +8 -10
- doctr/models/recognition/viptr/pytorch.py +3 -5
- doctr/models/recognition/vitstr/pytorch.py +5 -5
- doctr/models/recognition/zoo.py +5 -6
- doctr/models/table_structure/__init__.py +2 -0
- doctr/models/table_structure/predictor/__init__.py +1 -0
- doctr/models/table_structure/predictor/pytorch.py +80 -0
- doctr/models/table_structure/tablecenternet/__init__.py +2 -0
- doctr/models/table_structure/tablecenternet/base.py +485 -0
- doctr/models/table_structure/tablecenternet/pytorch.py +522 -0
- doctr/models/table_structure/zoo.py +82 -0
- doctr/models/utils/pytorch.py +314 -15
- doctr/models/zoo.py +90 -2
- doctr/transforms/modules/base.py +247 -82
- doctr/transforms/modules/pytorch.py +212 -73
- doctr/utils/common_types.py +21 -1
- doctr/utils/data.py +4 -2
- doctr/utils/fonts.py +55 -16
- doctr/utils/geometry.py +135 -18
- doctr/utils/metrics.py +350 -18
- doctr/utils/multithreading.py +5 -2
- doctr/utils/reconstitution.py +696 -132
- doctr/utils/visualization.py +62 -3
- doctr/version.py +1 -1
- {python_doctr-1.0.1.dist-info → python_doctr-1.1.0.dist-info}/METADATA +67 -27
- python_doctr-1.1.0.dist-info/RECORD +179 -0
- {python_doctr-1.0.1.dist-info → python_doctr-1.1.0.dist-info}/WHEEL +1 -1
- python_doctr-1.1.0.dist-info/entry_points.txt +2 -0
- python_doctr-1.0.1.dist-info/RECORD +0 -149
- {python_doctr-1.0.1.dist-info → python_doctr-1.1.0.dist-info}/licenses/LICENSE +0 -0
- {python_doctr-1.0.1.dist-info → python_doctr-1.1.0.dist-info}/top_level.txt +0 -0
- {python_doctr-1.0.1.dist-info → python_doctr-1.1.0.dist-info}/zip-safe +0 -0
doctr/utils/geometry.py
CHANGED
|
@@ -3,7 +3,6 @@
|
|
|
3
3
|
# This program is licensed under the Apache License 2.0.
|
|
4
4
|
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
|
|
5
5
|
|
|
6
|
-
from copy import deepcopy
|
|
7
6
|
from math import ceil
|
|
8
7
|
|
|
9
8
|
import cv2
|
|
@@ -14,12 +13,14 @@ from .common_types import BoundingBox, Polygon4P
|
|
|
14
13
|
__all__ = [
|
|
15
14
|
"bbox_to_polygon",
|
|
16
15
|
"polygon_to_bbox",
|
|
16
|
+
"order_points",
|
|
17
17
|
"resolve_enclosing_bbox",
|
|
18
18
|
"resolve_enclosing_rbbox",
|
|
19
19
|
"rotate_boxes",
|
|
20
20
|
"compute_expanded_shape",
|
|
21
21
|
"rotate_image",
|
|
22
22
|
"remove_image_padding",
|
|
23
|
+
"straighten_page",
|
|
23
24
|
"estimate_page_angle",
|
|
24
25
|
"convert_to_relative_coords",
|
|
25
26
|
"rotate_abs_geoms",
|
|
@@ -54,6 +55,56 @@ def polygon_to_bbox(polygon: Polygon4P) -> BoundingBox:
|
|
|
54
55
|
return (min(x), min(y)), (max(x), max(y))
|
|
55
56
|
|
|
56
57
|
|
|
58
|
+
def order_points(pts: np.ndarray) -> np.ndarray:
|
|
59
|
+
"""Order points in the following order: top-left, top-right, bottom-right, bottom-left
|
|
60
|
+
|
|
61
|
+
Args:
|
|
62
|
+
pts: array of shape (4, 2) or (4,) with the coordinates of the points
|
|
63
|
+
|
|
64
|
+
Returns:
|
|
65
|
+
ordered points in the following order: top-left, top-right, bottom-right, bottom-left
|
|
66
|
+
"""
|
|
67
|
+
pts = np.asarray(pts)
|
|
68
|
+
|
|
69
|
+
# (xmin, ymin, xmax, ymax)
|
|
70
|
+
if pts.shape == (4,):
|
|
71
|
+
xmin, ymin, xmax, ymax = pts
|
|
72
|
+
return np.array(
|
|
73
|
+
[
|
|
74
|
+
[xmin, ymin], # top-left
|
|
75
|
+
[xmax, ymin], # top-right
|
|
76
|
+
[xmax, ymax], # bottom-right
|
|
77
|
+
[xmin, ymax], # bottom-left
|
|
78
|
+
],
|
|
79
|
+
dtype=pts.dtype,
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
# (4, 2) quadrangle
|
|
83
|
+
if pts.shape == (4, 2):
|
|
84
|
+
c = pts.mean(axis=0)
|
|
85
|
+
|
|
86
|
+
# compute angle of each point around centroid
|
|
87
|
+
angles = np.arctan2(pts[:, 1] - c[1], pts[:, 0] - c[0])
|
|
88
|
+
|
|
89
|
+
# sort by angle (counter-clockwise ordering)
|
|
90
|
+
pts = pts[np.argsort(angles)]
|
|
91
|
+
|
|
92
|
+
# ensure consistent starting point (top-left)
|
|
93
|
+
start_idx = np.argmin(pts.sum(axis=1))
|
|
94
|
+
pts = np.roll(pts, -start_idx, axis=0)
|
|
95
|
+
|
|
96
|
+
# ensure order is TL, TR, BR, BL (clockwise)
|
|
97
|
+
def area(poly):
|
|
98
|
+
return 0.5 * np.sum(poly[:, 0] * np.roll(poly[:, 1], -1) - poly[:, 1] * np.roll(poly[:, 0], -1))
|
|
99
|
+
|
|
100
|
+
if area(pts) < 0:
|
|
101
|
+
pts = np.roll(pts[::-1], 1, axis=0)
|
|
102
|
+
|
|
103
|
+
return pts.astype(pts.dtype)
|
|
104
|
+
|
|
105
|
+
raise ValueError(f"Unsupported shape {pts.shape}, expected (4,) or (4,2)")
|
|
106
|
+
|
|
107
|
+
|
|
57
108
|
def detach_scores(boxes: list[np.ndarray]) -> tuple[list[np.ndarray], list[np.ndarray]]:
|
|
58
109
|
"""Detach the objectness scores from box predictions
|
|
59
110
|
|
|
@@ -113,9 +164,8 @@ def resolve_enclosing_rbbox(rbboxes: list[np.ndarray], intermed_size: int = 1024
|
|
|
113
164
|
"""
|
|
114
165
|
cloud: np.ndarray = np.concatenate(rbboxes, axis=0)
|
|
115
166
|
# Convert to absolute for minAreaRect
|
|
116
|
-
cloud
|
|
117
|
-
|
|
118
|
-
return cv2.boxPoints(rect) / intermed_size
|
|
167
|
+
rect = cv2.minAreaRect(cloud.astype(np.float32) * intermed_size)
|
|
168
|
+
return order_points(cv2.boxPoints(rect) / intermed_size)
|
|
119
169
|
|
|
120
170
|
|
|
121
171
|
def rotate_abs_points(points: np.ndarray, angle: float = 0.0) -> np.ndarray:
|
|
@@ -338,15 +388,78 @@ def remove_image_padding(image: np.ndarray) -> np.ndarray:
|
|
|
338
388
|
Returns:
|
|
339
389
|
Image with padding removed
|
|
340
390
|
"""
|
|
341
|
-
# Find the bounding box of the non-black region
|
|
342
|
-
rows = np.any(image, axis=
|
|
343
|
-
cols = np.any(image, axis=
|
|
344
|
-
|
|
345
|
-
|
|
391
|
+
# Find the bounding box of the non-black region (reduce over every axis but the one of interest)
|
|
392
|
+
rows = np.any(image, axis=tuple(ax for ax in range(image.ndim) if ax != 0))
|
|
393
|
+
cols = np.any(image, axis=tuple(ax for ax in range(image.ndim) if ax != 1))
|
|
394
|
+
if not rows.any(): # fully black image: nothing to crop
|
|
395
|
+
return image
|
|
396
|
+
rmin, rmax = int(np.argmax(rows)), image.shape[0] - 1 - int(np.argmax(rows[::-1]))
|
|
397
|
+
cmin, cmax = int(np.argmax(cols)), image.shape[1] - 1 - int(np.argmax(cols[::-1]))
|
|
346
398
|
|
|
347
399
|
return image[rmin : rmax + 1, cmin : cmax + 1]
|
|
348
400
|
|
|
349
401
|
|
|
402
|
+
def straighten_page(
|
|
403
|
+
page: np.ndarray,
|
|
404
|
+
angle: float,
|
|
405
|
+
) -> tuple[np.ndarray, np.ndarray]:
|
|
406
|
+
"""Straighten a page by rotating it and cropping to content, returning the straightened image
|
|
407
|
+
and the inverse affine matrix that maps straightened-page coordinates back to the original page.
|
|
408
|
+
|
|
409
|
+
Args:
|
|
410
|
+
page: the original page image (H, W, C)
|
|
411
|
+
angle: rotation angle in degrees (between -90 and +90)
|
|
412
|
+
|
|
413
|
+
Returns:
|
|
414
|
+
a tuple (straightened, M_inv) where straightened is the page rotated and cropped to the
|
|
415
|
+
non-padded region, and M_inv is a (3, 3) array mapping points in the straightened image's
|
|
416
|
+
pixel space (x, y, 1) back to the original page's pixel space.
|
|
417
|
+
"""
|
|
418
|
+
h, w = page.shape[:2]
|
|
419
|
+
|
|
420
|
+
# Padding to preserve content after rotation
|
|
421
|
+
exp = compute_expanded_shape((h, w), angle)
|
|
422
|
+
h_pad = int(max(0, np.ceil(exp[0] - h)))
|
|
423
|
+
w_pad = int(max(0, np.ceil(exp[1] - w)))
|
|
424
|
+
|
|
425
|
+
pt, pb = h_pad // 2, h_pad - h_pad // 2
|
|
426
|
+
pl, pr = w_pad // 2, w_pad - w_pad // 2
|
|
427
|
+
|
|
428
|
+
exp_img = np.pad(page, ((pt, pb), (pl, pr), (0, 0)))
|
|
429
|
+
ph_pad, pw_pad = exp_img.shape[:2]
|
|
430
|
+
|
|
431
|
+
# Rotate around the padded image center
|
|
432
|
+
rot_mat = cv2.getRotationMatrix2D((pw_pad / 2, ph_pad / 2), angle, 1.0)
|
|
433
|
+
rotated = cv2.warpAffine(exp_img, rot_mat, (pw_pad, ph_pad))
|
|
434
|
+
|
|
435
|
+
# Aspect-ratio padding (applied only on right/bottom so analytic crop stays simple)
|
|
436
|
+
if h_pad > 0 or w_pad > 0:
|
|
437
|
+
if (rotated.shape[0] / rotated.shape[1]) > (h / w):
|
|
438
|
+
w_pad2 = int(rotated.shape[0] * w / h - rotated.shape[1])
|
|
439
|
+
rotated = np.pad(rotated, ((0, 0), (0, w_pad2), (0, 0)))
|
|
440
|
+
else:
|
|
441
|
+
h_pad2 = int(rotated.shape[1] * h / w - rotated.shape[0])
|
|
442
|
+
rotated = np.pad(rotated, ((0, h_pad2), (0, 0), (0, 0)))
|
|
443
|
+
|
|
444
|
+
# Analytic crop: project the four content corners through the rotation matrix
|
|
445
|
+
corners = np.array(
|
|
446
|
+
[[pl, pt, 1], [pl + w, pt, 1], [pl + w, pt + h, 1], [pl, pt + h, 1]],
|
|
447
|
+
dtype=np.float64,
|
|
448
|
+
).T
|
|
449
|
+
rc = rot_mat @ corners
|
|
450
|
+
cx, cy = max(0, int(np.floor(rc[0].min()))), max(0, int(np.floor(rc[1].min())))
|
|
451
|
+
cropped = rotated[cy:, cx:]
|
|
452
|
+
|
|
453
|
+
# Composite forward matrix: crop ∘ rotate ∘ pad
|
|
454
|
+
# cv2.warpAffine treats the rotation matrix as src→dst
|
|
455
|
+
c3 = np.array([[1, 0, -cx], [0, 1, -cy], [0, 0, 1]], dtype=np.float64)
|
|
456
|
+
r3 = np.vstack([rot_mat, [0, 0, 1]])
|
|
457
|
+
p3 = np.array([[1, 0, pl], [0, 1, pt], [0, 0, 1]], dtype=np.float64)
|
|
458
|
+
m_inv = np.linalg.inv(c3 @ r3 @ p3)
|
|
459
|
+
|
|
460
|
+
return cropped, m_inv
|
|
461
|
+
|
|
462
|
+
|
|
350
463
|
def estimate_page_angle(polys: np.ndarray) -> float:
|
|
351
464
|
"""Takes a batch of rotated previously ORIENTED polys (N, 4, 2) (rectified by the classifier) and return the
|
|
352
465
|
estimated angle ccw in degrees
|
|
@@ -356,13 +469,12 @@ def estimate_page_angle(polys: np.ndarray) -> float:
|
|
|
356
469
|
yleft = polys[:, 0, 1] + polys[:, 3, 1]
|
|
357
470
|
xright = polys[:, 1, 0] + polys[:, 2, 0]
|
|
358
471
|
yright = polys[:, 1, 1] + polys[:, 2, 1]
|
|
359
|
-
with np.errstate(divide="
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
return 0.0
|
|
472
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
473
|
+
angles = np.arctan((yleft - yright) / (xright - xleft)) * 180 / np.pi # Y axis from top to bottom!
|
|
474
|
+
# Degenerate polygons (0/0) yield NaN: ignore them instead of discarding the whole page estimate,
|
|
475
|
+
# while vertical polygons (x/0 -> +/-inf) legitimately contribute +/-90 degrees through arctan
|
|
476
|
+
angles = angles[np.isfinite(angles)]
|
|
477
|
+
return float(np.median(angles)) if angles.size > 0 else 0.0
|
|
366
478
|
|
|
367
479
|
|
|
368
480
|
def convert_to_relative_coords(geoms: np.ndarray, img_shape: tuple[int, int]) -> np.ndarray:
|
|
@@ -414,9 +526,9 @@ def extract_crops(img: np.ndarray, boxes: np.ndarray) -> list[np.ndarray]:
|
|
|
414
526
|
_boxes[:, [1, 3]] *= h
|
|
415
527
|
_boxes = _boxes.round().astype(int)
|
|
416
528
|
# Add last index
|
|
417
|
-
_boxes[2:] += 1
|
|
529
|
+
_boxes[:, 2:] += 1
|
|
418
530
|
|
|
419
|
-
return
|
|
531
|
+
return [np.ascontiguousarray(img[box[1] : box[3], box[0] : box[2]]) for box in _boxes]
|
|
420
532
|
|
|
421
533
|
|
|
422
534
|
def extract_rcrops(
|
|
@@ -481,6 +593,9 @@ def extract_rcrops(
|
|
|
481
593
|
# Get the maximum width and height
|
|
482
594
|
rect_width = max(int(width_upper), int(width_lower))
|
|
483
595
|
rect_height = max(int(height_left), int(height_right))
|
|
596
|
+
if rect_width < 1 or rect_height < 1:
|
|
597
|
+
crops.append(np.zeros((0, 0, *img.shape[2:]), dtype=img.dtype))
|
|
598
|
+
continue
|
|
484
599
|
|
|
485
600
|
dst_pts = np.array(
|
|
486
601
|
[
|
|
@@ -526,6 +641,8 @@ def extract_rcrops(
|
|
|
526
641
|
cv2.getAffineTransform(src_pts[idx], dst_pts[idx]),
|
|
527
642
|
(int(d1[idx]), int(d2[idx])),
|
|
528
643
|
)
|
|
644
|
+
if int(d1[idx]) > 0 and int(d2[idx]) > 0
|
|
645
|
+
else np.zeros((0, 0, *img.shape[2:]), dtype=img.dtype)
|
|
529
646
|
for idx in range(_boxes.shape[0])
|
|
530
647
|
]
|
|
531
648
|
return crops
|
doctr/utils/metrics.py
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
import numpy as np
|
|
8
8
|
from anyascii import anyascii
|
|
9
9
|
from scipy.optimize import linear_sum_assignment
|
|
10
|
-
from shapely
|
|
10
|
+
from shapely import STRtree, area, intersection, polygons
|
|
11
11
|
|
|
12
12
|
__all__ = [
|
|
13
13
|
"TextMatch",
|
|
@@ -17,6 +17,8 @@ __all__ = [
|
|
|
17
17
|
"LocalizationConfusion",
|
|
18
18
|
"OCRMetric",
|
|
19
19
|
"DetectionMetric",
|
|
20
|
+
"ObjectDetectionMetric",
|
|
21
|
+
"TableCellMetric",
|
|
20
22
|
]
|
|
21
23
|
|
|
22
24
|
|
|
@@ -144,7 +146,7 @@ def box_iou(boxes_1: np.ndarray, boxes_2: np.ndarray) -> np.ndarray:
|
|
|
144
146
|
|
|
145
147
|
intersection = np.clip(right - left, 0, np.inf) * np.clip(bot - top, 0, np.inf)
|
|
146
148
|
union = (r1 - l1) * (b1 - t1) + ((r2 - l2) * (b2 - t2)).T - intersection
|
|
147
|
-
iou_mat = intersection
|
|
149
|
+
iou_mat = np.divide(intersection, union, out=np.zeros_like(intersection), where=union > 0)
|
|
148
150
|
|
|
149
151
|
return iou_mat
|
|
150
152
|
|
|
@@ -155,8 +157,6 @@ def polygon_iou(polys_1: np.ndarray, polys_2: np.ndarray) -> np.ndarray:
|
|
|
155
157
|
Args:
|
|
156
158
|
polys_1: rotated bounding boxes of shape (N, 4, 2)
|
|
157
159
|
polys_2: rotated bounding boxes of shape (M, 4, 2)
|
|
158
|
-
mask_shape: spatial shape of the intermediate masks
|
|
159
|
-
use_broadcasting: if set to True, leverage broadcasting speedup by consuming more memory
|
|
160
160
|
|
|
161
161
|
Returns:
|
|
162
162
|
the IoU matrix of shape (N, M)
|
|
@@ -164,17 +164,20 @@ def polygon_iou(polys_1: np.ndarray, polys_2: np.ndarray) -> np.ndarray:
|
|
|
164
164
|
if polys_1.ndim != 3 or polys_2.ndim != 3:
|
|
165
165
|
raise AssertionError("expects boxes to be in format (N, 4, 2)")
|
|
166
166
|
|
|
167
|
-
|
|
167
|
+
n, m = polys_1.shape[0], polys_2.shape[0]
|
|
168
|
+
if n == 0 or m == 0:
|
|
169
|
+
return np.zeros((n, m), dtype=np.float32)
|
|
168
170
|
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
for i, poly1 in enumerate(shapely_polys_1):
|
|
173
|
-
for j, poly2 in enumerate(shapely_polys_2):
|
|
174
|
-
intersection_area = poly1.intersection(poly2).area
|
|
175
|
-
union_area = poly1.area + poly2.area - intersection_area
|
|
176
|
-
iou_mat[i, j] = intersection_area / union_area
|
|
171
|
+
geoms_1 = polygons(polys_1)
|
|
172
|
+
geoms_2 = polygons(polys_2)
|
|
177
173
|
|
|
174
|
+
iou_mat = np.zeros((n, m), dtype=np.float32)
|
|
175
|
+
idcs_1, idcs_2 = STRtree(geoms_2).query(geoms_1)
|
|
176
|
+
if idcs_1.size > 0:
|
|
177
|
+
# Compute intersections and areas for the candidate pairs only
|
|
178
|
+
intersections = area(intersection(geoms_1[idcs_1], geoms_2[idcs_2]))
|
|
179
|
+
unions = area(geoms_1)[idcs_1] + area(geoms_2)[idcs_2] - intersections
|
|
180
|
+
iou_mat[idcs_1, idcs_2] = np.divide(intersections, unions, out=np.zeros_like(intersections), where=unions > 0)
|
|
178
181
|
return iou_mat
|
|
179
182
|
|
|
180
183
|
|
|
@@ -269,7 +272,7 @@ class LocalizationConfusion:
|
|
|
269
272
|
gts: a set of relative bounding boxes either of shape (N, 4) or (N, 5) if they are rotated ones
|
|
270
273
|
preds: a set of relative bounding boxes either of shape (M, 4) or (M, 5) if they are rotated ones
|
|
271
274
|
"""
|
|
272
|
-
if preds.shape[0] > 0:
|
|
275
|
+
if gts.shape[0] > 0 and preds.shape[0] > 0:
|
|
273
276
|
# Compute IoU
|
|
274
277
|
if self.use_polygons:
|
|
275
278
|
iou_mat = polygon_iou(gts, preds)
|
|
@@ -309,6 +312,89 @@ class LocalizationConfusion:
|
|
|
309
312
|
self.tot_iou = 0.0
|
|
310
313
|
|
|
311
314
|
|
|
315
|
+
class TableCellMetric:
|
|
316
|
+
r"""Implements a table-structure-recognition metric.
|
|
317
|
+
|
|
318
|
+
Predicted cells are matched to ground-truth cells by maximising the total IoU (Hungarian assignment); a pair
|
|
319
|
+
counts as a match when its IoU is at least `iou_thresh`. From the matches it reports cell-detection recall,
|
|
320
|
+
precision, F1 and the **structure accuracy** (the fraction of matched cells whose logical coordinates
|
|
321
|
+
`[start_col, end_col, start_row, end_row]` exactly equal the ground-truth ones).
|
|
322
|
+
|
|
323
|
+
>>> import numpy as np
|
|
324
|
+
>>> from doctr.utils import TableCellMetric
|
|
325
|
+
>>> metric = TableCellMetric(iou_thresh=0.5)
|
|
326
|
+
>>> gt = np.array([[0, 0, 1, 1]], dtype=np.float32)
|
|
327
|
+
>>> metric.update(gt, np.array([[0, 0, 0, 0]]), gt, np.array([[0, 0, 0, 0]]))
|
|
328
|
+
>>> metric.summary()
|
|
329
|
+
|
|
330
|
+
Args:
|
|
331
|
+
iou_thresh: minimum IoU for a predicted/ground-truth cell pair to be considered a match
|
|
332
|
+
use_polygons: if set to True, predictions and targets will be expected to have polygon format
|
|
333
|
+
"""
|
|
334
|
+
|
|
335
|
+
def __init__(
|
|
336
|
+
self,
|
|
337
|
+
iou_thresh: float = 0.5,
|
|
338
|
+
use_polygons: bool = False,
|
|
339
|
+
) -> None:
|
|
340
|
+
self.iou_thresh = iou_thresh
|
|
341
|
+
self.use_polygons = use_polygons
|
|
342
|
+
self.reset()
|
|
343
|
+
|
|
344
|
+
def update(
|
|
345
|
+
self,
|
|
346
|
+
gt_cells: np.ndarray,
|
|
347
|
+
gt_logic: np.ndarray,
|
|
348
|
+
pred_cells: np.ndarray,
|
|
349
|
+
pred_logic: np.ndarray,
|
|
350
|
+
) -> None:
|
|
351
|
+
"""Update the metric with one sample.
|
|
352
|
+
|
|
353
|
+
Args:
|
|
354
|
+
gt_cells: ground-truth cells, shape (N, 4) or (N, 4, 2) when `use_polygons=True`
|
|
355
|
+
gt_logic: ground-truth logical coordinates, shape (N, 4)
|
|
356
|
+
pred_cells: predicted cells, shape (M, 4) or (M, 4, 2) when `use_polygons=True`
|
|
357
|
+
pred_logic: predicted logical coordinates, shape (M, 4)
|
|
358
|
+
"""
|
|
359
|
+
self.num_gts += gt_cells.shape[0]
|
|
360
|
+
self.num_preds += pred_cells.shape[0]
|
|
361
|
+
if gt_cells.shape[0] == 0 or pred_cells.shape[0] == 0:
|
|
362
|
+
return
|
|
363
|
+
|
|
364
|
+
if self.use_polygons:
|
|
365
|
+
iou_mat = polygon_iou(gt_cells, pred_cells)
|
|
366
|
+
else:
|
|
367
|
+
iou_mat = box_iou(gt_cells, pred_cells)
|
|
368
|
+
gt_idx, pred_idx = linear_sum_assignment(-iou_mat)
|
|
369
|
+
for gi, pi in zip(gt_idx, pred_idx):
|
|
370
|
+
if iou_mat[gi, pi] >= self.iou_thresh:
|
|
371
|
+
self.matches += 1
|
|
372
|
+
if np.array_equal(np.asarray(gt_logic[gi]), np.asarray(pred_logic[pi])):
|
|
373
|
+
self.struct_matches += 1
|
|
374
|
+
|
|
375
|
+
def summary(self) -> dict[str, float | None]:
|
|
376
|
+
"""Compute the aggregated metrics.
|
|
377
|
+
|
|
378
|
+
Returns:
|
|
379
|
+
a dict with `recall`, `precision`, `f1` (cell detection) and `structure_acc`
|
|
380
|
+
"""
|
|
381
|
+
recall = self.matches / self.num_gts if self.num_gts > 0 else None
|
|
382
|
+
precision = self.matches / self.num_preds if self.num_preds > 0 else None
|
|
383
|
+
f1 = (
|
|
384
|
+
2 * precision * recall / (precision + recall)
|
|
385
|
+
if precision is not None and recall is not None and (precision + recall) > 0
|
|
386
|
+
else None
|
|
387
|
+
)
|
|
388
|
+
structure_acc = self.struct_matches / self.matches if self.matches > 0 else None
|
|
389
|
+
return {"recall": recall, "precision": precision, "f1": f1, "structure_acc": structure_acc}
|
|
390
|
+
|
|
391
|
+
def reset(self) -> None:
|
|
392
|
+
self.num_gts = 0
|
|
393
|
+
self.num_preds = 0
|
|
394
|
+
self.matches = 0
|
|
395
|
+
self.struct_matches = 0
|
|
396
|
+
|
|
397
|
+
|
|
312
398
|
class OCRMetric:
|
|
313
399
|
r"""Implements an end-to-end OCR metric.
|
|
314
400
|
|
|
@@ -379,8 +465,7 @@ class OCRMetric:
|
|
|
379
465
|
"there should be the same number of boxes and string both for the ground truth and the predictions"
|
|
380
466
|
)
|
|
381
467
|
|
|
382
|
-
|
|
383
|
-
if pred_boxes.shape[0] > 0:
|
|
468
|
+
if gt_boxes.shape[0] > 0 and pred_boxes.shape[0] > 0:
|
|
384
469
|
if self.use_polygons:
|
|
385
470
|
iou_mat = polygon_iou(gt_boxes, pred_boxes)
|
|
386
471
|
else:
|
|
@@ -509,8 +594,7 @@ class DetectionMetric:
|
|
|
509
594
|
"there should be the same number of boxes and string both for the ground truth and the predictions"
|
|
510
595
|
)
|
|
511
596
|
|
|
512
|
-
|
|
513
|
-
if pred_boxes.shape[0] > 0:
|
|
597
|
+
if gt_boxes.shape[0] > 0 and pred_boxes.shape[0] > 0:
|
|
514
598
|
if self.use_polygons:
|
|
515
599
|
iou_mat = polygon_iou(gt_boxes, pred_boxes)
|
|
516
600
|
else:
|
|
@@ -549,3 +633,251 @@ class DetectionMetric:
|
|
|
549
633
|
self.num_preds = 0
|
|
550
634
|
self.tot_iou = 0.0
|
|
551
635
|
self.num_matches = 0
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
class ObjectDetectionMetric:
|
|
639
|
+
r"""Implements a COCO-style object detection metric (mAP@[.5:.95]) inspired by the COCO evaluation protocol.
|
|
640
|
+
|
|
641
|
+
The aggregated metrics are computed as follows:
|
|
642
|
+
|
|
643
|
+
.. math::
|
|
644
|
+
|
|
645
|
+
\forall (B, C) \in \mathcal{B}^N \times \mathcal{C}^N,
|
|
646
|
+
\forall (\hat{B}, \hat{C}, S) \in \mathcal{B}^M \times \mathcal{C}^M \times \mathbb{R}^M, \\
|
|
647
|
+
|
|
648
|
+
AP_t(C) =
|
|
649
|
+
\frac{1}{101}
|
|
650
|
+
\sum\limits_{r \in \{0, 0.01, \dots, 1.0\}}
|
|
651
|
+
\max_{\tilde{r} \geq r} Precision_t(\tilde{r}, C) \\
|
|
652
|
+
|
|
653
|
+
mAP@[.5:.95] =
|
|
654
|
+
\frac{1}{|\mathcal{T}|}
|
|
655
|
+
\sum\limits_{t \in \mathcal{T}}
|
|
656
|
+
\frac{1}{|\mathcal{C}|}
|
|
657
|
+
\sum\limits_{c \in \mathcal{C}} AP_t(c)
|
|
658
|
+
|
|
659
|
+
where:
|
|
660
|
+
- :math:`\mathcal{B}` is the set of possible bounding boxes,
|
|
661
|
+
- :math:`\mathcal{C}` is the set of possible class indices,
|
|
662
|
+
- :math:`S` are confidence scores associated to predictions,
|
|
663
|
+
- :math:`\mathcal{T} = \{0.5, 0.55, \dots, 0.95\}` is the set of IoU thresholds,
|
|
664
|
+
- :math:`AP_t(c)` is the Average Precision for class :math:`c`
|
|
665
|
+
at IoU threshold :math:`t`.
|
|
666
|
+
|
|
667
|
+
For a given class and IoU threshold, predictions from all images are
|
|
668
|
+
aggregated and sorted globally by decreasing confidence score.
|
|
669
|
+
|
|
670
|
+
Each prediction is greedily matched to the unmatched ground-truth box
|
|
671
|
+
with the highest IoU, provided that:
|
|
672
|
+
|
|
673
|
+
- the IoU is greater than or equal to the threshold,
|
|
674
|
+
- the ground-truth box has not already been matched.
|
|
675
|
+
|
|
676
|
+
True positives and false positives are accumulated to build a
|
|
677
|
+
precision-recall curve.
|
|
678
|
+
|
|
679
|
+
Average Precision is computed using the COCO 101-point interpolated
|
|
680
|
+
precision-recall curve.
|
|
681
|
+
|
|
682
|
+
>>> import numpy as np
|
|
683
|
+
>>> from doctr.utils import ObjectDetectionMetric
|
|
684
|
+
>>> metric = ObjectDetectionMetric()
|
|
685
|
+
>>> metric.update(
|
|
686
|
+
... np.asarray([[0, 0, 100, 100]]),
|
|
687
|
+
... np.asarray([[0, 0, 80, 80], [120, 120, 200, 200]]),
|
|
688
|
+
... np.asarray([0]),
|
|
689
|
+
... np.asarray([0, 1]),
|
|
690
|
+
... np.asarray([0.9, 0.3])
|
|
691
|
+
... )
|
|
692
|
+
>>> metric.summary()
|
|
693
|
+
|
|
694
|
+
Args:
|
|
695
|
+
iou_thresholds: sequence of IoU thresholds used to compute the metric
|
|
696
|
+
(defaults to np.arange(0.5, 1.0, 0.05))
|
|
697
|
+
num_classes: total number of classes. If None, inferred from data
|
|
698
|
+
use_polygons: if set to True, predictions and targets will be expected
|
|
699
|
+
to have rotated format
|
|
700
|
+
"""
|
|
701
|
+
|
|
702
|
+
def __init__(
|
|
703
|
+
self,
|
|
704
|
+
iou_thresholds: np.ndarray | None = None,
|
|
705
|
+
num_classes: int | None = None,
|
|
706
|
+
use_polygons: bool = False,
|
|
707
|
+
) -> None:
|
|
708
|
+
self.iou_thresholds = iou_thresholds if iou_thresholds is not None else np.round(np.arange(0.5, 1.0, 0.05), 2)
|
|
709
|
+
self.num_classes = num_classes
|
|
710
|
+
self.use_polygons = use_polygons
|
|
711
|
+
self.reset()
|
|
712
|
+
|
|
713
|
+
def update(
|
|
714
|
+
self,
|
|
715
|
+
gt_boxes: np.ndarray,
|
|
716
|
+
pred_boxes: np.ndarray,
|
|
717
|
+
gt_labels: np.ndarray,
|
|
718
|
+
pred_labels: np.ndarray,
|
|
719
|
+
pred_scores: np.ndarray,
|
|
720
|
+
) -> None:
|
|
721
|
+
if (
|
|
722
|
+
gt_boxes.shape[0] != gt_labels.shape[0]
|
|
723
|
+
or pred_boxes.shape[0] != pred_labels.shape[0]
|
|
724
|
+
or pred_boxes.shape[0] != pred_scores.shape[0]
|
|
725
|
+
):
|
|
726
|
+
raise AssertionError("Mismatch between boxes, labels, scores")
|
|
727
|
+
|
|
728
|
+
self._gts.append({"boxes": gt_boxes, "labels": gt_labels})
|
|
729
|
+
self._preds.append({"boxes": pred_boxes, "labels": pred_labels, "scores": pred_scores})
|
|
730
|
+
|
|
731
|
+
def summary(self) -> dict[str, float | dict[float, float]]:
|
|
732
|
+
"""Computes the aggregated metrics
|
|
733
|
+
|
|
734
|
+
Returns:
|
|
735
|
+
a dictionary with the mAP@[.5:.95], AP@[.5], AP@[.75] and AP per IoU threshold
|
|
736
|
+
"""
|
|
737
|
+
if len(self._gts) == 0:
|
|
738
|
+
raise AssertionError("No samples added")
|
|
739
|
+
|
|
740
|
+
# Determine classes
|
|
741
|
+
if self.num_classes is None:
|
|
742
|
+
labels = []
|
|
743
|
+
for g in self._gts:
|
|
744
|
+
labels.extend(g["labels"].tolist())
|
|
745
|
+
for p in self._preds:
|
|
746
|
+
labels.extend(p["labels"].tolist())
|
|
747
|
+
classes = np.unique(labels)
|
|
748
|
+
else:
|
|
749
|
+
classes = np.arange(self.num_classes)
|
|
750
|
+
|
|
751
|
+
ap_per_iou = {}
|
|
752
|
+
|
|
753
|
+
for iou_thresh in self.iou_thresholds:
|
|
754
|
+
class_aps = []
|
|
755
|
+
|
|
756
|
+
for c in classes:
|
|
757
|
+
# Collect GTs per image
|
|
758
|
+
gt_by_image = {}
|
|
759
|
+
total_gt = 0
|
|
760
|
+
|
|
761
|
+
for img_idx, gt in enumerate(self._gts):
|
|
762
|
+
mask = gt["labels"] == c
|
|
763
|
+
gt_boxes = gt["boxes"][mask]
|
|
764
|
+
|
|
765
|
+
gt_by_image[img_idx] = {
|
|
766
|
+
"boxes": gt_boxes,
|
|
767
|
+
"matched": np.zeros(len(gt_boxes), dtype=bool),
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
total_gt += len(gt_boxes)
|
|
771
|
+
|
|
772
|
+
if total_gt == 0:
|
|
773
|
+
continue
|
|
774
|
+
|
|
775
|
+
# Collect all detections globally
|
|
776
|
+
detections = []
|
|
777
|
+
|
|
778
|
+
for img_idx, pred in enumerate(self._preds):
|
|
779
|
+
mask = pred["labels"] == c
|
|
780
|
+
|
|
781
|
+
pred_boxes = pred["boxes"][mask]
|
|
782
|
+
pred_scores = pred["scores"][mask]
|
|
783
|
+
|
|
784
|
+
for box, score in zip(pred_boxes, pred_scores):
|
|
785
|
+
detections.append({
|
|
786
|
+
"image_id": img_idx,
|
|
787
|
+
"box": box,
|
|
788
|
+
"score": float(score),
|
|
789
|
+
})
|
|
790
|
+
|
|
791
|
+
if len(detections) == 0:
|
|
792
|
+
class_aps.append(0.0)
|
|
793
|
+
continue
|
|
794
|
+
|
|
795
|
+
# Global sorting COCO-style
|
|
796
|
+
detections.sort(key=lambda x: -x["score"])
|
|
797
|
+
|
|
798
|
+
tp = np.zeros(len(detections))
|
|
799
|
+
fp = np.zeros(len(detections))
|
|
800
|
+
|
|
801
|
+
# Evaluate detections
|
|
802
|
+
for det_idx, det in enumerate(detections):
|
|
803
|
+
img_idx = det["image_id"]
|
|
804
|
+
pred_box = det["box"]
|
|
805
|
+
|
|
806
|
+
gt_data = gt_by_image[img_idx]
|
|
807
|
+
gt_boxes = gt_data["boxes"]
|
|
808
|
+
|
|
809
|
+
if len(gt_boxes) == 0:
|
|
810
|
+
fp[det_idx] = 1
|
|
811
|
+
continue
|
|
812
|
+
|
|
813
|
+
# Compute IoUs
|
|
814
|
+
if self.use_polygons:
|
|
815
|
+
iou_mat = polygon_iou(
|
|
816
|
+
gt_boxes,
|
|
817
|
+
np.expand_dims(pred_box, axis=0),
|
|
818
|
+
)
|
|
819
|
+
else:
|
|
820
|
+
iou_mat = box_iou(
|
|
821
|
+
gt_boxes,
|
|
822
|
+
np.expand_dims(pred_box, axis=0),
|
|
823
|
+
)
|
|
824
|
+
|
|
825
|
+
ious = iou_mat[:, 0]
|
|
826
|
+
|
|
827
|
+
best_gt = np.argmax(ious)
|
|
828
|
+
best_iou = ious[best_gt]
|
|
829
|
+
|
|
830
|
+
if best_iou >= iou_thresh and not gt_data["matched"][best_gt]:
|
|
831
|
+
tp[det_idx] = 1
|
|
832
|
+
gt_data["matched"][best_gt] = True
|
|
833
|
+
else:
|
|
834
|
+
fp[det_idx] = 1
|
|
835
|
+
|
|
836
|
+
# Precision / Recall
|
|
837
|
+
tp_cum = np.cumsum(tp)
|
|
838
|
+
fp_cum = np.cumsum(fp)
|
|
839
|
+
|
|
840
|
+
recall = tp_cum / total_gt
|
|
841
|
+
precision = tp_cum / np.maximum(tp_cum + fp_cum, 1e-8)
|
|
842
|
+
|
|
843
|
+
ap = self._compute_ap(recall, precision)
|
|
844
|
+
class_aps.append(ap)
|
|
845
|
+
|
|
846
|
+
ap_per_iou[float(iou_thresh)] = float(np.mean(class_aps)) if len(class_aps) > 0 else 0.0
|
|
847
|
+
|
|
848
|
+
map_value = float(np.mean(list(ap_per_iou.values())))
|
|
849
|
+
ap50 = ap_per_iou.get(0.5, 0.0)
|
|
850
|
+
ap75 = ap_per_iou.get(0.75, 0.0)
|
|
851
|
+
|
|
852
|
+
return {
|
|
853
|
+
"mAP@[.5:.95]": map_value,
|
|
854
|
+
"AP@[.5]": ap50,
|
|
855
|
+
"AP@[.75]": ap75,
|
|
856
|
+
"AP_per_IoU": ap_per_iou,
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
def _compute_ap(self, recall: np.ndarray, precision: np.ndarray) -> float:
|
|
860
|
+
"""Computes the Average Precision using the 101-point interpolation method from COCO
|
|
861
|
+
|
|
862
|
+
Args:
|
|
863
|
+
recall: array of recall values
|
|
864
|
+
precision: array of precision values
|
|
865
|
+
|
|
866
|
+
Returns:
|
|
867
|
+
the Average Precision score
|
|
868
|
+
"""
|
|
869
|
+
# 101-point interpolation as per COCO
|
|
870
|
+
precision = np.maximum.accumulate(precision[::-1])[::-1]
|
|
871
|
+
|
|
872
|
+
recall_levels = np.linspace(0, 1, 101)
|
|
873
|
+
precisions = np.zeros_like(recall_levels)
|
|
874
|
+
|
|
875
|
+
for i, r in enumerate(recall_levels):
|
|
876
|
+
p = precision[recall >= r]
|
|
877
|
+
precisions[i] = np.max(p) if p.size > 0 else 0.0
|
|
878
|
+
|
|
879
|
+
return float(np.mean(precisions))
|
|
880
|
+
|
|
881
|
+
def reset(self):
|
|
882
|
+
self._gts = []
|
|
883
|
+
self._preds = []
|
doctr/utils/multithreading.py
CHANGED
|
@@ -36,13 +36,16 @@ def multithread_exec(func: Callable[[Any], Any], seq: Iterable[Any], threads: in
|
|
|
36
36
|
you might want to disable multiprocessing. To achieve that, set 'DOCTR_MULTIPROCESSING_DISABLE' to 'TRUE'.
|
|
37
37
|
"""
|
|
38
38
|
threads = threads if isinstance(threads, int) else min(16, mp.cpu_count())
|
|
39
|
+
items = seq if isinstance(seq, (list, tuple)) else list(seq)
|
|
40
|
+
# Never spawn more workers than items - single-item calls skip pool startup entirely
|
|
41
|
+
threads = min(threads, len(items))
|
|
39
42
|
# Single-thread
|
|
40
43
|
if threads < 2 or os.environ.get("DOCTR_MULTIPROCESSING_DISABLE", "").upper() in ENV_VARS_TRUE_VALUES:
|
|
41
|
-
results = map(func,
|
|
44
|
+
results = map(func, items)
|
|
42
45
|
# Multi-threading
|
|
43
46
|
else:
|
|
44
47
|
with ThreadPool(threads) as tp:
|
|
45
48
|
# ThreadPool's map function returns a list, but seq could be of a different type
|
|
46
49
|
# That's why wrapping result in map to return iterator
|
|
47
|
-
results = map(lambda x: x, tp.map(func,
|
|
50
|
+
results = map(lambda x: x, tp.map(func, items)) # noqa: C417
|
|
48
51
|
return results
|