pycut-image-splitter 1.0.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,189 @@
1
+ Dual-licensed under either of:
2
+
3
+ - Apache License, Version 2.0 (see below or http://www.apache.org/licenses/LICENSE-2.0)
4
+ - MIT License (see below or http://opensource.org/licenses/MIT)
5
+
6
+ at your option.
7
+
8
+ ================================================================================
9
+ APACHE LICENSE, VERSION 2.0
10
+ ================================================================================
11
+
12
+ Apache License
13
+ Version 2.0, January 2004
14
+ http://www.apache.org/licenses/
15
+
16
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
17
+
18
+ 1. Definitions.
19
+
20
+ "License" shall mean the terms and conditions for use, reproduction,
21
+ and distribution as defined by Sections 1 through 9 of this document.
22
+
23
+ "Licensor" shall mean the copyright owner or entity authorized by
24
+ the copyright owner that is granting the License.
25
+
26
+ "Legal Entity" shall mean the union of the acting entity and all
27
+ other entities that control, are controlled by, or are under common
28
+ control with that entity. For the purposes of this definition,
29
+ "control" means (i) the power, direct or indirect, to cause the
30
+ direction or management of such entity, whether by contract or
31
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
32
+ outstanding shares, or (iii) beneficial ownership of such entity.
33
+
34
+ "You" (or "Your") shall mean an individual or Legal Entity
35
+ exercising permissions granted by this License.
36
+
37
+ "Source" form shall mean the preferred form for making modifications,
38
+ including but not limited to software source code, documentation
39
+ source, and configuration files.
40
+
41
+ "Object" form shall mean any form resulting from mechanical
42
+ transformation or translation of a Source form, including but
43
+ not limited to compiled object code, generated documentation,
44
+ and conversions to other media types.
45
+
46
+ "Work" shall mean the work of authorship, whether in Source or
47
+ Object form, made available under the License, as indicated by a
48
+ copyright notice that is included in or attached to the work
49
+ (an example is provided in the Appendix below).
50
+
51
+ "Derivative Works" shall mean any work, whether in Source or Object
52
+ form, that is based on (or derived from) the Work and for which the
53
+ editorial revisions, annotations, elaborations, or other modifications
54
+ represent, as a whole, an original work of authorship. For the purposes
55
+ of this License, Derivative Works shall not include works that remain
56
+ separable from, or merely link (or bind by name) to the interfaces of,
57
+ the Work and Derivative Works thereof.
58
+
59
+ "Contribution" shall mean any work of authorship, including
60
+ the original version of the Work and any modifications or additions
61
+ to that Work or Derivative Works thereof, that is intentionally
62
+ submitted to Licensor for inclusion in the Work by the copyright owner
63
+ or by an individual or Legal Entity authorized to submit on behalf of
64
+ the copyright owner. For the purposes of this definition, "submitted"
65
+ means any form of electronic, verbal, or written communication sent
66
+ to the Licensor or its representatives, including but not limited to
67
+ communication on electronic mailing lists, source code control systems,
68
+ and issue tracking systems that are managed by, or on behalf of, the
69
+ Licensor for the purpose of discussing and improving the Work, but
70
+ excluding communication that is conspicuously marked or otherwise
71
+ designated in writing by the copyright owner as "Not a Contribution."
72
+
73
+ "Contributor" shall mean Licensor and any individual or Legal Entity
74
+ on behalf of whom a Contribution has been received by Licensor and
75
+ subsequently incorporated within the Work.
76
+
77
+ 2. Grant of Copyright License. Subject to the terms and conditions of
78
+ this License, each Contributor hereby grants to You a perpetual,
79
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
80
+ copyright license to reproduce, prepare Derivative Works of,
81
+ publicly display, publicly perform, sublicense, and distribute the
82
+ Work and such Derivative Works in Source or Object form.
83
+
84
+ 3. Grant of Patent License. Subject to the terms and conditions of
85
+ this License, each Contributor hereby grants to You a perpetual,
86
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
87
+ (except as stated in this section) patent license to make, have made,
88
+ use, offer to sell, sell, import, and otherwise transfer the Work,
89
+ where such license applies only to those patent claims licensable
90
+ by such Contributor that are necessarily infringed by their
91
+ Contribution(s) alone or by combination of their Contribution(s)
92
+ with the Work to which such Contribution(s) was submitted. If You
93
+ institute patent litigation against any entity (including a
94
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
95
+ or a Contribution incorporated within the Work constitutes direct
96
+ or contributory patent infringement, then any patent licenses granted
97
+ to You under this License for that Work shall terminate as of the
98
+ date such litigation is filed.
99
+
100
+ 4. Redistribution. You may reproduce and distribute copies of the
101
+ Work or Derivative Works thereof in any medium, with or without
102
+ modifications, and in Source or Object form, provided that You
103
+ meet the following conditions:
104
+
105
+ (a) You must give any other recipients of the Work or
106
+ Derivative Works a copy of this License; and
107
+
108
+ (b) You must cause any modified files to carry prominent notices
109
+ stating that You changed the files; and
110
+
111
+ (c) You must retain, in the Source form of any Derivative Works
112
+ that You distribute, all copyright, patent, and trademark
113
+ notices from the Source form of the Work, excluding those
114
+ notices that do not pertain to any part of the Derivative
115
+ Works; and
116
+
117
+ (d) If the Work includes a "NOTICE" text file as part of its
118
+ distribution, then any Derivative Works that You distribute must
119
+ include a readable copy of the NOTICE file within such file,
120
+ except those notices that do not pertain to any part of the
121
+ Derivative Works.
122
+
123
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
124
+ any Contribution intentionally submitted for inclusion in the Work
125
+ by You to the Licensor shall be under the terms and conditions of
126
+ this License, without any additional terms or conditions.
127
+ Notwithstanding the above, nothing herein shall supersede or modify
128
+ the terms of any separate license agreement you may have executed
129
+ with Licensor regarding such Contributions.
130
+
131
+ 6. Trademarks. This License does not grant permission to use the terms
132
+ "SliceCraft", "Smart Image Splitter", or any other trade names,
133
+ trademarks, service marks, or product names of the Licensor, except
134
+ as required for reasonable and customary use in describing the origin
135
+ of the Work and reproducing the content of the NOTICE file.
136
+
137
+ 7. Disclaimer of Warranty. Unless required by applicable law or
138
+ agreed to in writing, Licensor provides the Work (and each
139
+ Contributor provides its Contributions) on an "AS IS" BASIS,
140
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
141
+ implied, including, without limitation, any warranties or conditions
142
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
143
+ PARTICULAR PURPOSE. You are solely responsible for determining the
144
+ appropriateness of using or redistributing the Work and assume any
145
+ risks associated with Your exercise of permissions under this License.
146
+
147
+ 8. Limitation of Liability. In no event and under no legal theory,
148
+ whether in tort (including negligence), contract, or otherwise,
149
+ unless required by applicable law (such as deliberate misconduct
150
+ or gross negligence) or agreed to in writing, shall any Contributor be
151
+ liable to You for damages, including any direct, indirect, special,
152
+ incidental, or consequential damages of any character arising as a
153
+ result of this License or out of the use or inability to use the
154
+ Work (including but not limited to damages for loss of goodwill,
155
+ work stoppage, computer failure or malfunction, or any and all
156
+ other commercial damages or losses), even if such Contributor
157
+ has been advised of the possibility of such damages.
158
+
159
+ 9. Accepting Warranty or Additional Liability. While redistributing
160
+ the Work or Derivative Works thereof, You may choose to offer,
161
+ and charge a fee for, acceptance of support, warranty, indemnity,
162
+ or other liability obligations and/or rights consistent with this
163
+ License. However, in accepting such obligations, You may act only
164
+ on Your own behalf and on Your sole responsibility, not on behalf
165
+ of any other Contributor.
166
+
167
+ ================================================================================
168
+ MIT LICENSE
169
+ ================================================================================
170
+
171
+ Copyright (c) 2026 0passion0 and PyCut Image Splitter Contributors
172
+
173
+ Permission is hereby granted, free of charge, to any person obtaining a copy
174
+ of this software and associated documentation files (the "Software"), to deal
175
+ in the Software without restriction, including without limitation the rights
176
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
177
+ copies of the Software, and to permit persons to whom the Software is
178
+ furnished to do so, subject to the following conditions:
179
+
180
+ The above copyright notice and this permission notice shall be included in all
181
+ copies or substantial portions of the Software.
182
+
183
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
184
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
185
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
186
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
187
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
188
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
189
+ SOFTWARE.
@@ -0,0 +1,13 @@
1
+ include LICENSE
2
+ include README.md
3
+ include pyproject.toml
4
+ include MANIFEST.in
5
+ recursive-include python_engine/pycut_splitter *.py
6
+
7
+ prune src
8
+ prune public
9
+ prune node_modules
10
+ prune .pytest_cache
11
+ prune python_engine/.pytest_cache
12
+ prune python_engine/tests
13
+ global-exclude __pycache__ *.py[cod]
@@ -0,0 +1,222 @@
1
+ Metadata-Version: 2.4
2
+ Name: pycut-image-splitter
3
+ Version: 1.0.0
4
+ Summary: Memory-safe, ultra-fast pure Python + OpenCV + vectorized NumPy image layout parser and batch slicer.
5
+ Author: 0passion0, PyCut Contributors
6
+ License-Expression: Apache-2.0 OR MIT
7
+ Project-URL: Homepage, https://github.com/0passion0/pycut_splitter
8
+ Project-URL: Repository, https://github.com/0passion0/pycut_splitter
9
+ Project-URL: Issues, https://github.com/0passion0/pycut_splitter/issues
10
+ Keywords: image-splitting,computer-vision,opencv,numpy,xy-cut,layout-analysis
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Topic :: Multimedia :: Graphics
17
+ Classifier: Topic :: Scientific/Engineering :: Image Processing
18
+ Requires-Python: >=3.12
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: numpy>=2.0
22
+ Requires-Dist: opencv-python-headless>=4.10
23
+ Requires-Dist: pillow>=10.0
24
+ Provides-Extra: dev
25
+ Requires-Dist: pytest>=8.0; extra == "dev"
26
+ Requires-Dist: build>=1.2; extra == "dev"
27
+ Requires-Dist: twine>=5.0; extra == "dev"
28
+ Dynamic: license-file
29
+
30
+ # PyCut 智能切图引擎(`pycut-image-splitter`)
31
+
32
+ **简体中文** | [English](./README.en.md)
33
+
34
+ [![PyPI](https://img.shields.io/pypi/v/pycut-image-splitter?color=blue&label=PyPI)](https://pypi.org/project/pycut-image-splitter/)
35
+ [![Python](https://img.shields.io/pypi/pyversions/pycut-image-splitter)](https://pypi.org/project/pycut-image-splitter/)
36
+ [![CI](https://github.com/0passion0/pycut_splitter/actions/workflows/ci.yml/badge.svg)](https://github.com/0passion0/pycut_splitter/actions/workflows/ci.yml)
37
+ [![License](https://img.shields.io/badge/license-Apache--2.0%20OR%20MIT-green.svg)](./LICENSE)
38
+
39
+ 基于 **Python 3.12 + OpenCV SIMD + NumPy 向量化加速** 构建的高性能、严格内存安全复合图像版面解析与批量裁切引擎。通过**分条(Strip-Chunked)投影计算**与**零拷贝 ROI 切片**,在 4K / 8K 超大图场景下保持极低延迟与极低瞬态内存占用。
40
+
41
+ ---
42
+
43
+ ## 目录
44
+
45
+ 1. [核心能力与内存优化亮点](#1-核心能力与内存优化亮点)
46
+ 2. [处理管线与工作模式](#2-处理管线与工作模式)
47
+ 3. [快速安装(PyPI / GitHub / 本地源码)](#3-快速安装pypi--github--本地源码)
48
+ 4. [Python API 与 CLI 用法](#4-python-api-与-cli-用法)
49
+ 5. [核心参数速查表](#5-核心参数速查表)
50
+ 6. [运行测试与 PyCut Studio 工作台](#6-运行测试与-pycut-studio-工作台)
51
+ 7. [仓库目录结构](#7-仓库目录结构)
52
+ 8. [开源协议](#8-开源协议)
53
+
54
+ ---
55
+
56
+ ## 1. 核心能力与内存优化亮点
57
+
58
+ - **全向量化 OpenCV + NumPy 内核**:核心投影、边缘能量计算与形态学提取完全基于 OpenCV C++ 底层算子(`cv2.absdiff`、`cv2.addWeighted`、`cv2.dilate`、`cv2.connectedComponentsWithStats`)与 NumPy `uint8` / `uint16` 运算,零 Python 像素循环。
59
+ - **分条(Strip-Chunked)低内存架构**:按 `1024` 行分块扫描图像背景差值与边界梯度能量,及时释放临时切片缓冲,避免创建全图 `float32` / `int16` 副本;在 **8K(7680×4320,94.92 MB 原图)** 压测下峰值瞬态缓冲仅约 **21 MB(22.1%)**。
60
+ - **方向步进 + 1px 细线接缝能量检测**:结合 `C^2.4` 非线性覆盖率抑制与切向平滑度过滤,避免图表、文字段落与表格内部出现误切。
61
+ - **谷底折叠与递归 XY-Cut BSP**:自动识别背景留白沟槽(Gutter)并折叠中点,配合 **±12px 兄弟网格线传播**,稳健应对未对齐网格、非对称 Bento 拼图以及浅白细线分隔。
62
+ - **±8px 阶跃吸附与边缘去污染(`bleed_trim`)**:对分割边界进行局部能量极大值吸附,并向内剥离抗锯齿残影与 `1px` 灰边。
63
+ - **零拷贝 ROI 裁切与多线程并发编码**:基于 NumPy 切片视图截取子图,通过 `ThreadPoolExecutor` 释放 GIL 并发执行 `cv2.imencode`(支持 `PNG` / `JPG` / `WebP` 及 Alpha 透明通道保留),并内置 `pad` / `resize` / `crop` 统一输出尺寸。
64
+ - **严格内存安全护栏(`memory_safe.py`)**:内建解压缩炸弹像素上限保护(默认 `256 MP`)、数组维度与 `dtype` 校验、边界坐标安全钳位(`clamp_box`)以及只读零拷贝 ROI 校验。
65
+
66
+ ---
67
+
68
+ ## 2. 处理管线与工作模式
69
+
70
+ ```text
71
+ 输入图像 (NumPy ndarray / 磁盘文件)
72
+ │
73
+ ▼ [memory_safe.py: 256MP 解压防爆拦截 & 维度/dtype 校验]
74
+ [1. 分条 SIMD 投影与背景估计] 1024 行分块扫描 · 阶跃梯度 + 1px 细线脉冲
75
+ │
76
+ ├─ mode = "auto" ──► 基于前景连通域分布自动决策 xycut 或 contour
77
+ ├─ mode = "xycut" ──► 谷底折叠 + 递归 XY-Cut BSP + ±12px 兄弟网格传播 + ±8px 边缘吸附
78
+ ├─ mode = "contour" ──► 可分离降采样 + 自适应闭运算 (contour_gap_px) + 1:1 边缘收紧
79
+ └─ mode = "grid" ──► 整数均分 + gutter_px 间距扣除
80
+ │
81
+ ▼ [可选统一长宽: uniform_size / target_size (pad | resize | crop)]
82
+ [2. ThreadPoolExecutor 并发编码] 零拷贝 ROI 切片 + 释放 GIL 并发写盘或内存 bytes
83
+ ```
84
+
85
+ | 模式 (`mode`) | 适用场景 | 核心实现 |
86
+ | :--- | :--- | :--- |
87
+ | `auto`(默认) | 通用混排图、幻灯片拼图、散落元素图 | 根据前景连通域宽高比与空间重叠度自动决策 `xycut` 或 `contour` |
88
+ | `xycut` | 3×3 幻灯片、Bento 布局、带细线/留白的多栏拼贴 | 向量化行列接缝能量投影 + 谷底折叠 + 递归 BSP + 兄弟传播 + 边缘修剪 |
89
+ | `contour` | 散落图标、不规则排版卡片、透明背景素材 | 可分离降采样 + 自适应形态学闭运算(`contour_gap_px`)+ 1:1 紧致边界收紧 |
90
+ | `grid` | 规整宫格切图(支持自定义行列与间距) | 基于整数均分与 `gutter_px` 内缩的高速网格切分 |
91
+
92
+ ---
93
+
94
+ ## 3. 快速安装(PyPI / GitHub / 本地源码)
95
+
96
+ ### 环境要求
97
+
98
+ - **Python `>= 3.12`**(推荐 Python `3.12` / `3.13`)
99
+ - 核心依赖:`numpy >= 2.0`、`opencv-python-headless >= 4.10`、`pillow >= 10.0`
100
+
101
+ ```bash
102
+ # 方式 1:直接从 PyPI 安装(推荐)
103
+ pip install pycut-image-splitter
104
+
105
+ # 方式 2:从 GitHub 直接安装
106
+ pip install git+https://github.com/0passion0/pycut_splitter.git
107
+
108
+ # 方式 3:本地开发可编辑安装
109
+ pip install -e ".[dev]"
110
+ ```
111
+
112
+ ---
113
+
114
+ ## 4. Python API 与 CLI 用法
115
+
116
+ ### Python API 示例
117
+
118
+ ```python
119
+ import numpy as np
120
+ from PIL import Image
121
+ from pycut_splitter import SmartSplitter
122
+
123
+ # 1. 初始化切分器
124
+ splitter = SmartSplitter(
125
+ mode="auto", # "auto" | "xycut" | "contour" | "grid"
126
+ sensitivity=0.65, # 分割灵敏度 (0.1 ~ 1.0)
127
+ min_region_ratio=0.08, # 最小有效区域占比
128
+ bleed_trim=2, # 边缘去污染像素数
129
+ contour_gap_px=8, # 轮廓模式形态学闭合间隙
130
+ uniform_size=False, # 是否统一输出尺寸
131
+ uniform_mode="pad", # "pad" | "resize" | "crop"
132
+ )
133
+
134
+ # 2. 直接切分文件并保存为 PNG / JPG / WebP
135
+ result, saved_paths = splitter.split_file(
136
+ "public/examples/sample_slides.png",
137
+ "./output_slices",
138
+ fmt="png",
139
+ )
140
+ print(
141
+ f"模式: {result.detected_mode}, 后端: {result.backend}, "
142
+ f"切片数: {len(result.boxes)}, 耗时: {result.elapsed_ms:.1f}ms"
143
+ )
144
+
145
+ # 3. 或者在内存中处理 NumPy RGB/RGBA 数组(零磁盘落地)
146
+ img = np.asarray(Image.open("public/examples/sample_slides.png").convert("RGB"))
147
+ res, bytes_list = splitter.split_to_bytes(img, fmt="webp")
148
+ ```
149
+
150
+ ### 命令行工具(CLI)
151
+
152
+ ```bash
153
+ pycut-split public/examples/sample_slides.png -o ./slices --mode auto --format png
154
+ ```
155
+
156
+ ---
157
+
158
+ ## 5. 核心参数速查表
159
+
160
+ | 参数 | 默认值 | 说明 |
161
+ |---|---|---|
162
+ | `mode` | `"auto"` | 布局检测模式:`"auto"` / `"xycut"` / `"contour"` / `"grid"` |
163
+ | `sensitivity` | `0.65` | 边缘与前景灵敏度(`0.1..=1.0`) |
164
+ | `min_region_ratio` | `0.08` | 子图边长占短边最小比例(`0.03..=0.35`) |
165
+ | `bleed_trim` | `2` | 内接缝抗锯齿去杂边像素数(px) |
166
+ | `contour_gap_px` | `8` | 轮廓模式形态学闭运算弥合半径(px) |
167
+ | `uniform_size` | `False` | 是否统一所有切片输出宽高 |
168
+ | `target_size` | `None` | 显式指定统一尺寸 `(width, height)` |
169
+ | `uniform_mode` | `"pad"` | 统一尺寸对齐方式:`"pad"` / `"resize"` / `"crop"` |
170
+ | `max_pixels` | `268_435_456` | 防解压炸弹最大像素限制(`256 MP`) |
171
+ | `ml_segmenter` | `None` | 可选机器学习检测回调(返回 `(x, y, w, h)` 列表) |
172
+
173
+ ---
174
+
175
+ ## 6. 运行测试与 PyCut Studio 工作台
176
+
177
+ 本项目同时内置基于 **Express + Python 3.12 持久化 IPC Worker + React** 的 **PyCut Studio** 交互式工作台,可实时调节参数、检查像素边缘并运行 1080p–8K 实时基准压测。
178
+
179
+ ```bash
180
+ # 运行 Python 单元测试与 4K 内存安全压测(10 项测试)
181
+ pytest -v python_engine/tests/test_pycut.py
182
+
183
+ # 构建 wheel 与 sdist 并检查分发规范
184
+ python -m build --outdir dist
185
+ twine check dist/*
186
+
187
+ # 启动 PyCut Studio 全栈工作台(默认监听 3000 端口)
188
+ npm run dev
189
+ ```
190
+
191
+ ---
192
+
193
+ ## 7. 仓库目录结构
194
+
195
+ ```text
196
+ .
197
+ ├── LICENSE # Apache-2.0 OR MIT 双重开源协议
198
+ ├── MANIFEST.in # PyPI 源码分发清单(排除前端/Node 非核心资源)
199
+ ├── pyproject.toml # 根目录 PyPI 打包构建配置(pycut-image-splitter)
200
+ ├── README.md # 默认中文使用说明
201
+ ├── README.en.md # 英文说明文档
202
+ ├── .github/workflows/
203
+ │ ├── ci.yml # Python 3.12/3.13 Pytest + 打包校验 CI
204
+ │ └── release-pypi.yml # GitHub Release 与 PyPI 自动发布流
205
+ ├── python_engine/
206
+ │ ├── pyproject.toml # 子目录兼容安装配置
207
+ │ ├── pycut_splitter/ # 核心 Python 3.12 + OpenCV/NumPy 引擎
208
+ │ │ ├── algorithms.py # SIMD 投影、XY-Cut BSP、Contour 与并发裁切
209
+ │ │ ├── memory_safe.py # 解压缩炸弹防护、坐标钳位与零拷贝 ROI 校验
210
+ │ │ ├── engine.py # SmartSplitter / SplitBox / SplitResult 主类
211
+ │ │ ├── worker.py # 供 Node.js 后端调用的持久化 JSON-line IPC 进程
212
+ │ │ └── cli.py # 命令行批量切图入口
213
+ │ └── tests/test_pycut.py # pytest 完整算法与内存安全测试集
214
+ ├── server.ts # Express 后端与 Python 3.12 Worker 进程池
215
+ └── src/ # React + Tailwind CSS 中文可视化工作台
216
+ ```
217
+
218
+ ---
219
+
220
+ ## 8. 开源协议
221
+
222
+ 本项目采用 **[Apache-2.0 OR MIT](LICENSE)** 双重协议开源。
@@ -0,0 +1,193 @@
1
+ # PyCut 智能切图引擎(`pycut-image-splitter`)
2
+
3
+ **简体中文** | [English](./README.en.md)
4
+
5
+ [![PyPI](https://img.shields.io/pypi/v/pycut-image-splitter?color=blue&label=PyPI)](https://pypi.org/project/pycut-image-splitter/)
6
+ [![Python](https://img.shields.io/pypi/pyversions/pycut-image-splitter)](https://pypi.org/project/pycut-image-splitter/)
7
+ [![CI](https://github.com/0passion0/pycut_splitter/actions/workflows/ci.yml/badge.svg)](https://github.com/0passion0/pycut_splitter/actions/workflows/ci.yml)
8
+ [![License](https://img.shields.io/badge/license-Apache--2.0%20OR%20MIT-green.svg)](./LICENSE)
9
+
10
+ 基于 **Python 3.12 + OpenCV SIMD + NumPy 向量化加速** 构建的高性能、严格内存安全复合图像版面解析与批量裁切引擎。通过**分条(Strip-Chunked)投影计算**与**零拷贝 ROI 切片**,在 4K / 8K 超大图场景下保持极低延迟与极低瞬态内存占用。
11
+
12
+ ---
13
+
14
+ ## 目录
15
+
16
+ 1. [核心能力与内存优化亮点](#1-核心能力与内存优化亮点)
17
+ 2. [处理管线与工作模式](#2-处理管线与工作模式)
18
+ 3. [快速安装(PyPI / GitHub / 本地源码)](#3-快速安装pypi--github--本地源码)
19
+ 4. [Python API 与 CLI 用法](#4-python-api-与-cli-用法)
20
+ 5. [核心参数速查表](#5-核心参数速查表)
21
+ 6. [运行测试与 PyCut Studio 工作台](#6-运行测试与-pycut-studio-工作台)
22
+ 7. [仓库目录结构](#7-仓库目录结构)
23
+ 8. [开源协议](#8-开源协议)
24
+
25
+ ---
26
+
27
+ ## 1. 核心能力与内存优化亮点
28
+
29
+ - **全向量化 OpenCV + NumPy 内核**:核心投影、边缘能量计算与形态学提取完全基于 OpenCV C++ 底层算子(`cv2.absdiff`、`cv2.addWeighted`、`cv2.dilate`、`cv2.connectedComponentsWithStats`)与 NumPy `uint8` / `uint16` 运算,零 Python 像素循环。
30
+ - **分条(Strip-Chunked)低内存架构**:按 `1024` 行分块扫描图像背景差值与边界梯度能量,及时释放临时切片缓冲,避免创建全图 `float32` / `int16` 副本;在 **8K(7680×4320,94.92 MB 原图)** 压测下峰值瞬态缓冲仅约 **21 MB(22.1%)**。
31
+ - **方向步进 + 1px 细线接缝能量检测**:结合 `C^2.4` 非线性覆盖率抑制与切向平滑度过滤,避免图表、文字段落与表格内部出现误切。
32
+ - **谷底折叠与递归 XY-Cut BSP**:自动识别背景留白沟槽(Gutter)并折叠中点,配合 **±12px 兄弟网格线传播**,稳健应对未对齐网格、非对称 Bento 拼图以及浅白细线分隔。
33
+ - **±8px 阶跃吸附与边缘去污染(`bleed_trim`)**:对分割边界进行局部能量极大值吸附,并向内剥离抗锯齿残影与 `1px` 灰边。
34
+ - **零拷贝 ROI 裁切与多线程并发编码**:基于 NumPy 切片视图截取子图,通过 `ThreadPoolExecutor` 释放 GIL 并发执行 `cv2.imencode`(支持 `PNG` / `JPG` / `WebP` 及 Alpha 透明通道保留),并内置 `pad` / `resize` / `crop` 统一输出尺寸。
35
+ - **严格内存安全护栏(`memory_safe.py`)**:内建解压缩炸弹像素上限保护(默认 `256 MP`)、数组维度与 `dtype` 校验、边界坐标安全钳位(`clamp_box`)以及只读零拷贝 ROI 校验。
36
+
37
+ ---
38
+
39
+ ## 2. 处理管线与工作模式
40
+
41
+ ```text
42
+ 输入图像 (NumPy ndarray / 磁盘文件)
43
+ │
44
+ ▼ [memory_safe.py: 256MP 解压防爆拦截 & 维度/dtype 校验]
45
+ [1. 分条 SIMD 投影与背景估计] 1024 行分块扫描 · 阶跃梯度 + 1px 细线脉冲
46
+ │
47
+ ├─ mode = "auto" ──► 基于前景连通域分布自动决策 xycut 或 contour
48
+ ├─ mode = "xycut" ──► 谷底折叠 + 递归 XY-Cut BSP + ±12px 兄弟网格传播 + ±8px 边缘吸附
49
+ ├─ mode = "contour" ──► 可分离降采样 + 自适应闭运算 (contour_gap_px) + 1:1 边缘收紧
50
+ └─ mode = "grid" ──► 整数均分 + gutter_px 间距扣除
51
+ │
52
+ ▼ [可选统一长宽: uniform_size / target_size (pad | resize | crop)]
53
+ [2. ThreadPoolExecutor 并发编码] 零拷贝 ROI 切片 + 释放 GIL 并发写盘或内存 bytes
54
+ ```
55
+
56
+ | 模式 (`mode`) | 适用场景 | 核心实现 |
57
+ | :--- | :--- | :--- |
58
+ | `auto`(默认) | 通用混排图、幻灯片拼图、散落元素图 | 根据前景连通域宽高比与空间重叠度自动决策 `xycut` 或 `contour` |
59
+ | `xycut` | 3×3 幻灯片、Bento 布局、带细线/留白的多栏拼贴 | 向量化行列接缝能量投影 + 谷底折叠 + 递归 BSP + 兄弟传播 + 边缘修剪 |
60
+ | `contour` | 散落图标、不规则排版卡片、透明背景素材 | 可分离降采样 + 自适应形态学闭运算(`contour_gap_px`)+ 1:1 紧致边界收紧 |
61
+ | `grid` | 规整宫格切图(支持自定义行列与间距) | 基于整数均分与 `gutter_px` 内缩的高速网格切分 |
62
+
63
+ ---
64
+
65
+ ## 3. 快速安装(PyPI / GitHub / 本地源码)
66
+
67
+ ### 环境要求
68
+
69
+ - **Python `>= 3.12`**(推荐 Python `3.12` / `3.13`)
70
+ - 核心依赖:`numpy >= 2.0`、`opencv-python-headless >= 4.10`、`pillow >= 10.0`
71
+
72
+ ```bash
73
+ # 方式 1:直接从 PyPI 安装(推荐)
74
+ pip install pycut-image-splitter
75
+
76
+ # 方式 2:从 GitHub 直接安装
77
+ pip install git+https://github.com/0passion0/pycut_splitter.git
78
+
79
+ # 方式 3:本地开发可编辑安装
80
+ pip install -e ".[dev]"
81
+ ```
82
+
83
+ ---
84
+
85
+ ## 4. Python API 与 CLI 用法
86
+
87
+ ### Python API 示例
88
+
89
+ ```python
90
+ import numpy as np
91
+ from PIL import Image
92
+ from pycut_splitter import SmartSplitter
93
+
94
+ # 1. 初始化切分器
95
+ splitter = SmartSplitter(
96
+ mode="auto", # "auto" | "xycut" | "contour" | "grid"
97
+ sensitivity=0.65, # 分割灵敏度 (0.1 ~ 1.0)
98
+ min_region_ratio=0.08, # 最小有效区域占比
99
+ bleed_trim=2, # 边缘去污染像素数
100
+ contour_gap_px=8, # 轮廓模式形态学闭合间隙
101
+ uniform_size=False, # 是否统一输出尺寸
102
+ uniform_mode="pad", # "pad" | "resize" | "crop"
103
+ )
104
+
105
+ # 2. 直接切分文件并保存为 PNG / JPG / WebP
106
+ result, saved_paths = splitter.split_file(
107
+ "public/examples/sample_slides.png",
108
+ "./output_slices",
109
+ fmt="png",
110
+ )
111
+ print(
112
+ f"模式: {result.detected_mode}, 后端: {result.backend}, "
113
+ f"切片数: {len(result.boxes)}, 耗时: {result.elapsed_ms:.1f}ms"
114
+ )
115
+
116
+ # 3. 或者在内存中处理 NumPy RGB/RGBA 数组(零磁盘落地)
117
+ img = np.asarray(Image.open("public/examples/sample_slides.png").convert("RGB"))
118
+ res, bytes_list = splitter.split_to_bytes(img, fmt="webp")
119
+ ```
120
+
121
+ ### 命令行工具(CLI)
122
+
123
+ ```bash
124
+ pycut-split public/examples/sample_slides.png -o ./slices --mode auto --format png
125
+ ```
126
+
127
+ ---
128
+
129
+ ## 5. 核心参数速查表
130
+
131
+ | 参数 | 默认值 | 说明 |
132
+ |---|---|---|
133
+ | `mode` | `"auto"` | 布局检测模式:`"auto"` / `"xycut"` / `"contour"` / `"grid"` |
134
+ | `sensitivity` | `0.65` | 边缘与前景灵敏度(`0.1..=1.0`) |
135
+ | `min_region_ratio` | `0.08` | 子图边长占短边最小比例(`0.03..=0.35`) |
136
+ | `bleed_trim` | `2` | 内接缝抗锯齿去杂边像素数(px) |
137
+ | `contour_gap_px` | `8` | 轮廓模式形态学闭运算弥合半径(px) |
138
+ | `uniform_size` | `False` | 是否统一所有切片输出宽高 |
139
+ | `target_size` | `None` | 显式指定统一尺寸 `(width, height)` |
140
+ | `uniform_mode` | `"pad"` | 统一尺寸对齐方式:`"pad"` / `"resize"` / `"crop"` |
141
+ | `max_pixels` | `268_435_456` | 防解压炸弹最大像素限制(`256 MP`) |
142
+ | `ml_segmenter` | `None` | 可选机器学习检测回调(返回 `(x, y, w, h)` 列表) |
143
+
144
+ ---
145
+
146
+ ## 6. 运行测试与 PyCut Studio 工作台
147
+
148
+ 本项目同时内置基于 **Express + Python 3.12 持久化 IPC Worker + React** 的 **PyCut Studio** 交互式工作台,可实时调节参数、检查像素边缘并运行 1080p–8K 实时基准压测。
149
+
150
+ ```bash
151
+ # 运行 Python 单元测试与 4K 内存安全压测(10 项测试)
152
+ pytest -v python_engine/tests/test_pycut.py
153
+
154
+ # 构建 wheel 与 sdist 并检查分发规范
155
+ python -m build --outdir dist
156
+ twine check dist/*
157
+
158
+ # 启动 PyCut Studio 全栈工作台(默认监听 3000 端口)
159
+ npm run dev
160
+ ```
161
+
162
+ ---
163
+
164
+ ## 7. 仓库目录结构
165
+
166
+ ```text
167
+ .
168
+ ├── LICENSE # Apache-2.0 OR MIT 双重开源协议
169
+ ├── MANIFEST.in # PyPI 源码分发清单(排除前端/Node 非核心资源)
170
+ ├── pyproject.toml # 根目录 PyPI 打包构建配置(pycut-image-splitter)
171
+ ├── README.md # 默认中文使用说明
172
+ ├── README.en.md # 英文说明文档
173
+ ├── .github/workflows/
174
+ │ ├── ci.yml # Python 3.12/3.13 Pytest + 打包校验 CI
175
+ │ └── release-pypi.yml # GitHub Release 与 PyPI 自动发布流
176
+ ├── python_engine/
177
+ │ ├── pyproject.toml # 子目录兼容安装配置
178
+ │ ├── pycut_splitter/ # 核心 Python 3.12 + OpenCV/NumPy 引擎
179
+ │ │ ├── algorithms.py # SIMD 投影、XY-Cut BSP、Contour 与并发裁切
180
+ │ │ ├── memory_safe.py # 解压缩炸弹防护、坐标钳位与零拷贝 ROI 校验
181
+ │ │ ├── engine.py # SmartSplitter / SplitBox / SplitResult 主类
182
+ │ │ ├── worker.py # 供 Node.js 后端调用的持久化 JSON-line IPC 进程
183
+ │ │ └── cli.py # 命令行批量切图入口
184
+ │ └── tests/test_pycut.py # pytest 完整算法与内存安全测试集
185
+ ├── server.ts # Express 后端与 Python 3.12 Worker 进程池
186
+ └── src/ # React + Tailwind CSS 中文可视化工作台
187
+ ```
188
+
189
+ ---
190
+
191
+ ## 8. 开源协议
192
+
193
+ 本项目采用 **[Apache-2.0 OR MIT](LICENSE)** 双重协议开源。
@@ -0,0 +1,53 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "pycut-image-splitter"
7
+ version = "1.0.0"
8
+ description = "Memory-safe, ultra-fast pure Python + OpenCV + vectorized NumPy image layout parser and batch slicer."
9
+ readme = "README.md"
10
+ requires-python = ">=3.12"
11
+ license = "Apache-2.0 OR MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "0passion0" }, { name = "PyCut Contributors" }]
14
+ keywords = [
15
+ "image-splitting",
16
+ "computer-vision",
17
+ "opencv",
18
+ "numpy",
19
+ "xy-cut",
20
+ "layout-analysis",
21
+ ]
22
+ classifiers = [
23
+ "Development Status :: 5 - Production/Stable",
24
+ "Intended Audience :: Developers",
25
+ "Programming Language :: Python :: 3",
26
+ "Programming Language :: Python :: 3.12",
27
+ "Programming Language :: Python :: 3.13",
28
+ "Topic :: Multimedia :: Graphics",
29
+ "Topic :: Scientific/Engineering :: Image Processing",
30
+ ]
31
+ dependencies = [
32
+ "numpy>=2.0",
33
+ "opencv-python-headless>=4.10",
34
+ "pillow>=10.0",
35
+ ]
36
+
37
+ [project.urls]
38
+ Homepage = "https://github.com/0passion0/pycut_splitter"
39
+ Repository = "https://github.com/0passion0/pycut_splitter"
40
+ Issues = "https://github.com/0passion0/pycut_splitter/issues"
41
+
42
+ [project.optional-dependencies]
43
+ dev = ["pytest>=8.0", "build>=1.2", "twine>=5.0"]
44
+
45
+ [project.scripts]
46
+ pycut-split = "pycut_splitter.cli:main"
47
+
48
+ [tool.setuptools]
49
+ include-package-data = true
50
+
51
+ [tool.setuptools.packages.find]
52
+ where = ["python_engine"]
53
+ include = ["pycut_splitter*"]