cedarrapidsboy commited on
Commit
fa7afba
·
verified ·
1 Parent(s): fd214a5

Upload detect_and_order.py

Browse files
Files changed (1) hide show
  1. detect_and_order.py +145 -0
detect_and_order.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Bare-minimum example: detect comic panels on a page image and predict
4
+ their reading order, using the two ONNX models published in this repo's
5
+ Hugging Face model card (panel-detector.onnx + panel-order-model.onnx).
6
+
7
+ pip install onnxruntime opencv-python numpy
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import sys
13
+
14
+ import cv2
15
+ import numpy as np
16
+ import onnxruntime as ort
17
+
18
+ DETECTOR_PATH = "best.onnx" # YOLOv8-n panel detector
19
+ ORDER_PATH = "panel-order-model.onnx" # pairwise reading-order classifier
20
+
21
+ CONF_THRESH = 0.25
22
+ NMS_THRESH = 0.45
23
+ IMG_SIZE = 640
24
+
25
+
26
+ def detect_panels(image_bgr: np.ndarray, session: ort.InferenceSession) -> list[dict]:
27
+ """Run the YOLOv8-n detector and return panel boxes as page-relative
28
+ (0..1) {x, y, w, h} dicts, x/y being the top-left corner."""
29
+ # NOTE: plain resize, not letterboxed — fine for this example, but a
30
+ # production pipeline should letterbox (pad to square) like Ultralytics
31
+ # does during training, for best accuracy on non-square pages.
32
+ resized = cv2.resize(image_bgr, (IMG_SIZE, IMG_SIZE))
33
+ rgb = cv2.cvtColor(resized, cv2.COLOR_BGR2RGB).astype(np.float32) / 255.0
34
+ blob = np.transpose(rgb, (2, 0, 1))[None] # NCHW
35
+
36
+ input_name = session.get_inputs()[0].name
37
+ output = session.run(None, {input_name: blob})[0][0].T # (N, 5): cx,cy,w,h,conf
38
+
39
+ boxes_xywh, scores = [], []
40
+ for cx, cy, w, h, conf in output:
41
+ if conf < CONF_THRESH:
42
+ continue
43
+ boxes_xywh.append([float(cx - w / 2), float(cy - h / 2), float(w), float(h)])
44
+ scores.append(float(conf))
45
+ if not boxes_xywh:
46
+ return []
47
+
48
+ keep = cv2.dnn.NMSBoxes(boxes_xywh, scores, CONF_THRESH, NMS_THRESH)
49
+
50
+ panels = []
51
+ for i in np.array(keep).flatten():
52
+ x, y, w, h = boxes_xywh[i]
53
+ # boxes are in the 640x640 resized pixel space, so dividing by
54
+ # IMG_SIZE gives page-relative (0..1) coordinates directly.
55
+ panels.append({"x": x / IMG_SIZE, "y": y / IMG_SIZE,
56
+ "w": w / IMG_SIZE, "h": h / IMG_SIZE})
57
+ return panels
58
+
59
+
60
+ def _positive_class_probs(outputs: list) -> np.ndarray:
61
+ """skl2onnx classifiers output [labels, probabilities]. `probabilities`
62
+ is either a plain (N, 2) array, or — if ZipMap wasn't disabled at
63
+ export time — a list of {0: p0, 1: p1} dicts."""
64
+ probs = outputs[1]
65
+ if isinstance(probs, list):
66
+ return np.array([p[1] for p in probs], dtype=np.float64)
67
+ return np.asarray(probs)[:, 1]
68
+
69
+
70
+ def order_panels(panels: list[dict], session: ort.InferenceSession) -> list[int]:
71
+ """Return panel indices (into `panels`) in predicted reading order."""
72
+ n = len(panels)
73
+ if n <= 1:
74
+ return list(range(n))
75
+
76
+ for p in panels:
77
+ p["cx"] = p["x"] + p["w"] / 2
78
+ p["cy"] = p["y"] + p["h"] / 2
79
+ p["x2"] = p["x"] + p["w"]
80
+ p["y2"] = p["y"] + p["h"]
81
+
82
+ med_h = float(np.median([p["h"] for p in panels]))
83
+ n_norm = n / 20.0
84
+
85
+ def pair_features(a: dict, b: dict) -> list[float]:
86
+ """Same 14 features the model was trained on — order matters."""
87
+ dx, dy = b["cx"] - a["cx"], b["cy"] - a["cy"]
88
+
89
+ shorter_h = min(a["h"], b["h"])
90
+ v_ovl = max(0.0, min(a["y2"], b["y2"]) - max(a["y"], b["y"]))
91
+ v_ovl = v_ovl / shorter_h if shorter_h > 0 else 0.0
92
+
93
+ shorter_w = min(a["w"], b["w"])
94
+ h_ovl = max(0.0, min(a["x2"], b["x2"]) - max(a["x"], b["x"]))
95
+ h_ovl = h_ovl / shorter_w if shorter_w > 0 else 0.0
96
+
97
+ h_ratio = a["h"] / b["h"] if b["h"] > 0 else 1.0
98
+ w_ratio = a["w"] / b["w"] if b["w"] > 0 else 1.0
99
+ a_left, b_left = float(a["cx"] < 0.5), float(b["cx"] < 0.5)
100
+ a_top, b_top = float(a["cy"] < 0.5), float(b["cy"] < 0.5)
101
+ a_tall = float(a["h"] > med_h * 1.4)
102
+ b_tall = float(b["h"] > med_h * 1.4)
103
+ same_row_right = float(v_ovl >= 0.3 and dx > 0)
104
+
105
+ return [dx, dy, v_ovl, h_ovl, h_ratio, w_ratio,
106
+ a_left, b_left, a_top, b_top, a_tall, b_tall,
107
+ n_norm, same_row_right]
108
+
109
+ input_name = session.get_inputs()[0].name
110
+ scores = np.zeros(n)
111
+ for i in range(n):
112
+ batch = np.array(
113
+ [pair_features(panels[i], panels[j]) for j in range(n) if j != i],
114
+ dtype=np.float32,
115
+ )
116
+ outputs = session.run(None, {input_name: batch})
117
+ probs = _positive_class_probs(outputs) # P(panel i before panel j)
118
+ scores[i] = probs.sum()
119
+
120
+ return list(np.argsort(-scores)) # highest "beats" score read first
121
+
122
+
123
+ def main(image_path: str) -> None:
124
+ det_session = ort.InferenceSession(DETECTOR_PATH)
125
+ order_session = ort.InferenceSession(ORDER_PATH)
126
+
127
+ image = cv2.imread(image_path)
128
+ if image is None:
129
+ raise SystemExit(f"Could not read image: {image_path}")
130
+
131
+ panels = detect_panels(image, det_session)
132
+ print(f"Detected {len(panels)} panels")
133
+
134
+ order = order_panels(panels, order_session)
135
+ print("Reading order:")
136
+ for rank, idx in enumerate(order):
137
+ p = panels[idx]
138
+ print(f" {rank + 1}. panel {idx} "
139
+ f"x={p['x']:.3f} y={p['y']:.3f} w={p['w']:.3f} h={p['h']:.3f}")
140
+
141
+
142
+ if __name__ == "__main__":
143
+ if len(sys.argv) != 2:
144
+ raise SystemExit(f"Usage: python {sys.argv[0]} <page_image.jpg>")
145
+ main(sys.argv[1])