python-doctr 1.0.0__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/contrib/artefacts.py +1 -1
- doctr/contrib/base.py +1 -1
- doctr/datasets/__init__.py +2 -0
- doctr/datasets/coco_text.py +5 -3
- doctr/datasets/cord.py +3 -2
- doctr/datasets/datasets/base.py +13 -25
- doctr/datasets/datasets/pytorch.py +15 -5
- doctr/datasets/detection.py +3 -2
- doctr/datasets/doc_artefacts.py +3 -2
- doctr/datasets/funsd.py +3 -2
- doctr/datasets/generator/base.py +6 -5
- doctr/datasets/generator/pytorch.py +5 -6
- doctr/datasets/ic03.py +4 -3
- doctr/datasets/ic13.py +5 -3
- doctr/datasets/iiit5k.py +3 -2
- doctr/datasets/iiithws.py +5 -3
- doctr/datasets/imgur5k.py +5 -3
- doctr/datasets/layout.py +123 -0
- doctr/datasets/mjsynth.py +5 -3
- doctr/datasets/ocr.py +3 -2
- doctr/datasets/orientation.py +3 -2
- doctr/datasets/recognition.py +3 -2
- doctr/datasets/sroie.py +3 -2
- doctr/datasets/svhn.py +3 -2
- doctr/datasets/svt.py +4 -3
- doctr/datasets/synthtext.py +3 -2
- doctr/datasets/table_structure.py +97 -0
- doctr/datasets/utils.py +15 -6
- doctr/datasets/vocabs.py +3 -1
- doctr/datasets/wildreceipt.py +5 -3
- doctr/file_utils.py +4 -2
- doctr/io/__init__.py +1 -0
- doctr/io/elements.py +253 -261
- doctr/io/exporters.py +1275 -0
- doctr/io/html.py +1 -1
- doctr/io/image/base.py +4 -3
- doctr/io/image/pytorch.py +6 -4
- doctr/io/pdf.py +1 -1
- doctr/io/reader.py +1 -1
- doctr/models/__init__.py +2 -0
- doctr/models/_utils.py +111 -25
- doctr/models/builder.py +533 -62
- doctr/models/classification/__init__.py +2 -0
- doctr/models/classification/magc_resnet/pytorch.py +2 -2
- doctr/models/classification/mobilenet/pytorch.py +7 -7
- doctr/models/classification/predictor/pytorch.py +7 -3
- doctr/models/classification/resnet/pytorch.py +6 -6
- doctr/models/classification/starnet/__init__.py +1 -0
- doctr/models/classification/starnet/pytorch.py +202 -0
- doctr/models/classification/textnet/pytorch.py +7 -6
- doctr/models/classification/vgg/pytorch.py +4 -3
- doctr/models/classification/vip/layers/pytorch.py +5 -5
- doctr/models/classification/vip/pytorch.py +5 -5
- doctr/models/classification/vit/pytorch.py +4 -4
- 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 +4 -1
- doctr/models/core.py +1 -1
- doctr/models/detection/_utils/base.py +24 -8
- doctr/models/detection/_utils/pytorch.py +1 -1
- doctr/models/detection/core.py +34 -19
- doctr/models/detection/differentiable_binarization/base.py +7 -5
- doctr/models/detection/differentiable_binarization/pytorch.py +4 -4
- doctr/models/detection/fast/base.py +6 -2
- doctr/models/detection/fast/pytorch.py +4 -4
- doctr/models/detection/linknet/base.py +6 -2
- doctr/models/detection/linknet/pytorch.py +4 -4
- doctr/models/detection/predictor/pytorch.py +4 -3
- doctr/models/detection/zoo.py +3 -3
- doctr/models/factory/hub.py +72 -52
- doctr/models/kie_predictor/base.py +17 -2
- doctr/models/kie_predictor/pytorch.py +42 -11
- 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 +140 -4
- doctr/models/modules/transformer/pytorch.py +1 -1
- doctr/models/modules/vision_transformer/pytorch.py +1 -1
- doctr/models/predictor/base.py +138 -16
- doctr/models/predictor/pytorch.py +151 -9
- doctr/models/preprocessor/pytorch.py +78 -23
- doctr/models/reading_order/__init__.py +1 -0
- doctr/models/reading_order/base.py +667 -0
- doctr/models/recognition/core.py +1 -1
- doctr/models/recognition/crnn/pytorch.py +6 -8
- doctr/models/recognition/master/base.py +1 -1
- doctr/models/recognition/master/pytorch.py +7 -8
- doctr/models/recognition/parseq/base.py +1 -1
- doctr/models/recognition/parseq/pytorch.py +5 -5
- doctr/models/recognition/predictor/_utils.py +1 -1
- doctr/models/recognition/predictor/pytorch.py +2 -2
- doctr/models/recognition/sar/pytorch.py +2 -2
- doctr/models/recognition/utils.py +9 -11
- doctr/models/recognition/viptr/pytorch.py +4 -6
- doctr/models/recognition/vitstr/base.py +1 -1
- doctr/models/recognition/vitstr/pytorch.py +6 -6
- doctr/models/recognition/zoo.py +6 -7
- 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 +316 -16
- doctr/models/zoo.py +91 -3
- doctr/transforms/functional/base.py +3 -2
- doctr/transforms/functional/pytorch.py +1 -1
- doctr/transforms/modules/base.py +248 -83
- doctr/transforms/modules/pytorch.py +213 -74
- doctr/utils/common_types.py +22 -2
- doctr/utils/data.py +5 -4
- doctr/utils/fonts.py +56 -17
- doctr/utils/geometry.py +136 -19
- doctr/utils/metrics.py +351 -19
- doctr/utils/multithreading.py +6 -3
- doctr/utils/reconstitution.py +697 -133
- doctr/utils/repr.py +1 -1
- doctr/utils/visualization.py +63 -4
- doctr/version.py +1 -1
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/METADATA +73 -26
- python_doctr-1.1.0.dist-info/RECORD +179 -0
- {python_doctr-1.0.0.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.0.dist-info/RECORD +0 -149
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/licenses/LICENSE +0 -0
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/top_level.txt +0 -0
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/zip-safe +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# Copyright (C) 2021-
|
|
1
|
+
# Copyright (C) 2021-2026, Mindee.
|
|
2
2
|
|
|
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.
|
|
@@ -12,6 +12,7 @@ from torch import nn
|
|
|
12
12
|
from doctr.io.elements import Document
|
|
13
13
|
from doctr.models._utils import get_language, invert_data_structure
|
|
14
14
|
from doctr.models.detection.predictor import DetectionPredictor
|
|
15
|
+
from doctr.models.layout.predictor import LayoutPredictor
|
|
15
16
|
from doctr.models.recognition.predictor import RecognitionPredictor
|
|
16
17
|
from doctr.utils.geometry import detach_scores
|
|
17
18
|
|
|
@@ -35,6 +36,9 @@ class KIEPredictor(nn.Module, _KIEPredictor):
|
|
|
35
36
|
page. Doing so will slightly deteriorate the overall latency.
|
|
36
37
|
detect_language: if True, the language prediction will be added to the predictions for each
|
|
37
38
|
page. Doing so will slightly deteriorate the overall latency.
|
|
39
|
+
preserve_original_coords: if True and straighten_pages is True, bounding boxes are mapped back to the
|
|
40
|
+
original page coordinates. Useful for redaction and annotation.
|
|
41
|
+
layout_predictor: optional layout detection module
|
|
38
42
|
**kwargs: keyword args of `DocumentBuilder`
|
|
39
43
|
"""
|
|
40
44
|
|
|
@@ -48,6 +52,8 @@ class KIEPredictor(nn.Module, _KIEPredictor):
|
|
|
48
52
|
symmetric_pad: bool = True,
|
|
49
53
|
detect_orientation: bool = False,
|
|
50
54
|
detect_language: bool = False,
|
|
55
|
+
preserve_original_coords: bool = False,
|
|
56
|
+
layout_predictor: LayoutPredictor | None = None,
|
|
51
57
|
**kwargs: Any,
|
|
52
58
|
) -> None:
|
|
53
59
|
nn.Module.__init__(self)
|
|
@@ -60,10 +66,12 @@ class KIEPredictor(nn.Module, _KIEPredictor):
|
|
|
60
66
|
preserve_aspect_ratio,
|
|
61
67
|
symmetric_pad,
|
|
62
68
|
detect_orientation,
|
|
69
|
+
preserve_original_coords=preserve_original_coords,
|
|
63
70
|
**kwargs,
|
|
64
71
|
)
|
|
65
72
|
self.detect_orientation = detect_orientation
|
|
66
73
|
self.detect_language = detect_language
|
|
74
|
+
self.layout_predictor = layout_predictor.eval() if layout_predictor is not None else None
|
|
67
75
|
|
|
68
76
|
@torch.inference_mode()
|
|
69
77
|
def forward(
|
|
@@ -77,16 +85,25 @@ class KIEPredictor(nn.Module, _KIEPredictor):
|
|
|
77
85
|
|
|
78
86
|
origin_page_shapes = [page.shape[:2] for page in pages]
|
|
79
87
|
|
|
80
|
-
|
|
81
|
-
|
|
88
|
+
if not self.straighten_pages:
|
|
89
|
+
# Detect layout regions on the pages
|
|
90
|
+
regions = self.layout_predictor(pages, **kwargs) if self.layout_predictor is not None else None
|
|
91
|
+
det_pages = self._mask_regions(pages, regions)
|
|
92
|
+
else:
|
|
93
|
+
det_pages = pages
|
|
94
|
+
|
|
95
|
+
# Localize text elements (segmentation maps are only materialized when actually consumed)
|
|
96
|
+
if self.detect_orientation or self.straighten_pages:
|
|
97
|
+
loc_preds, out_maps = self.det_predictor(det_pages, return_maps=True, **kwargs)
|
|
98
|
+
bin_thresh = kwargs.get("bin_thresh", getattr(self.det_predictor.model.postprocessor, "bin_thresh", 0.3))
|
|
99
|
+
seg_maps = [
|
|
100
|
+
((np.expand_dims(np.amax(out_map, axis=-1), axis=-1) > bin_thresh).astype(np.uint8) * 255)
|
|
101
|
+
for out_map in out_maps
|
|
102
|
+
]
|
|
103
|
+
else:
|
|
104
|
+
loc_preds = self.det_predictor(det_pages, **kwargs)
|
|
82
105
|
|
|
83
106
|
# Detect document rotation and rotate pages
|
|
84
|
-
seg_maps = [
|
|
85
|
-
np.where(np.expand_dims(np.amax(out_map, axis=-1), axis=-1) > kwargs.get("bin_thresh", 0.3), 255, 0).astype(
|
|
86
|
-
np.uint8
|
|
87
|
-
)
|
|
88
|
-
for out_map in out_maps
|
|
89
|
-
]
|
|
90
107
|
if self.detect_orientation:
|
|
91
108
|
general_pages_orientations, origin_pages_orientations = self._get_orientations(pages, seg_maps)
|
|
92
109
|
orientations = [
|
|
@@ -97,12 +114,21 @@ class KIEPredictor(nn.Module, _KIEPredictor):
|
|
|
97
114
|
general_pages_orientations = None
|
|
98
115
|
origin_pages_orientations = None
|
|
99
116
|
if self.straighten_pages:
|
|
100
|
-
|
|
117
|
+
_orig_shapes = origin_page_shapes
|
|
118
|
+
_orig_pages = list(pages)
|
|
119
|
+
pages, m_invs = self._straighten_pages(
|
|
120
|
+
pages, seg_maps, general_pages_orientations, origin_pages_orientations
|
|
121
|
+
)
|
|
101
122
|
# update page shapes after straightening
|
|
102
123
|
origin_page_shapes = [page.shape[:2] for page in pages]
|
|
124
|
+
_straight_shapes = origin_page_shapes
|
|
125
|
+
|
|
126
|
+
# Detect layout regions on the pages
|
|
127
|
+
regions = self.layout_predictor(pages, **kwargs) if self.layout_predictor is not None else None
|
|
128
|
+
det_pages = self._mask_regions(pages, regions)
|
|
103
129
|
|
|
104
130
|
# Forward again to get predictions on straight pages
|
|
105
|
-
loc_preds = self.det_predictor(
|
|
131
|
+
loc_preds = self.det_predictor(det_pages, **kwargs)
|
|
106
132
|
|
|
107
133
|
dict_loc_preds: dict[str, list[np.ndarray]] = invert_data_structure(loc_preds) # type: ignore[assignment]
|
|
108
134
|
|
|
@@ -173,7 +199,12 @@ class KIEPredictor(nn.Module, _KIEPredictor):
|
|
|
173
199
|
crop_orientations_per_page,
|
|
174
200
|
orientations,
|
|
175
201
|
languages_dict,
|
|
202
|
+
regions,
|
|
176
203
|
)
|
|
204
|
+
|
|
205
|
+
# manipulate the already built Document to restore the original pages / shapes and geometries
|
|
206
|
+
if self.straighten_pages and self.preserve_original_coords:
|
|
207
|
+
out = self._remap_to_original_coords(out, _orig_shapes, _straight_shapes, m_invs, _orig_pages) # type: ignore[assignment]
|
|
177
208
|
return out
|
|
178
209
|
|
|
179
210
|
@staticmethod
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .pytorch import *
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
# Copyright (C) 2021-2026, Mindee.
|
|
2
|
+
|
|
3
|
+
# This program is licensed under the Apache License 2.0.
|
|
4
|
+
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
|
|
5
|
+
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import cv2
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
from doctr.models.core import BaseModel
|
|
12
|
+
from doctr.utils import order_points
|
|
13
|
+
|
|
14
|
+
__all__ = ["_LWDETR", "LWDETRPostProcessor"]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class LWDETRPostProcessor:
|
|
18
|
+
"""Implements a post processor for LW-DETR model
|
|
19
|
+
|
|
20
|
+
Args:
|
|
21
|
+
num_classes: number of classes
|
|
22
|
+
score_thresh: confidence threshold for filtering predictions
|
|
23
|
+
iou_thresh: IoU threshold for NMS
|
|
24
|
+
topk: number of top predictions to keep before NMS
|
|
25
|
+
assume_straight_pages: whether the pages are assumed to be straight (i.e., no rotation)
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def __init__(
|
|
29
|
+
self,
|
|
30
|
+
num_classes: int,
|
|
31
|
+
score_thresh: float = 0.5,
|
|
32
|
+
iou_thresh: float = 0.5,
|
|
33
|
+
topk: int = 300,
|
|
34
|
+
assume_straight_pages: bool = True,
|
|
35
|
+
):
|
|
36
|
+
self.num_classes = num_classes
|
|
37
|
+
self.score_thresh = score_thresh
|
|
38
|
+
self.iou_thresh = iou_thresh
|
|
39
|
+
self.topk = topk
|
|
40
|
+
self.assume_straight_pages = assume_straight_pages
|
|
41
|
+
|
|
42
|
+
def _decode_boxes(self, boxes: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
|
43
|
+
"""Decode the predicted boxes from OBB format to polygon format
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
boxes: array of predicted boxes in OBB format (N, 6) (cx, cy, w, h, sin(theta), cos(theta))
|
|
47
|
+
|
|
48
|
+
Returns:
|
|
49
|
+
tuple of (polys, angles) where polys is an array of decoded polygons (N, 4, 2)
|
|
50
|
+
and angles is an array of angles in radians (N,)
|
|
51
|
+
"""
|
|
52
|
+
cx, cy, w, h = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
|
|
53
|
+
sin, cos = boxes[:, 4], boxes[:, 5]
|
|
54
|
+
|
|
55
|
+
angles = np.arctan2(sin, cos)
|
|
56
|
+
|
|
57
|
+
polys = []
|
|
58
|
+
for i in range(len(boxes)):
|
|
59
|
+
rect = ((float(cx[i]), float(cy[i])), (float(w[i]), float(h[i])), float(np.degrees(angles[i])))
|
|
60
|
+
|
|
61
|
+
poly = order_points(cv2.boxPoints(rect))
|
|
62
|
+
polys.append(poly)
|
|
63
|
+
|
|
64
|
+
return np.asarray(polys, dtype=np.float32), angles
|
|
65
|
+
|
|
66
|
+
def _iou(self, poly1: np.ndarray, poly2: np.ndarray) -> float:
|
|
67
|
+
"""Compute the IoU between two polygons
|
|
68
|
+
|
|
69
|
+
Args:
|
|
70
|
+
poly1: first polygon (4, 2)
|
|
71
|
+
poly2: second polygon (4, 2)
|
|
72
|
+
|
|
73
|
+
Returns:
|
|
74
|
+
IoU between the two polygons
|
|
75
|
+
"""
|
|
76
|
+
inter = cv2.intersectConvexConvex(
|
|
77
|
+
poly1.astype(np.float32),
|
|
78
|
+
poly2.astype(np.float32),
|
|
79
|
+
)[0]
|
|
80
|
+
|
|
81
|
+
if inter <= 0:
|
|
82
|
+
return 0.0
|
|
83
|
+
|
|
84
|
+
area1 = cv2.contourArea(poly1)
|
|
85
|
+
area2 = cv2.contourArea(poly2)
|
|
86
|
+
|
|
87
|
+
return inter / (area1 + area2 - inter + 1e-6)
|
|
88
|
+
|
|
89
|
+
def _nms(self, polys: np.ndarray, scores: np.ndarray, labels: np.ndarray) -> list[int]:
|
|
90
|
+
"""
|
|
91
|
+
Class-wise greedy NMS for rotated polygons.
|
|
92
|
+
|
|
93
|
+
Args:
|
|
94
|
+
polys: (N, 4, 2)
|
|
95
|
+
scores: (N,)
|
|
96
|
+
labels: (N,)
|
|
97
|
+
|
|
98
|
+
Returns:
|
|
99
|
+
indices kept after NMS (global indices)
|
|
100
|
+
"""
|
|
101
|
+
if len(polys) == 0:
|
|
102
|
+
return []
|
|
103
|
+
|
|
104
|
+
keep: list[int] = []
|
|
105
|
+
|
|
106
|
+
# Process each class independently
|
|
107
|
+
for cls in np.unique(labels):
|
|
108
|
+
cls_idxs = np.where(labels == cls)[0]
|
|
109
|
+
if len(cls_idxs) == 0:
|
|
110
|
+
continue
|
|
111
|
+
|
|
112
|
+
cls_scores = scores[cls_idxs]
|
|
113
|
+
cls_polys = polys[cls_idxs]
|
|
114
|
+
|
|
115
|
+
# sort by confidence
|
|
116
|
+
order = np.argsort(cls_scores)[::-1]
|
|
117
|
+
cls_idxs = cls_idxs[order]
|
|
118
|
+
cls_polys = cls_polys[order]
|
|
119
|
+
cls_scores = cls_scores[order]
|
|
120
|
+
|
|
121
|
+
suppressed = np.zeros(len(cls_idxs), dtype=bool)
|
|
122
|
+
|
|
123
|
+
for i in range(len(cls_idxs)):
|
|
124
|
+
if suppressed[i]:
|
|
125
|
+
continue
|
|
126
|
+
|
|
127
|
+
keep.append(cls_idxs[i])
|
|
128
|
+
|
|
129
|
+
# compare current box with the rest
|
|
130
|
+
for j in range(i + 1, len(cls_idxs)):
|
|
131
|
+
if suppressed[j]:
|
|
132
|
+
continue
|
|
133
|
+
|
|
134
|
+
iou = self._iou(cls_polys[i], cls_polys[j])
|
|
135
|
+
if iou >= self.iou_thresh:
|
|
136
|
+
suppressed[j] = True
|
|
137
|
+
return keep
|
|
138
|
+
|
|
139
|
+
def __call__(self, logits: np.ndarray, boxes: np.ndarray) -> list[tuple[list[int], np.ndarray, list[float]]]:
|
|
140
|
+
logits = np.asarray(logits)
|
|
141
|
+
boxes = np.asarray(boxes)
|
|
142
|
+
|
|
143
|
+
results: list[tuple[list[int], np.ndarray, list[float]]] = []
|
|
144
|
+
|
|
145
|
+
for b in range(boxes.shape[0]):
|
|
146
|
+
# Sigmoid scores (the model is trained with a sigmoid-based (IA-BCE) loss without
|
|
147
|
+
# a background class)
|
|
148
|
+
prob = 1.0 / (1.0 + np.exp(-logits[b])) # (num_queries, num_classes)
|
|
149
|
+
num_classes = prob.shape[-1]
|
|
150
|
+
|
|
151
|
+
# Keep only the topk (query, class) pairs before NMS
|
|
152
|
+
flat_prob = prob.reshape(-1)
|
|
153
|
+
topk = min(self.topk, flat_prob.size) if self.topk is not None else flat_prob.size
|
|
154
|
+
topk_idxs = np.argsort(flat_prob)[::-1][:topk]
|
|
155
|
+
|
|
156
|
+
scores_b = flat_prob[topk_idxs]
|
|
157
|
+
labels_b = topk_idxs % num_classes
|
|
158
|
+
query_idxs = topk_idxs // num_classes
|
|
159
|
+
bboxes = boxes[b][query_idxs]
|
|
160
|
+
|
|
161
|
+
mask = scores_b > self.score_thresh
|
|
162
|
+
|
|
163
|
+
bboxes = bboxes[mask]
|
|
164
|
+
scores_b = scores_b[mask]
|
|
165
|
+
labels_b = labels_b[mask]
|
|
166
|
+
|
|
167
|
+
polys, _ = (
|
|
168
|
+
self._decode_boxes(bboxes)
|
|
169
|
+
if len(bboxes) > 0
|
|
170
|
+
else (
|
|
171
|
+
np.zeros((0, 4, 2), dtype=np.float32),
|
|
172
|
+
np.zeros((0,), dtype=np.float32),
|
|
173
|
+
)
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
keep = self._nms(polys, scores_b, labels_b) if len(polys) > 0 else []
|
|
177
|
+
|
|
178
|
+
final_labels = []
|
|
179
|
+
final_boxes = []
|
|
180
|
+
final_scores = []
|
|
181
|
+
|
|
182
|
+
for idx in keep:
|
|
183
|
+
poly = polys[idx].reshape(-1).tolist()
|
|
184
|
+
if self.assume_straight_pages:
|
|
185
|
+
x_coords = poly[0::2]
|
|
186
|
+
y_coords = poly[1::2]
|
|
187
|
+
xmin, xmax = min(x_coords), max(x_coords)
|
|
188
|
+
ymin, ymax = min(y_coords), max(y_coords)
|
|
189
|
+
final_boxes.append([xmin, ymin, xmax, ymax])
|
|
190
|
+
else:
|
|
191
|
+
final_boxes.append(poly)
|
|
192
|
+
|
|
193
|
+
final_labels.append(int(labels_b[idx]))
|
|
194
|
+
final_scores.append(float(scores_b[idx]))
|
|
195
|
+
|
|
196
|
+
final_boxes_arr = (
|
|
197
|
+
np.asarray(final_boxes, dtype=np.float32).reshape(-1, 4, 2)
|
|
198
|
+
if not self.assume_straight_pages
|
|
199
|
+
else np.asarray(final_boxes, dtype=np.float32).reshape(-1, 4)
|
|
200
|
+
).clip(0, 1)
|
|
201
|
+
|
|
202
|
+
results.append((
|
|
203
|
+
final_labels,
|
|
204
|
+
final_boxes_arr,
|
|
205
|
+
final_scores,
|
|
206
|
+
))
|
|
207
|
+
|
|
208
|
+
return results
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
class _LWDETR(BaseModel):
|
|
212
|
+
"""LW-DETR as described in `"LW-DETR: A Transformer Replacement to YOLO for Real-Time Detection"
|
|
213
|
+
<https://arxiv.org/pdf/2406.03459v1>`_.
|
|
214
|
+
"""
|
|
215
|
+
|
|
216
|
+
def build_target(
|
|
217
|
+
self,
|
|
218
|
+
target: list[dict[str, np.ndarray]],
|
|
219
|
+
class_names: list[str],
|
|
220
|
+
) -> list[dict[str, Any]]:
|
|
221
|
+
"""Build the target for LW-DETR training
|
|
222
|
+
|
|
223
|
+
Args:
|
|
224
|
+
target: list of dictionaries where each dictionary corresponds to a sample and has keys corresponding
|
|
225
|
+
to class names and values corresponding to lists of boxes in either polygon format (4, 2)
|
|
226
|
+
or bounding box format (4,) (xmin, ymin, xmax, ymax)
|
|
227
|
+
class_names: list of class names
|
|
228
|
+
|
|
229
|
+
Returns:
|
|
230
|
+
list of dictionaries with keys "boxes" and "labels" where "boxes" is an array of shape (num_boxes, 6)
|
|
231
|
+
containing the box parameters in OBB format (cx, cy, w, h, sin(theta), cos(theta))
|
|
232
|
+
and "labels" is an array of shape (num_boxes,) containing the class labels
|
|
233
|
+
"""
|
|
234
|
+
targets = []
|
|
235
|
+
class_to_id = {name: i for i, name in enumerate(class_names)}
|
|
236
|
+
|
|
237
|
+
def _quad_to_obb(poly: np.ndarray):
|
|
238
|
+
poly = np.asarray(poly, dtype=np.float32)
|
|
239
|
+
|
|
240
|
+
# Center point is simply the average of the relative vertices
|
|
241
|
+
cx, cy = np.mean(poly, axis=0)
|
|
242
|
+
|
|
243
|
+
edges = np.stack([
|
|
244
|
+
poly[1] - poly[0],
|
|
245
|
+
poly[2] - poly[1],
|
|
246
|
+
poly[3] - poly[2],
|
|
247
|
+
poly[0] - poly[3],
|
|
248
|
+
])
|
|
249
|
+
|
|
250
|
+
lengths = np.linalg.norm(edges, axis=1)
|
|
251
|
+
i = np.argmax(lengths)
|
|
252
|
+
dx, dy = edges[i]
|
|
253
|
+
|
|
254
|
+
theta = np.arctan2(dy, dx)
|
|
255
|
+
|
|
256
|
+
# Width and height remain cleanly in relative coordinate space [0, 1]
|
|
257
|
+
w = np.mean([lengths[i], lengths[(i + 2) % 4]])
|
|
258
|
+
h = np.mean([lengths[(i + 1) % 4], lengths[(i + 3) % 4]])
|
|
259
|
+
|
|
260
|
+
# Enforce strict unit-length normal vectors for rotation
|
|
261
|
+
sin_t = np.sin(theta)
|
|
262
|
+
cos_t = np.cos(theta)
|
|
263
|
+
norm = np.sqrt(sin_t**2 + cos_t**2) + 1e-8
|
|
264
|
+
|
|
265
|
+
return np.array(
|
|
266
|
+
[cx, cy, w, h, sin_t / norm, cos_t / norm],
|
|
267
|
+
dtype=np.float32,
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
def to_quad(box: np.ndarray):
|
|
271
|
+
box = np.asarray(box, dtype=np.float32)
|
|
272
|
+
if box.shape == (4,):
|
|
273
|
+
x1, y1, x2, y2 = box
|
|
274
|
+
return np.array([[x1, y1], [x2, y1], [x2, y2], [x1, y2]], dtype=np.float32)
|
|
275
|
+
if box.shape == (4, 2):
|
|
276
|
+
return box.astype(np.float32)
|
|
277
|
+
raise ValueError(f"Unsupported box shape: {box.shape}") # pragma: no cover
|
|
278
|
+
|
|
279
|
+
for sample in target:
|
|
280
|
+
boxes_all = []
|
|
281
|
+
labels_all = []
|
|
282
|
+
|
|
283
|
+
for class_name, boxes in sample.items():
|
|
284
|
+
if class_name not in class_to_id:
|
|
285
|
+
raise ValueError(f"Unknown class name: {class_name}") # pragma: no cover
|
|
286
|
+
|
|
287
|
+
cls_id = class_to_id[class_name]
|
|
288
|
+
boxes = np.asarray(boxes)
|
|
289
|
+
|
|
290
|
+
if boxes.ndim == 1:
|
|
291
|
+
boxes = boxes[None, :]
|
|
292
|
+
|
|
293
|
+
for box in boxes:
|
|
294
|
+
poly = to_quad(box)
|
|
295
|
+
obb = _quad_to_obb(poly)
|
|
296
|
+
|
|
297
|
+
# filter out degenerate boxes
|
|
298
|
+
if obb[2] <= 1e-5 or obb[3] <= 1e-5:
|
|
299
|
+
continue
|
|
300
|
+
|
|
301
|
+
boxes_all.append(obb)
|
|
302
|
+
labels_all.append(cls_id)
|
|
303
|
+
|
|
304
|
+
targets.append({
|
|
305
|
+
"boxes": np.asarray(boxes_all, dtype=np.float32) if boxes_all else np.zeros((0, 6), dtype=np.float32),
|
|
306
|
+
"labels": np.asarray(labels_all, dtype=np.int64),
|
|
307
|
+
})
|
|
308
|
+
|
|
309
|
+
return targets
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .pytorch import *
|