fredcallagan commited on
Commit
39c8284
·
verified ·
1 Parent(s): a160f74

Upload folder using huggingface_hub

Browse files
Files changed (4) hide show
  1. LICENSE +190 -0
  2. README.md +151 -0
  3. config.json +33 -0
  4. example.py +235 -0
LICENSE ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2023 Floor Verhoeven, Tanguy Magne, Olga Sorkine-Hornung
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ library_name: onnx
4
+ pipeline_tag: image-to-image
5
+ tags:
6
+ - onnx
7
+ - document-processing
8
+ - document-unwarping
9
+ - image-processing
10
+ - ocr-preprocessing
11
+ - computer-vision
12
+ ---
13
+
14
+ # UVDoc Grid Output - Document Unwarping ONNX Model
15
+
16
+ This is an ONNX export of the [UVDoc](https://github.com/tanguymagne/UVDoc) document unwarping model,
17
+ modified to output a **coordinate grid** instead of an image. This enables high-resolution document
18
+ unwarping via `cv2.remap()`.
19
+
20
+ ## Model Description
21
+
22
+ UVDoc is a deep learning model for correcting perspective distortion and curvature in photographed
23
+ documents. Unlike the PaddlePaddle ONNX variant that outputs a fixed 288x288 image, this version
24
+ outputs a coordinate mapping grid that can be applied to images of any resolution.
25
+
26
+ ### Key Difference: Grid Output vs Image Output
27
+
28
+ | Approach | Output | Quality |
29
+ |----------|--------|---------|
30
+ | **Image-output models** | 288x288 RGB image | Poor (must upscale) |
31
+ | **This grid-output model** | 45x31 coordinate grid | Native resolution |
32
+
33
+ ## Model Details
34
+
35
+ - **Architecture:** UVDoc (ResNet-based encoder-decoder)
36
+ - **Input:** `(1, 3, 720, 496)` - RGB image, normalized [0, 1]
37
+ - **Output:** `(1, 2, 45, 31)` - Coordinate grid in [-1, 1] range
38
+ - **ONNX Opset:** 16
39
+ - **Size:** ~30 MB
40
+
41
+ ### Input Specifications
42
+
43
+ | Property | Value |
44
+ |----------|-------|
45
+ | Shape | `(batch, 3, 720, 496)` |
46
+ | Format | RGB (not BGR) |
47
+ | Range | `[0, 1]` (normalized) |
48
+ | Layout | NCHW (batch, channels, height, width) |
49
+
50
+ ### Output Specifications
51
+
52
+ | Property | Value |
53
+ |----------|-------|
54
+ | Shape | `(batch, 2, 45, 31)` |
55
+ | Channels | 2 (x, y coordinates) |
56
+ | Range | `[-1, 1]` (normalized coordinates) |
57
+ | Layout | NCHW (batch, channels, height, width) |
58
+
59
+ ## Usage
60
+
61
+ ### With ONNX Runtime (Python)
62
+
63
+ ```python
64
+ import cv2
65
+ import numpy as np
66
+ import onnxruntime as ort
67
+
68
+ # Load model
69
+ session = ort.InferenceSession("UVDoc_grid.onnx", providers=['CPUExecutionProvider'])
70
+
71
+ # Load and preprocess image
72
+ image = cv2.imread("warped_document.jpg")
73
+ h_orig, w_orig = image.shape[:2]
74
+
75
+ # Prepare model input (720x496 RGB normalized)
76
+ img_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
77
+ resized = cv2.resize(img_rgb, (496, 720)) # width, height
78
+ blob = resized.astype(np.float32) / 255.0
79
+ blob = np.transpose(blob, (2, 0, 1))[None] # (1, 3, 720, 496)
80
+
81
+ # Run inference
82
+ result = session.run(None, {'image': blob})[0] # (1, 2, 45, 31)
83
+
84
+ # Convert grid to remap coordinates
85
+ grid = np.transpose(result[0], (1, 2, 0)) # (45, 31, 2)
86
+ grid_up = cv2.resize(grid, (w_orig, h_orig), interpolation=cv2.INTER_LINEAR)
87
+
88
+ map_x = ((grid_up[..., 0] + 1) / 2) * (w_orig - 1)
89
+ map_y = ((grid_up[..., 1] + 1) / 2) * (h_orig - 1)
90
+
91
+ # Apply unwarping to original high-res image
92
+ unwarped = cv2.remap(
93
+ image,
94
+ map_x.astype(np.float32),
95
+ map_y.astype(np.float32),
96
+ interpolation=cv2.INTER_CUBIC,
97
+ borderMode=cv2.BORDER_REPLICATE
98
+ )
99
+
100
+ cv2.imwrite("unwarped_document.jpg", unwarped)
101
+ ```
102
+
103
+ ### With HuggingFace Hub
104
+
105
+ ```python
106
+ from huggingface_hub import hf_hub_download
107
+
108
+ model_path = hf_hub_download(
109
+ repo_id="YOUR_USERNAME/uvdoc-grid-onnx",
110
+ filename="UVDoc_grid.onnx"
111
+ )
112
+ ```
113
+
114
+ ## Training Details
115
+
116
+ This model was not retrained. It is a direct ONNX export of the original UVDoc weights from
117
+ [tanguymagne/UVDoc](https://github.com/tanguymagne/UVDoc), with a wrapper to output only the
118
+ 2D coordinate grid (discarding the 3D shape output).
119
+
120
+ ### Original Model
121
+
122
+ - **Paper:** [UVDoc: Neural Grid-based Document Unwarping](https://arxiv.org/abs/2302.02887)
123
+ - **Authors:** Floor Verhoeven, Tanguy Magne, Olga Sorkine-Hornung (ETH Zurich)
124
+ - **Published:** SIGGRAPH Asia 2023
125
+ - **Original Repository:** [tanguymagne/UVDoc](https://github.com/tanguymagne/UVDoc)
126
+
127
+ ## Limitations
128
+
129
+ - Input must be resized to 720x496 for inference (grid output is always 45x31)
130
+ - Works best on documents with visible text/content (needs features for grid estimation)
131
+ - May not handle extreme perspective distortions well
132
+ - CPU inference takes ~100-200ms per image
133
+
134
+ ## Citation
135
+
136
+ If you use this model, please cite the original UVDoc paper:
137
+
138
+ ```bibtex
139
+ @inproceedings{UVDoc,
140
+ title={{UVDoc}: Neural Grid-based Document Unwarping},
141
+ author={Floor Verhoeven and Tanguy Magne and Olga Sorkine-Hornung},
142
+ booktitle = {SIGGRAPH ASIA, Technical Papers},
143
+ year = {2023},
144
+ url={https://doi.org/10.1145/3610548.3618174}
145
+ }
146
+ ```
147
+
148
+ ## License
149
+
150
+ This ONNX export is provided under the Apache 2.0 license. The original UVDoc model is also
151
+ Apache 2.0 licensed. See the original repository for full license details.
config.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "uvdoc",
3
+ "architecture": "encoder-decoder",
4
+ "framework": "onnx",
5
+ "input": {
6
+ "name": "image",
7
+ "shape": [1, 3, 720, 496],
8
+ "format": "NCHW",
9
+ "dtype": "float32",
10
+ "color_space": "RGB",
11
+ "normalization": {
12
+ "range": [0, 1],
13
+ "method": "divide_by_255"
14
+ }
15
+ },
16
+ "output": {
17
+ "name": "grid_2d",
18
+ "shape": [1, 2, 45, 31],
19
+ "format": "NCHW",
20
+ "dtype": "float32",
21
+ "description": "2D coordinate grid for document unwarping",
22
+ "coordinate_range": [-1, 1]
23
+ },
24
+ "onnx_opset": 16,
25
+ "original_model": {
26
+ "name": "UVDoc",
27
+ "repository": "https://github.com/tanguymagne/UVDoc",
28
+ "paper": "https://arxiv.org/abs/2302.02887",
29
+ "authors": ["Floor Verhoeven", "Tanguy Magne", "Olga Sorkine-Hornung"],
30
+ "institution": "ETH Zurich",
31
+ "venue": "SIGGRAPH Asia 2023"
32
+ }
33
+ }
example.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ UVDoc Grid-Output Document Unwarping Example
4
+
5
+ This script demonstrates how to use the UVDoc ONNX model with grid output
6
+ for high-resolution document unwarping.
7
+
8
+ The key advantage of this grid-output model over image-output models is that
9
+ the coordinate grid can be upscaled to any resolution, preserving document
10
+ quality when applied via cv2.remap().
11
+
12
+ Usage:
13
+ python example.py input_image.jpg output_image.jpg
14
+ python example.py input_image.jpg output_image.jpg --model path/to/UVDoc_grid.onnx
15
+
16
+ Requirements:
17
+ pip install onnxruntime opencv-python numpy
18
+
19
+ Optional (for automatic model download):
20
+ pip install huggingface_hub
21
+ """
22
+
23
+ import argparse
24
+ import sys
25
+ from pathlib import Path
26
+
27
+ import cv2
28
+ import numpy as np
29
+
30
+ # Model input dimensions (fixed for UVDoc architecture)
31
+ MODEL_INPUT_HEIGHT = 720
32
+ MODEL_INPUT_WIDTH = 496
33
+
34
+
35
+ def load_model(model_path: str = None):
36
+ """
37
+ Load the ONNX model.
38
+
39
+ Args:
40
+ model_path: Path to the ONNX model file. If None, attempts to download
41
+ from HuggingFace Hub.
42
+
43
+ Returns:
44
+ ONNX Runtime InferenceSession
45
+ """
46
+ import onnxruntime as ort
47
+
48
+ if model_path is None:
49
+ try:
50
+ from huggingface_hub import hf_hub_download
51
+
52
+ print("Downloading model from HuggingFace Hub...")
53
+ model_path = hf_hub_download(
54
+ repo_id="YOUR_USERNAME/uvdoc-grid-onnx", # Update with actual repo
55
+ filename="UVDoc_grid.onnx"
56
+ )
57
+ print(f"Model downloaded to: {model_path}")
58
+ except ImportError:
59
+ print("Error: huggingface_hub not installed. Install it or provide --model path.")
60
+ print(" pip install huggingface_hub")
61
+ sys.exit(1)
62
+
63
+ print(f"Loading model from: {model_path}")
64
+ session = ort.InferenceSession(
65
+ model_path,
66
+ providers=['CPUExecutionProvider']
67
+ )
68
+
69
+ return session
70
+
71
+
72
+ def preprocess_image(image: np.ndarray) -> np.ndarray:
73
+ """
74
+ Preprocess image for UVDoc model input.
75
+
76
+ Args:
77
+ image: BGR image from cv2.imread()
78
+
79
+ Returns:
80
+ Preprocessed tensor of shape (1, 3, 720, 496)
81
+ """
82
+ # Convert BGR to RGB
83
+ img_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
84
+
85
+ # Resize to model input size
86
+ resized = cv2.resize(img_rgb, (MODEL_INPUT_WIDTH, MODEL_INPUT_HEIGHT))
87
+
88
+ # Normalize to [0, 1]
89
+ normalized = resized.astype(np.float32) / 255.0
90
+
91
+ # Convert HWC to CHW format
92
+ transposed = np.transpose(normalized, (2, 0, 1))
93
+
94
+ # Add batch dimension
95
+ batched = np.expand_dims(transposed, axis=0)
96
+
97
+ return batched
98
+
99
+
100
+ def apply_grid_unwarping(
101
+ image: np.ndarray,
102
+ grid: np.ndarray,
103
+ interpolation: int = cv2.INTER_CUBIC
104
+ ) -> np.ndarray:
105
+ """
106
+ Apply the coordinate grid to unwarp the image.
107
+
108
+ Args:
109
+ image: Original BGR image (any resolution)
110
+ grid: Model output grid of shape (1, 2, 45, 31)
111
+ interpolation: OpenCV interpolation method
112
+
113
+ Returns:
114
+ Unwarped image at original resolution
115
+ """
116
+ h_orig, w_orig = image.shape[:2]
117
+
118
+ # Remove batch dimension and transpose to (H, W, 2)
119
+ grid_2d = np.transpose(grid[0], (1, 2, 0)) # (45, 31, 2)
120
+
121
+ # Upscale grid to original image resolution
122
+ grid_upscaled = cv2.resize(
123
+ grid_2d,
124
+ (w_orig, h_orig),
125
+ interpolation=cv2.INTER_LINEAR
126
+ )
127
+
128
+ # Convert normalized coordinates [-1, 1] to pixel coordinates
129
+ # Grid channel 0 = x (width), channel 1 = y (height)
130
+ map_x = ((grid_upscaled[..., 0] + 1) / 2) * (w_orig - 1)
131
+ map_y = ((grid_upscaled[..., 1] + 1) / 2) * (h_orig - 1)
132
+
133
+ # Apply remapping
134
+ unwarped = cv2.remap(
135
+ image,
136
+ map_x.astype(np.float32),
137
+ map_y.astype(np.float32),
138
+ interpolation=interpolation,
139
+ borderMode=cv2.BORDER_REPLICATE
140
+ )
141
+
142
+ return unwarped
143
+
144
+
145
+ def unwarp_document(
146
+ image_path: str,
147
+ output_path: str,
148
+ model_path: str = None
149
+ ) -> None:
150
+ """
151
+ Main function to unwarp a document image.
152
+
153
+ Args:
154
+ image_path: Path to input warped document image
155
+ output_path: Path to save unwarped result
156
+ model_path: Optional path to ONNX model file
157
+ """
158
+ # Load image
159
+ print(f"Loading image: {image_path}")
160
+ image = cv2.imread(image_path)
161
+ if image is None:
162
+ print(f"Error: Could not load image from {image_path}")
163
+ sys.exit(1)
164
+
165
+ h, w = image.shape[:2]
166
+ print(f"Image size: {w}x{h}")
167
+
168
+ # Load model
169
+ session = load_model(model_path)
170
+
171
+ # Get input name
172
+ input_name = session.get_inputs()[0].name
173
+ print(f"Model input name: {input_name}")
174
+
175
+ # Preprocess
176
+ print("Preprocessing image...")
177
+ input_tensor = preprocess_image(image)
178
+ print(f"Input tensor shape: {input_tensor.shape}")
179
+
180
+ # Run inference
181
+ print("Running inference...")
182
+ result = session.run(None, {input_name: input_tensor})[0]
183
+ print(f"Output grid shape: {result.shape}")
184
+ print(f"Output grid range: [{result.min():.4f}, {result.max():.4f}]")
185
+
186
+ # Apply unwarping
187
+ print("Applying grid-based unwarping...")
188
+ unwarped = apply_grid_unwarping(image, result)
189
+
190
+ # Save result
191
+ print(f"Saving result to: {output_path}")
192
+ cv2.imwrite(output_path, unwarped)
193
+
194
+ print("Done!")
195
+
196
+
197
+ def main():
198
+ parser = argparse.ArgumentParser(
199
+ description="Unwarp document images using UVDoc grid-output ONNX model",
200
+ formatter_class=argparse.RawDescriptionHelpFormatter,
201
+ epilog="""
202
+ Examples:
203
+ python example.py warped_doc.jpg unwarped_doc.jpg
204
+ python example.py warped_doc.jpg unwarped_doc.jpg --model UVDoc_grid.onnx
205
+ """
206
+ )
207
+
208
+ parser.add_argument(
209
+ "input",
210
+ help="Path to input warped document image"
211
+ )
212
+
213
+ parser.add_argument(
214
+ "output",
215
+ help="Path to save unwarped output image"
216
+ )
217
+
218
+ parser.add_argument(
219
+ "--model", "-m",
220
+ default=None,
221
+ help="Path to UVDoc_grid.onnx model file (downloads from HuggingFace if not provided)"
222
+ )
223
+
224
+ args = parser.parse_args()
225
+
226
+ # Validate input file exists
227
+ if not Path(args.input).exists():
228
+ print(f"Error: Input file not found: {args.input}")
229
+ sys.exit(1)
230
+
231
+ unwarp_document(args.input, args.output, args.model)
232
+
233
+
234
+ if __name__ == "__main__":
235
+ main()