smart-image-splitter 0.2.0__tar.gz

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.
@@ -0,0 +1,22 @@
1
+ [package]
2
+ name = "smart-image-splitter"
3
+ version = "0.2.0"
4
+ edition = "2021"
5
+ description = "High-performance Rust core (PyO3 + Rayon + image) for multi-strategy image splitting and seam bleed removal"
6
+ license = "Apache-2.0"
7
+
8
+ [lib]
9
+ name = "_core"
10
+ path = "src/lib.rs"
11
+ crate-type = ["cdylib"]
12
+
13
+ [dependencies]
14
+ pyo3 = { version = "0.22", features = ["extension-module"] }
15
+ numpy = "0.22"
16
+ rayon = "1.10"
17
+ image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp"] }
18
+
19
+ [profile.release]
20
+ opt-level = 3
21
+ lto = "thin"
22
+ codegen-units = 1
@@ -0,0 +1,151 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, whether in
49
+ Source or Object form, that is intentionally submitted to Licensor
50
+ for inclusion in the Work by the copyright owner or by an individual
51
+ or Legal Entity authorized to submit on behalf of the copyright owner.
52
+ For the purposes of this definition, "Contribution" means any form of
53
+ electronic, verbal, or written communication sent to the Licensor
54
+ or its representatives, including but not limited to communication on
55
+ electronic mailing lists, source code control systems, and issue
56
+ tracking systems that are managed by, or on behalf of, the Licensor for
57
+ the purpose of discussing and improving the Work, but excluding
58
+ communication that is conspicuously marked or otherwise designated in
59
+ writing by the copyright owner as "Not a Contribution."
60
+
61
+ "Contributor" shall mean Licensor and any individual or Legal Entity
62
+ on behalf of whom a Contribution has been received by Licensor and
63
+ subsequently incorporated into the Work.
64
+
65
+ 2. Grant of Copyright License. Subject to the terms and conditions of
66
+ this License, each Contributor hereby grants to You a perpetual,
67
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
68
+ copyright license to reproduce, prepare Derivative Works of,
69
+ publicly display, publicly perform, sublicense, and distribute the
70
+ Work and such Derivative Works in Source or Object form.
71
+
72
+ 3. Grant of Patent License. Subject to the terms and conditions of
73
+ this License, each Contributor hereby grants to You a perpetual,
74
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
75
+ (except as stated in this section) patent license to make, have made,
76
+ use, offer to sell, sell, import, and otherwise transfer the Work,
77
+ where such license applies only to those patent claims licensable
78
+ by such Contributor that are necessarily infringed by their
79
+ Contribution(s) alone or by combination of their Contribution(s)
80
+ with the Work to which such Contribution(s) was submitted. If You
81
+ institute patent litigation against any entity (including a
82
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
83
+ or a Contribution incorporated within the Work constitutes direct
84
+ or indirect patent infringement, then any patent licenses granted
85
+ to You under this License for that Work shall terminate as of the
86
+ date such litigation is filed.
87
+
88
+ 4. Redistribution. You may reproduce and distribute copies of the
89
+ Work or Derivative Works thereof in any medium, with or without
90
+ modifications, and in Source or Object form, provided that You
91
+ meet the following conditions:
92
+
93
+ (a) You must give any other recipients of the Work or
94
+ Derivative Works a copy of this License; and
95
+
96
+ (b) You must cause any modified files to retain prominent notices
97
+ stating that You modified the files; and
98
+
99
+ (c) You must retain, in the Source form of any Derivative Works
100
+ that You distribute, all copyright, patent, and trademark
101
+ notices from the Source form of the Work, excluding those
102
+ notices that do not pertain to any part of the Derivative
103
+ Works; and
104
+
105
+ (d) If the Work includes a "NOTICE" file as part of its
106
+ distribution, then any Derivative Works that You distribute must
107
+ include a copy of the NOTICE file in such distribution.
108
+
109
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
110
+ any Contribution intentionally submitted for inclusion in the Work
111
+ by You shall be under the terms and conditions of this License,
112
+ without any additional terms or conditions. Notwithstanding the above,
113
+ nothing herein shall supersede or modify the terms of any separate
114
+ license agreement you may have executed with Licensor regarding
115
+ such Contributions.
116
+
117
+ 6. Trademarks. This License does not grant permission to use the terms
118
+ "SliceCraft", "Smart Image Splitter", or any other trade names,
119
+ trademarks, service marks, or product names of the Licensor, except
120
+ as required for reasonable and customary use in describing the origin
121
+ of the Work and reproducing the content of the NOTICE file.
122
+
123
+ 7. Disclaimer of Warranty. Unless required by applicable law or
124
+ agreed to in writing, Licensor provides the Work (and each
125
+ Contributor provides its Contributions) on an "AS IS" BASIS,
126
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
127
+ implied, including, without limitation, any warranties or conditions
128
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
129
+ PARTICULAR PURPOSE. You are solely responsible for determining the
130
+ appropriateness of using or redistributing the Work and assume any
131
+ risks associated with Your use of this License.
132
+
133
+ 8. Limitation of Liability. In no event and under no legal theory,
134
+ whether in tort (including negligence), contract, or otherwise,
135
+ unless required by applicable law (such as deliberate gross
136
+ negligence) or agreed to in writing, shall any Contributor be
137
+ liable to You for damages, including any direct, indirect, special,
138
+ incidental, or consequential damages of any character arising as a
139
+ result of this License or out of the use or inability to use the
140
+ Work (including but not limited to damages for loss of goodwill,
141
+ work stoppage, computer failure or malfunction, or any and all
142
+ other commercial damages or losses), even if such Contributor
143
+ has been advised of the possibility of such damages.
144
+
145
+ 9. Accepting Warranty or Additional Liability. While redistributing
146
+ the Work or Derivative Works thereof, You may choose to offer,
147
+ and charge a fee for, acceptance of support, warranty, indemnity,
148
+ or other liability obligations and/or rights consistent with this
149
+ License. However, in accepting such obligations, You may act only
150
+ on Your own behalf and on Your sole responsibility, not on behalf
151
+ of any other Contributor.
@@ -0,0 +1,9 @@
1
+ include Cargo.toml
2
+ include LICENSE
3
+ include README.md
4
+ include README.zh-CN.md
5
+ include pyproject.toml
6
+ include setup.py
7
+ recursive-include src *.rs
8
+ recursive-include python *.py
9
+ recursive-include tests *.py
@@ -0,0 +1,232 @@
1
+ Metadata-Version: 2.4
2
+ Name: smart-image-splitter
3
+ Version: 0.2.0
4
+ Summary: High-performance hybrid Rust (PyO3 + Rayon) and OpenCV image splitter with XY-Cut BSP, gutter collapsing, bleed decontamination, and contour extraction.
5
+ Author: SliceCraft Contributors
6
+ License: Apache-2.0
7
+ Keywords: image-splitting,computer-vision,rust,pyo3,opencv,xy-cut
8
+ Requires-Python: >=3.9
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: numpy>=1.24
12
+ Requires-Dist: opencv-python-headless>=4.8
13
+ Requires-Dist: pillow>=10.0
14
+ Provides-Extra: ml
15
+ Requires-Dist: onnxruntime>=1.18; extra == "ml"
16
+ Requires-Dist: torch>=2.2; extra == "ml"
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest>=8.0; extra == "dev"
19
+ Requires-Dist: maturin>=1.7; extra == "dev"
20
+ Dynamic: license-file
21
+
22
+ # smart-image-splitter · High-Precision Rust + Python Image Splitter
23
+
24
+ **English** | [简体中文](./README.zh-CN.md)
25
+
26
+ **smart-image-splitter** is a high-performance, pixel-accurate composite image segmentation Python package powered by a **native Rust (`PyO3` + `Rayon`) core** and a **full-parity vectorized OpenCV / NumPy fallback engine**.
27
+
28
+ It is engineered for real-world composite images where naive `W / N × H / M` grid slicing fails—including **slide sheets with misaligned seams**, **asymmetric Bento layouts**, **white-guttered collages**, **scattered objects on solid/transparent backgrounds**, and **overlapping photo grids (via optional ML segmentation hooks)**.
29
+
30
+ ---
31
+
32
+ ## Table of Contents
33
+ 1. [Why Naive Grid Slicing Fails](#1-why-naive-grid-slicing-fails)
34
+ 2. [Algorithm Theory & Mathematical Formulation](#2-algorithm-theory--mathematical-formulation)
35
+ - [2.1 Directional Step + 1px Hairline Energy Profiling](#21-directional-step--1px-hairline-energy-profiling)
36
+ - [2.2 Non-Linear Coverage Weighting & Tangential Smoothness Penalty](#22-non-linear-coverage-weighting--tangential-smoothness-penalty)
37
+ - [2.3 Gutter Valley Detection & Contiguous Run Collapsing](#23-gutter-valley-detection--contiguous-run-collapsing)
38
+ - [2.4 Recursive Hierarchical XY-Cut BSP & Sibling Grid-Line Propagation](#24-recursive-hierarchical-xy-cut-bsp--sibling-grid-line-propagation)
39
+ - [2.5 Per-Cell Discontinuity Snap & Bleed Decontamination](#25-per-cell-discontinuity-snap--bleed-decontamination)
40
+ - [2.6 Separable O(N) DSU Contour Segmentation & 1:1 Tight Edge Refinement](#26-separable-on-dsu-contour-segmentation--11-tight-edge-refinement)
41
+ 3. [Engineering Practice & Extreme Performance Optimization](#3-engineering-practice--extreme-performance-optimization)
42
+ 4. [Quick Start (`pip install` Directly from GitHub)](#4-quick-start-pip-install-directly-from-github)
43
+ 5. [Repository Structure](#5-repository-structure)
44
+
45
+ ---
46
+
47
+ ## 1. Why Naive Grid Slicing Fails
48
+
49
+ Consider the included `2848 × 1600` 3×3 presentation slide sheet (`examples/sample_slides.png`):
50
+ - A uniform 3×3 mathematical grid slices at `x = 949, 1898` and `y = 533, 1066`.
51
+ - In reality, the true panel boundaries sit at:
52
+ - Horizontal seams: `y = 531`, `y = 1043..1047`
53
+ - Left column seam: `x = 945..946` (with a `1px` gray divider `(213, 214, 217)` at `x = 946`)
54
+ - Right column seam: **`x = 1824`** in Rows 0–1, shifting **12px left to `x = 1812`** in Row 2!
55
+ - Naive uniform slicing produces up to **86 pixels of cross-panel bleed** and splits slide content down the middle.
56
+ - Worse yet, adjacent white-background slides (e.g., Row 1 Col 0 vs. Row 2 Col 0) are separated only by a faint `1px` shadow hairline—invisible to naive thresholding, yet crisp when modeled with a combined **step + impulse gradient** and **sibling grid-line propagation**.
57
+
58
+ ---
59
+
60
+ ## 2. Algorithm Theory & Mathematical Formulation
61
+
62
+ ### 2.1 Directional Step + 1px Hairline Energy Profiling
63
+
64
+ For any candidate axis position $p$ (e.g., row $y$ with orthogonal samples $x \in [x_0, x_1)$), a true seam exhibits either:
65
+ 1. **A color step transition** across two neighboring regions, or
66
+ 2. **A `1px` hairline divider / drop shadow** where pixel $I(p)$ deviates sharply from both neighbors $I(p-1)$ and $I(p+1)$ (even when both panels share the exact same white background!).
67
+
68
+ We compute two $L_1$ color-space responses at each sample point $u$:
69
+
70
+ $$E_{\text{step}}(p, u) = \|I(p, u) - I(p+1, u)\|_1$$
71
+
72
+ $$E_{\text{line}}(p, u) = \frac{1}{2} \|2I(p, u) - I(p-1, u) - I(p+1, u)\|_1$$
73
+
74
+ Total local edge energy at $(p, u)$ is:
75
+
76
+ $$E(p, u) = E_{\text{step}}(p, u) + E_{\text{line}}(p, u)$$
77
+
78
+ Why this matters in practice:
79
+ - If Slide A (navy) meets Slide B (white), $E_{\text{step}}$ fires strongly ($\approx 600$).
80
+ - If Slide A (white) meets Slide B (white) across a `1px` light-gray shadow line $\Delta = 15$ per channel, $E_{\text{step}} \approx 45$ and $E_{\text{line}} \approx 45$, reinforcing each other while suppressing uniform interior noise.
81
+
82
+ ### 2.2 Non-Linear Coverage Weighting & Tangential Smoothness Penalty
83
+
84
+ Text, charts, and tables inside a panel also create strong local gradients—**how do we avoid cutting through a chart title or table header?**
85
+
86
+ 1. **$\pm 2\text{px}$ Neighborhood Coverage $C(p)$**:
87
+ Real layout seams are rarely strictly horizontal to `0px` under JPEG/anti-aliasing compression; they may wobble by $\pm 1\text{–}2\text{px}$. A sample $u$ is marked active if any row/column within $[p-2, p+2]$ satisfies $E(r, u) > 16$:
88
+ $$C(p) = \frac{1}{N} \sum_{u=1}^{N} \mathbb{I}\!\left[\max_{r \in [p-2, p+2]} E(r, u) > 16\right]$$
89
+ Text lines rarely span $> 70\%$ of the full panel width, whereas true panel boundaries have $C(p) \in [0.85, 1.00]$. Applying the non-linear power $C(p)^{2.4}$ strongly attenuates partial interior lines (e.g., $0.4^{2.4} = 0.11$ vs. $0.95^{2.4} = 0.88$).
90
+
91
+ 2. **Tangential Smoothness Penalty $S_{\text{tan}}(p)$**:
92
+ Along a true divider or clean slide edge, pixel luminance varies smoothly in the tangential direction $u$:
93
+ $$S_{\text{tan}}(p) = \frac{1}{N-1} \sum_{u=2}^{N} \left| L(p, u) - L(p, u-1) \right|, \quad L = R + G + B$$
94
+ Taking the minimum smoothness across $[p-1, p, p+1]$ ensures a sharp edge right next to a clean background isn't penalized by texture on the opposite side.
95
+
96
+ 3. **Combined Seam Score**:
97
+ $$\text{Score}_{\text{seam}}(p) = \frac{\left(\bar{E}_{\text{step}}(p) + 0.7\,\bar{E}_{\text{line}}(p)\right) \cdot C(p)^{2.4}}{1 + 0.12 \cdot S_{\min}(p)}$$
98
+ Candidate peaks are selected via **1D Non-Maximum Suppression (NMS)** with minimum spacing $d_{\min} = \max(24, \text{minRegionRatio} \cdot \min(W, H))$ and coverage gate $C(p) \ge 0.72$.
99
+
100
+ ### 2.3 Gutter Valley Detection & Contiguous Run Collapsing
101
+
102
+ When panels are separated by **wide solid or transparent gutters** (e.g., a `40px` white margin between cards), edge gradients fire only on the gutter walls, not inside the empty gap.
103
+ 1. Border background color $\mathbf{b}$ and border uniformity $U_{\text{border}}$ are estimated via $8\times 8\times 8$-quantized histogram binning over 4 image perimeters (with alpha transparency check $\alpha < 32$).
104
+ 2. When $U_{\text{border}} > 0.72$, any interior strip with $> 95\%$ background match, low tangential variance ($S_{\text{tan}} < 2.5$), and foreground content present on **both sides** receives a high gutter score:
105
+ $$\text{Score}_{\text{gutter}}(p) = \frac{110}{1 + S_{\text{tan}}(p)}$$
106
+ 3. **Contiguous Run Collapsing**: A `40px` wide gutter generates 40 adjacent high-scoring rows/columns. Collapsing each contiguous gutter run $[i, j]$ to its single midpoint $\lfloor (i + j)/2 \rfloor$ guarantees cutting right down the center of the gutter rather than fracturing wide gutters into empty slivers. Empty background-only leaf regions ($< 3\%$ foreground density) are discarded automatically.
107
+
108
+ ### 2.4 Recursive Hierarchical XY-Cut BSP & Sibling Grid-Line Propagation
109
+
110
+ Rather than slicing globally along X and Y simultaneously:
111
+ 1. At each region $[x_0, y_0, x_1, y_1]$, profile both H and V seam scores.
112
+ 2. Select the dominant split axis (choosing H if $\max \text{Score}_H \ge 0.72 \cdot \max \text{Score}_V$, matching natural row-first slide flow).
113
+ 3. Partition into horizontal/vertical bands and **recursively profile each sub-band independently**.
114
+ - *Result*: Row 0–1 naturally finds `x = 1824` while Row 2 independently finds `x = 1812`—zero global misalignment!
115
+ 4. **Sibling Grid-Line Propagation**:
116
+ Suppose Column 1|2 has a faint white-on-white boundary below threshold $T$ on one sub-band while sibling columns above/below split cleanly around `y_cut`. For every internal boundary line $p_{\text{cut}}$ produced by siblings, any adjacent leaf spanning $p_{\text{cut}}$ searches a narrow $\pm 12\text{px}$ window under relaxed thresholds ($\text{cov} \ge 0.78$, $\bar{E}_{\text{raw}} \ge 10$, $S_{\text{tan}} < 2.2$). This recovers low-contrast white-on-white seams with zero false positives.
117
+
118
+ ### 2.5 Per-Cell Discontinuity Snap & Bleed Decontamination
119
+
120
+ After BSP leaves are finalized, each cell undergoes two refinement stages:
121
+ 1. **Local $\pm 8\text{px}$ Edge Snap**: Each interior edge snaps independently within $\pm 8\text{px}$ to the exact pixel transition of *that specific cell* (correcting minor diagonal tilt or row-by-row drift).
122
+ 2. **Outer Margin & Anti-Aliased Bleed Decontamination (`bleed_trim`)**:
123
+ - First strips any remaining uniform canvas background rows/columns (`> 94%` background match).
124
+ - Then inspects up to `bleed_trim` (default `2px`) outer pixel rows/columns along internal cut edges against an interior reference line `ref = edge ± (bleed_trim + 2)`. Whenever the average $L_1$ difference exceeds `20`, the outer `1px` transition/divider pixel (e.g., `1px` gray border or JPEG chroma ringing) is peeled off—guaranteeing **zero white halo on dark slides and zero dark edge bleed on light slides**.
125
+
126
+ ### 2.6 Separable $O(N)$ DSU Contour Segmentation & 1:1 Tight Edge Refinement
127
+
128
+ When an image consists of scattered objects, UI stickers, or transparent RGBA sprites ($U_{\text{border}} > 0.72$ and contour coverage $< 65\%$ of total area with $\ge 2$ components, or explicit `contour` mode):
129
+ 1. Downsample onto a canonical $\le 720\text{px}$ grid (`scale = ceil(max(W, H) / 720)`) and threshold foreground against $\mathbf{b}$ (or $\alpha > 24$).
130
+ 2. Apply **separable 1D forward/backward sweep morphological closing/dilation** in $O(s_w \cdot s_h)$ time (independent of `contour_gap_px`, avoiding $O(N \cdot r^2)$ nested loops).
131
+ 3. Extract 8-connected components using two-pass **Disjoint-Set Union (DSU) with path halving** in Rust (`src/lib.rs`) or `cv2.connectedComponentsWithStats` in OpenCV (`python/smart_splitter/engine.py`).
132
+ 4. **1:1 Full-Resolution Edge Tightening**: Because downsampling introduces up to $\pm \text{scale}$ quantization error, every component bounding box is shrunk/expanded directly against 1:1 raw image pixels until all 4 borders sit on exact foreground boundaries (`0px` integer error).
133
+
134
+ ---
135
+
136
+ ## 3. Engineering Practice & Extreme Performance Optimization
137
+
138
+ | Optimization | Problem Solved | Concrete Implementation |
139
+ |---|---|---|
140
+ | **1. Row-Major Parallel Scanning (`Rayon`)** | Vertical column loops `for x { for y }` stride `W * C` bytes per pixel read, thrashing CPU L1/L2 caches | Inverted vertical profiling to row-major `ys.par_iter().fold().reduce()` in Rust so every CPU thread streams contiguous cache lines |
141
+ | **2. Single-Pass Active Tracking** | Allocating `O(span × 200)` 2D energy matrices per recursive band wasted memory bandwidth | Replaced 2D matrices with a monotonic 1D cursor tracker proving exact equivalence to $\max_{r \in [p-2,p+2]} E(r,u) > 16$ |
142
+ | **3. 200-Sample Orthogonal Stride** | Scanning all 2,848 pixels horizontally at every row is redundant; skipping primary-axis rows misses `1px` odd hairlines | Kept primary-axis step strictly **`1px`** while striding the orthogonal axis to $\approx 200$ samples |
143
+ | **4. Zero-Copy NumPy Borrow + GIL Release** | Copying multi-megapixel NumPy buffers across FFI and blocking Python threads | Borrows C-contiguous NumPy arrays zero-copy (`Cow<[u8]>`) and releases the GIL via `py.allow_threads(...)` during detection and encoding |
144
+ | **5. Parallel In-Memory Batch Cropping** | Disk I/O bottlenecks when serving slices via FastAPI or feeding PyTorch DataLoaders | `batch_crop_to_memory_rs` encodes all slices concurrently in RAM across Rayon worker threads without touching disk |
145
+
146
+ ---
147
+
148
+ ## 4. Quick Start (`pip install` Directly from GitHub)
149
+
150
+ ### Installation (Zero Extra Setup)
151
+
152
+ ```bash
153
+ # Option 1: Install directly via Git + pip (recommended)
154
+ pip install git+https://github.com/<owner>/<repo>.git
155
+
156
+ # Option 2: Install via GitHub source archive URL (works even without git CLI installed)
157
+ pip install https://github.com/<owner>/<repo>/archive/refs/heads/main.zip
158
+
159
+ # Option 3: Install a prebuilt binary wheel from GitHub Releases (precompiled Rust PyO3, no compiler needed)
160
+ pip install https://github.com/<owner>/<repo>/releases/latest/download/smart_image_splitter-0.2.0-cp311-cp311-manylinux_2_17_x86_64.whl
161
+ ```
162
+
163
+ > **Note on GitHub URLs & `pip`**: Standard `pip` cannot install a bare GitHub webpage URL (`pip install https://github.com/owner/repo`) because GitHub serves HTML there. Always use `git+https://github.com/owner/repo` or `/archive/refs/heads/main.zip` (or a Release `.whl`).
164
+ >
165
+ > **Automatic Rust / OpenCV Dual-Backend**:
166
+ > - If `cargo` (Rust toolchain) is installed on the target machine, `pip install` automatically compiles `smart_splitter._core` (`PyO3` + `Rayon`) in release mode.
167
+ > - If `cargo` is **not** installed, `setup.py` skips Rust compilation gracefully with **zero errors** and uses the full-parity vectorized OpenCV / NumPy backend.
168
+ > - Pushing a version tag (`git tag v0.2.0 && git push --tags`) triggers `.github/workflows/release-wheels.yml` (`PyO3/maturin-action`) to publish prebuilt native Rust wheels for Linux, macOS, and Windows.
169
+
170
+ ### CLI & Python API Usage
171
+
172
+ ```bash
173
+ # CLI batch splitting
174
+ smart-split examples/sample_slides.png -o ./output_slices --mode auto --bleed-trim 2 --format png
175
+ ```
176
+
177
+ ```python
178
+ import cv2
179
+ from smart_splitter import SmartSplitter
180
+
181
+ splitter = SmartSplitter(mode="auto", sensitivity=0.65, bleed_trim=2)
182
+
183
+ # 1. File-to-directory splitting
184
+ result, paths = splitter.split_file("examples/sample_slides.png", "output_slices/")
185
+ print(f"Split into {len(paths)} slices via {result.backend} in {result.elapsed_ms:.1f}ms")
186
+
187
+ # 2. Zero-disk in-memory splitting (FastAPI / PyTorch dataloaders)
188
+ img = cv2.imread("examples/sample_slides.png")
189
+ result, png_blobs = splitter.split_to_bytes(img, fmt="png")
190
+
191
+ # 3. Optional ML segmentation hook (SAM 2 / YOLO / ONNX) for overlapping natural photos
192
+ ml_splitter = SmartSplitter(ml_segmenter=my_sam2_box_predictor)
193
+ ```
194
+
195
+ ### Local Development & Testing
196
+
197
+ ```bash
198
+ pip install setuptools wheel setuptools-rust maturin pytest numpy opencv-python-headless pillow
199
+ maturin develop --release
200
+ pytest -v tests/
201
+ ```
202
+
203
+ ---
204
+
205
+ ## 5. Repository Structure
206
+
207
+ ```text
208
+ .
209
+ ├── Cargo.toml # Rust PyO3 + Rayon crate manifest
210
+ ├── pyproject.toml # PEP 517 + setuptools / maturin build configuration
211
+ ├── setup.py # Optional Rust extension builder with graceful fallback
212
+ ├── MANIFEST.in # Source distribution manifest (Python + Rust sources only)
213
+ ├── LICENSE / CONTRIBUTING.md
214
+ ├── README.md / README.zh-CN.md
215
+ ├── .github/
216
+ │ ├── workflows/
217
+ │ │ ├── ci.yml # Root pip install + Cargo + maturin + pytest CI
218
+ │ │ └── release-wheels.yml # Multi-OS prebuilt wheel publisher (Linux/macOS/Windows)
219
+ │ ├── ISSUE_TEMPLATE/bug_report.md
220
+ │ └── pull_request_template.md
221
+ ├── src/
222
+ │ └── lib.rs # Native Rust (PyO3 + Rayon) engine: XY-Cut, DSU Contour & Memory Crop
223
+ ├── python/
224
+ │ └── smart_splitter/
225
+ │ ├── __init__.py # Public exports (SmartSplitter, SplitBox, SplitResult)
226
+ │ ├── engine.py # Hybrid Rust / full-parity OpenCV engine & ML hook
227
+ │ └── cli.py # `smart-split` CLI entrypoint
228
+ ├── tests/
229
+ │ └── test_splitter.py # Pytest unit tests (XY-Cut, White Gutter, Bleed Trim, Contour)
230
+ └── examples/
231
+ └── sample_slides.png # Real-world 2848x1600 3x3 slide benchmark image
232
+ ```
@@ -0,0 +1,211 @@
1
+ # smart-image-splitter · High-Precision Rust + Python Image Splitter
2
+
3
+ **English** | [简体中文](./README.zh-CN.md)
4
+
5
+ **smart-image-splitter** is a high-performance, pixel-accurate composite image segmentation Python package powered by a **native Rust (`PyO3` + `Rayon`) core** and a **full-parity vectorized OpenCV / NumPy fallback engine**.
6
+
7
+ It is engineered for real-world composite images where naive `W / N × H / M` grid slicing fails—including **slide sheets with misaligned seams**, **asymmetric Bento layouts**, **white-guttered collages**, **scattered objects on solid/transparent backgrounds**, and **overlapping photo grids (via optional ML segmentation hooks)**.
8
+
9
+ ---
10
+
11
+ ## Table of Contents
12
+ 1. [Why Naive Grid Slicing Fails](#1-why-naive-grid-slicing-fails)
13
+ 2. [Algorithm Theory & Mathematical Formulation](#2-algorithm-theory--mathematical-formulation)
14
+ - [2.1 Directional Step + 1px Hairline Energy Profiling](#21-directional-step--1px-hairline-energy-profiling)
15
+ - [2.2 Non-Linear Coverage Weighting & Tangential Smoothness Penalty](#22-non-linear-coverage-weighting--tangential-smoothness-penalty)
16
+ - [2.3 Gutter Valley Detection & Contiguous Run Collapsing](#23-gutter-valley-detection--contiguous-run-collapsing)
17
+ - [2.4 Recursive Hierarchical XY-Cut BSP & Sibling Grid-Line Propagation](#24-recursive-hierarchical-xy-cut-bsp--sibling-grid-line-propagation)
18
+ - [2.5 Per-Cell Discontinuity Snap & Bleed Decontamination](#25-per-cell-discontinuity-snap--bleed-decontamination)
19
+ - [2.6 Separable O(N) DSU Contour Segmentation & 1:1 Tight Edge Refinement](#26-separable-on-dsu-contour-segmentation--11-tight-edge-refinement)
20
+ 3. [Engineering Practice & Extreme Performance Optimization](#3-engineering-practice--extreme-performance-optimization)
21
+ 4. [Quick Start (`pip install` Directly from GitHub)](#4-quick-start-pip-install-directly-from-github)
22
+ 5. [Repository Structure](#5-repository-structure)
23
+
24
+ ---
25
+
26
+ ## 1. Why Naive Grid Slicing Fails
27
+
28
+ Consider the included `2848 × 1600` 3×3 presentation slide sheet (`examples/sample_slides.png`):
29
+ - A uniform 3×3 mathematical grid slices at `x = 949, 1898` and `y = 533, 1066`.
30
+ - In reality, the true panel boundaries sit at:
31
+ - Horizontal seams: `y = 531`, `y = 1043..1047`
32
+ - Left column seam: `x = 945..946` (with a `1px` gray divider `(213, 214, 217)` at `x = 946`)
33
+ - Right column seam: **`x = 1824`** in Rows 0–1, shifting **12px left to `x = 1812`** in Row 2!
34
+ - Naive uniform slicing produces up to **86 pixels of cross-panel bleed** and splits slide content down the middle.
35
+ - Worse yet, adjacent white-background slides (e.g., Row 1 Col 0 vs. Row 2 Col 0) are separated only by a faint `1px` shadow hairline—invisible to naive thresholding, yet crisp when modeled with a combined **step + impulse gradient** and **sibling grid-line propagation**.
36
+
37
+ ---
38
+
39
+ ## 2. Algorithm Theory & Mathematical Formulation
40
+
41
+ ### 2.1 Directional Step + 1px Hairline Energy Profiling
42
+
43
+ For any candidate axis position $p$ (e.g., row $y$ with orthogonal samples $x \in [x_0, x_1)$), a true seam exhibits either:
44
+ 1. **A color step transition** across two neighboring regions, or
45
+ 2. **A `1px` hairline divider / drop shadow** where pixel $I(p)$ deviates sharply from both neighbors $I(p-1)$ and $I(p+1)$ (even when both panels share the exact same white background!).
46
+
47
+ We compute two $L_1$ color-space responses at each sample point $u$:
48
+
49
+ $$E_{\text{step}}(p, u) = \|I(p, u) - I(p+1, u)\|_1$$
50
+
51
+ $$E_{\text{line}}(p, u) = \frac{1}{2} \|2I(p, u) - I(p-1, u) - I(p+1, u)\|_1$$
52
+
53
+ Total local edge energy at $(p, u)$ is:
54
+
55
+ $$E(p, u) = E_{\text{step}}(p, u) + E_{\text{line}}(p, u)$$
56
+
57
+ Why this matters in practice:
58
+ - If Slide A (navy) meets Slide B (white), $E_{\text{step}}$ fires strongly ($\approx 600$).
59
+ - If Slide A (white) meets Slide B (white) across a `1px` light-gray shadow line $\Delta = 15$ per channel, $E_{\text{step}} \approx 45$ and $E_{\text{line}} \approx 45$, reinforcing each other while suppressing uniform interior noise.
60
+
61
+ ### 2.2 Non-Linear Coverage Weighting & Tangential Smoothness Penalty
62
+
63
+ Text, charts, and tables inside a panel also create strong local gradients—**how do we avoid cutting through a chart title or table header?**
64
+
65
+ 1. **$\pm 2\text{px}$ Neighborhood Coverage $C(p)$**:
66
+ Real layout seams are rarely strictly horizontal to `0px` under JPEG/anti-aliasing compression; they may wobble by $\pm 1\text{–}2\text{px}$. A sample $u$ is marked active if any row/column within $[p-2, p+2]$ satisfies $E(r, u) > 16$:
67
+ $$C(p) = \frac{1}{N} \sum_{u=1}^{N} \mathbb{I}\!\left[\max_{r \in [p-2, p+2]} E(r, u) > 16\right]$$
68
+ Text lines rarely span $> 70\%$ of the full panel width, whereas true panel boundaries have $C(p) \in [0.85, 1.00]$. Applying the non-linear power $C(p)^{2.4}$ strongly attenuates partial interior lines (e.g., $0.4^{2.4} = 0.11$ vs. $0.95^{2.4} = 0.88$).
69
+
70
+ 2. **Tangential Smoothness Penalty $S_{\text{tan}}(p)$**:
71
+ Along a true divider or clean slide edge, pixel luminance varies smoothly in the tangential direction $u$:
72
+ $$S_{\text{tan}}(p) = \frac{1}{N-1} \sum_{u=2}^{N} \left| L(p, u) - L(p, u-1) \right|, \quad L = R + G + B$$
73
+ Taking the minimum smoothness across $[p-1, p, p+1]$ ensures a sharp edge right next to a clean background isn't penalized by texture on the opposite side.
74
+
75
+ 3. **Combined Seam Score**:
76
+ $$\text{Score}_{\text{seam}}(p) = \frac{\left(\bar{E}_{\text{step}}(p) + 0.7\,\bar{E}_{\text{line}}(p)\right) \cdot C(p)^{2.4}}{1 + 0.12 \cdot S_{\min}(p)}$$
77
+ Candidate peaks are selected via **1D Non-Maximum Suppression (NMS)** with minimum spacing $d_{\min} = \max(24, \text{minRegionRatio} \cdot \min(W, H))$ and coverage gate $C(p) \ge 0.72$.
78
+
79
+ ### 2.3 Gutter Valley Detection & Contiguous Run Collapsing
80
+
81
+ When panels are separated by **wide solid or transparent gutters** (e.g., a `40px` white margin between cards), edge gradients fire only on the gutter walls, not inside the empty gap.
82
+ 1. Border background color $\mathbf{b}$ and border uniformity $U_{\text{border}}$ are estimated via $8\times 8\times 8$-quantized histogram binning over 4 image perimeters (with alpha transparency check $\alpha < 32$).
83
+ 2. When $U_{\text{border}} > 0.72$, any interior strip with $> 95\%$ background match, low tangential variance ($S_{\text{tan}} < 2.5$), and foreground content present on **both sides** receives a high gutter score:
84
+ $$\text{Score}_{\text{gutter}}(p) = \frac{110}{1 + S_{\text{tan}}(p)}$$
85
+ 3. **Contiguous Run Collapsing**: A `40px` wide gutter generates 40 adjacent high-scoring rows/columns. Collapsing each contiguous gutter run $[i, j]$ to its single midpoint $\lfloor (i + j)/2 \rfloor$ guarantees cutting right down the center of the gutter rather than fracturing wide gutters into empty slivers. Empty background-only leaf regions ($< 3\%$ foreground density) are discarded automatically.
86
+
87
+ ### 2.4 Recursive Hierarchical XY-Cut BSP & Sibling Grid-Line Propagation
88
+
89
+ Rather than slicing globally along X and Y simultaneously:
90
+ 1. At each region $[x_0, y_0, x_1, y_1]$, profile both H and V seam scores.
91
+ 2. Select the dominant split axis (choosing H if $\max \text{Score}_H \ge 0.72 \cdot \max \text{Score}_V$, matching natural row-first slide flow).
92
+ 3. Partition into horizontal/vertical bands and **recursively profile each sub-band independently**.
93
+ - *Result*: Row 0–1 naturally finds `x = 1824` while Row 2 independently finds `x = 1812`—zero global misalignment!
94
+ 4. **Sibling Grid-Line Propagation**:
95
+ Suppose Column 1|2 has a faint white-on-white boundary below threshold $T$ on one sub-band while sibling columns above/below split cleanly around `y_cut`. For every internal boundary line $p_{\text{cut}}$ produced by siblings, any adjacent leaf spanning $p_{\text{cut}}$ searches a narrow $\pm 12\text{px}$ window under relaxed thresholds ($\text{cov} \ge 0.78$, $\bar{E}_{\text{raw}} \ge 10$, $S_{\text{tan}} < 2.2$). This recovers low-contrast white-on-white seams with zero false positives.
96
+
97
+ ### 2.5 Per-Cell Discontinuity Snap & Bleed Decontamination
98
+
99
+ After BSP leaves are finalized, each cell undergoes two refinement stages:
100
+ 1. **Local $\pm 8\text{px}$ Edge Snap**: Each interior edge snaps independently within $\pm 8\text{px}$ to the exact pixel transition of *that specific cell* (correcting minor diagonal tilt or row-by-row drift).
101
+ 2. **Outer Margin & Anti-Aliased Bleed Decontamination (`bleed_trim`)**:
102
+ - First strips any remaining uniform canvas background rows/columns (`> 94%` background match).
103
+ - Then inspects up to `bleed_trim` (default `2px`) outer pixel rows/columns along internal cut edges against an interior reference line `ref = edge ± (bleed_trim + 2)`. Whenever the average $L_1$ difference exceeds `20`, the outer `1px` transition/divider pixel (e.g., `1px` gray border or JPEG chroma ringing) is peeled off—guaranteeing **zero white halo on dark slides and zero dark edge bleed on light slides**.
104
+
105
+ ### 2.6 Separable $O(N)$ DSU Contour Segmentation & 1:1 Tight Edge Refinement
106
+
107
+ When an image consists of scattered objects, UI stickers, or transparent RGBA sprites ($U_{\text{border}} > 0.72$ and contour coverage $< 65\%$ of total area with $\ge 2$ components, or explicit `contour` mode):
108
+ 1. Downsample onto a canonical $\le 720\text{px}$ grid (`scale = ceil(max(W, H) / 720)`) and threshold foreground against $\mathbf{b}$ (or $\alpha > 24$).
109
+ 2. Apply **separable 1D forward/backward sweep morphological closing/dilation** in $O(s_w \cdot s_h)$ time (independent of `contour_gap_px`, avoiding $O(N \cdot r^2)$ nested loops).
110
+ 3. Extract 8-connected components using two-pass **Disjoint-Set Union (DSU) with path halving** in Rust (`src/lib.rs`) or `cv2.connectedComponentsWithStats` in OpenCV (`python/smart_splitter/engine.py`).
111
+ 4. **1:1 Full-Resolution Edge Tightening**: Because downsampling introduces up to $\pm \text{scale}$ quantization error, every component bounding box is shrunk/expanded directly against 1:1 raw image pixels until all 4 borders sit on exact foreground boundaries (`0px` integer error).
112
+
113
+ ---
114
+
115
+ ## 3. Engineering Practice & Extreme Performance Optimization
116
+
117
+ | Optimization | Problem Solved | Concrete Implementation |
118
+ |---|---|---|
119
+ | **1. Row-Major Parallel Scanning (`Rayon`)** | Vertical column loops `for x { for y }` stride `W * C` bytes per pixel read, thrashing CPU L1/L2 caches | Inverted vertical profiling to row-major `ys.par_iter().fold().reduce()` in Rust so every CPU thread streams contiguous cache lines |
120
+ | **2. Single-Pass Active Tracking** | Allocating `O(span × 200)` 2D energy matrices per recursive band wasted memory bandwidth | Replaced 2D matrices with a monotonic 1D cursor tracker proving exact equivalence to $\max_{r \in [p-2,p+2]} E(r,u) > 16$ |
121
+ | **3. 200-Sample Orthogonal Stride** | Scanning all 2,848 pixels horizontally at every row is redundant; skipping primary-axis rows misses `1px` odd hairlines | Kept primary-axis step strictly **`1px`** while striding the orthogonal axis to $\approx 200$ samples |
122
+ | **4. Zero-Copy NumPy Borrow + GIL Release** | Copying multi-megapixel NumPy buffers across FFI and blocking Python threads | Borrows C-contiguous NumPy arrays zero-copy (`Cow<[u8]>`) and releases the GIL via `py.allow_threads(...)` during detection and encoding |
123
+ | **5. Parallel In-Memory Batch Cropping** | Disk I/O bottlenecks when serving slices via FastAPI or feeding PyTorch DataLoaders | `batch_crop_to_memory_rs` encodes all slices concurrently in RAM across Rayon worker threads without touching disk |
124
+
125
+ ---
126
+
127
+ ## 4. Quick Start (`pip install` Directly from GitHub)
128
+
129
+ ### Installation (Zero Extra Setup)
130
+
131
+ ```bash
132
+ # Option 1: Install directly via Git + pip (recommended)
133
+ pip install git+https://github.com/<owner>/<repo>.git
134
+
135
+ # Option 2: Install via GitHub source archive URL (works even without git CLI installed)
136
+ pip install https://github.com/<owner>/<repo>/archive/refs/heads/main.zip
137
+
138
+ # Option 3: Install a prebuilt binary wheel from GitHub Releases (precompiled Rust PyO3, no compiler needed)
139
+ pip install https://github.com/<owner>/<repo>/releases/latest/download/smart_image_splitter-0.2.0-cp311-cp311-manylinux_2_17_x86_64.whl
140
+ ```
141
+
142
+ > **Note on GitHub URLs & `pip`**: Standard `pip` cannot install a bare GitHub webpage URL (`pip install https://github.com/owner/repo`) because GitHub serves HTML there. Always use `git+https://github.com/owner/repo` or `/archive/refs/heads/main.zip` (or a Release `.whl`).
143
+ >
144
+ > **Automatic Rust / OpenCV Dual-Backend**:
145
+ > - If `cargo` (Rust toolchain) is installed on the target machine, `pip install` automatically compiles `smart_splitter._core` (`PyO3` + `Rayon`) in release mode.
146
+ > - If `cargo` is **not** installed, `setup.py` skips Rust compilation gracefully with **zero errors** and uses the full-parity vectorized OpenCV / NumPy backend.
147
+ > - Pushing a version tag (`git tag v0.2.0 && git push --tags`) triggers `.github/workflows/release-wheels.yml` (`PyO3/maturin-action`) to publish prebuilt native Rust wheels for Linux, macOS, and Windows.
148
+
149
+ ### CLI & Python API Usage
150
+
151
+ ```bash
152
+ # CLI batch splitting
153
+ smart-split examples/sample_slides.png -o ./output_slices --mode auto --bleed-trim 2 --format png
154
+ ```
155
+
156
+ ```python
157
+ import cv2
158
+ from smart_splitter import SmartSplitter
159
+
160
+ splitter = SmartSplitter(mode="auto", sensitivity=0.65, bleed_trim=2)
161
+
162
+ # 1. File-to-directory splitting
163
+ result, paths = splitter.split_file("examples/sample_slides.png", "output_slices/")
164
+ print(f"Split into {len(paths)} slices via {result.backend} in {result.elapsed_ms:.1f}ms")
165
+
166
+ # 2. Zero-disk in-memory splitting (FastAPI / PyTorch dataloaders)
167
+ img = cv2.imread("examples/sample_slides.png")
168
+ result, png_blobs = splitter.split_to_bytes(img, fmt="png")
169
+
170
+ # 3. Optional ML segmentation hook (SAM 2 / YOLO / ONNX) for overlapping natural photos
171
+ ml_splitter = SmartSplitter(ml_segmenter=my_sam2_box_predictor)
172
+ ```
173
+
174
+ ### Local Development & Testing
175
+
176
+ ```bash
177
+ pip install setuptools wheel setuptools-rust maturin pytest numpy opencv-python-headless pillow
178
+ maturin develop --release
179
+ pytest -v tests/
180
+ ```
181
+
182
+ ---
183
+
184
+ ## 5. Repository Structure
185
+
186
+ ```text
187
+ .
188
+ ├── Cargo.toml # Rust PyO3 + Rayon crate manifest
189
+ ├── pyproject.toml # PEP 517 + setuptools / maturin build configuration
190
+ ├── setup.py # Optional Rust extension builder with graceful fallback
191
+ ├── MANIFEST.in # Source distribution manifest (Python + Rust sources only)
192
+ ├── LICENSE / CONTRIBUTING.md
193
+ ├── README.md / README.zh-CN.md
194
+ ├── .github/
195
+ │ ├── workflows/
196
+ │ │ ├── ci.yml # Root pip install + Cargo + maturin + pytest CI
197
+ │ │ └── release-wheels.yml # Multi-OS prebuilt wheel publisher (Linux/macOS/Windows)
198
+ │ ├── ISSUE_TEMPLATE/bug_report.md
199
+ │ └── pull_request_template.md
200
+ ├── src/
201
+ │ └── lib.rs # Native Rust (PyO3 + Rayon) engine: XY-Cut, DSU Contour & Memory Crop
202
+ ├── python/
203
+ │ └── smart_splitter/
204
+ │ ├── __init__.py # Public exports (SmartSplitter, SplitBox, SplitResult)
205
+ │ ├── engine.py # Hybrid Rust / full-parity OpenCV engine & ML hook
206
+ │ └── cli.py # `smart-split` CLI entrypoint
207
+ ├── tests/
208
+ │ └── test_splitter.py # Pytest unit tests (XY-Cut, White Gutter, Bleed Trim, Contour)
209
+ └── examples/
210
+ └── sample_slides.png # Real-world 2848x1600 3x3 slide benchmark image
211
+ ```