Upload folder using huggingface_hub
Browse filesFiles changed (4)
- LICENSEAdded+190
- README.mdAdded+151
- config.jsonAdded+33
- example.pyAdded+235
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to the Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Copyright 2023 Floor Verhoeven, Tanguy Magne, Olga Sorkine-Hornung
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151---license: apache-2.0library_name: onnxpipeline_tag: image-to-imagetags: - onnx - document-processing - document-unwarping - image-processing - ocr-preprocessing - computer-vision---
# UVDoc Grid Output - Document Unwarping ONNX Model
This is an ONNX export of the [UVDoc](https://github.com/tanguymagne/UVDoc) document unwarping model,modified to output a **coordinate grid** instead of an image. This enables high-resolution documentunwarping via `cv2.remap()`.
## Model Description
UVDoc is a deep learning model for correcting perspective distortion and curvature in photographeddocuments. Unlike the PaddlePaddle ONNX variant that outputs a fixed 288x288 image, this versionoutputs a coordinate mapping grid that can be applied to images of any resolution.
### Key Difference: Grid Output vs Image Output
| Approach | Output | Quality ||----------|--------|---------|| **Image-output models** | 288x288 RGB image | Poor (must upscale) || **This grid-output model** | 45x31 coordinate grid | Native resolution |
## Model Details
- **Architecture:** UVDoc (ResNet-based encoder-decoder)- **Input:** `(1, 3, 720, 496)` - RGB image, normalized [0, 1]- **Output:** `(1, 2, 45, 31)` - Coordinate grid in [-1, 1] range- **ONNX Opset:** 16- **Size:** ~30 MB
### Input Specifications
| Property | Value ||----------|-------|| Shape | `(batch, 3, 720, 496)` || Format | RGB (not BGR) || Range | `[0, 1]` (normalized) || Layout | NCHW (batch, channels, height, width) |
### Output Specifications
| Property | Value ||----------|-------|| Shape | `(batch, 2, 45, 31)` || Channels | 2 (x, y coordinates) || Range | `[-1, 1]` (normalized coordinates) || Layout | NCHW (batch, channels, height, width) |
## Usage
### With ONNX Runtime (Python)
```pythonimport cv2import numpy as npimport onnxruntime as ort
# Load modelsession = ort.InferenceSession("UVDoc_grid.onnx", providers=['CPUExecutionProvider'])
# Load and preprocess imageimage = cv2.imread("warped_document.jpg")h_orig, w_orig = image.shape[:2]
# Prepare model input (720x496 RGB normalized)img_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)resized = cv2.resize(img_rgb, (496, 720)) # width, heightblob = resized.astype(np.float32) / 255.0blob = np.transpose(blob, (2, 0, 1))[None] # (1, 3, 720, 496)
# Run inferenceresult = session.run(None, {'image': blob})[0] # (1, 2, 45, 31)
# Convert grid to remap coordinatesgrid = np.transpose(result[0], (1, 2, 0)) # (45, 31, 2)grid_up = cv2.resize(grid, (w_orig, h_orig), interpolation=cv2.INTER_LINEAR)
map_x = ((grid_up[..., 0] + 1) / 2) * (w_orig - 1)map_y = ((grid_up[..., 1] + 1) / 2) * (h_orig - 1)
# Apply unwarping to original high-res imageunwarped = cv2.remap( image, map_x.astype(np.float32), map_y.astype(np.float32), interpolation=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
cv2.imwrite("unwarped_document.jpg", unwarped)```
### With HuggingFace Hub
```pythonfrom huggingface_hub import hf_hub_download
model_path = hf_hub_download( repo_id="YOUR_USERNAME/uvdoc-grid-onnx", filename="UVDoc_grid.onnx")```
## Training Details
This model was not retrained. It is a direct ONNX export of the original UVDoc weights from[tanguymagne/UVDoc](https://github.com/tanguymagne/UVDoc), with a wrapper to output only the2D coordinate grid (discarding the 3D shape output).
### Original Model
- **Paper:** [UVDoc: Neural Grid-based Document Unwarping](https://arxiv.org/abs/2302.02887)- **Authors:** Floor Verhoeven, Tanguy Magne, Olga Sorkine-Hornung (ETH Zurich)- **Published:** SIGGRAPH Asia 2023- **Original Repository:** [tanguymagne/UVDoc](https://github.com/tanguymagne/UVDoc)
## Limitations
- Input must be resized to 720x496 for inference (grid output is always 45x31)- Works best on documents with visible text/content (needs features for grid estimation)- May not handle extreme perspective distortions well- CPU inference takes ~100-200ms per image
## Citation
If you use this model, please cite the original UVDoc paper:
```bibtex@inproceedings{UVDoc, title={{UVDoc}: Neural Grid-based Document Unwarping}, author={Floor Verhoeven and Tanguy Magne and Olga Sorkine-Hornung}, booktitle = {SIGGRAPH ASIA, Technical Papers}, year = {2023}, url={https://doi.org/10.1145/3610548.3618174}}```
## License
This ONNX export is provided under the Apache 2.0 license. The original UVDoc model is alsoApache 2.0 licensed. See the original repository for full license details.123456789101112131415161718192021222324252627282930313233{ "model_type": "uvdoc", "architecture": "encoder-decoder", "framework": "onnx", "input": { "name": "image", "shape": [1, 3, 720, 496], "format": "NCHW", "dtype": "float32", "color_space": "RGB", "normalization": { "range": [0, 1], "method": "divide_by_255" } }, "output": { "name": "grid_2d", "shape": [1, 2, 45, 31], "format": "NCHW", "dtype": "float32", "description": "2D coordinate grid for document unwarping", "coordinate_range": [-1, 1] }, "onnx_opset": 16, "original_model": { "name": "UVDoc", "repository": "https://github.com/tanguymagne/UVDoc", "paper": "https://arxiv.org/abs/2302.02887", "authors": ["Floor Verhoeven", "Tanguy Magne", "Olga Sorkine-Hornung"], "institution": "ETH Zurich", "venue": "SIGGRAPH Asia 2023" }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235#!/usr/bin/env python3"""UVDoc Grid-Output Document Unwarping Example
This script demonstrates how to use the UVDoc ONNX model with grid outputfor high-resolution document unwarping.
The key advantage of this grid-output model over image-output models is thatthe coordinate grid can be upscaled to any resolution, preserving documentquality when applied via cv2.remap().
Usage: python example.py input_image.jpg output_image.jpg python example.py input_image.jpg output_image.jpg --model path/to/UVDoc_grid.onnx
Requirements: pip install onnxruntime opencv-python numpy
Optional (for automatic model download): pip install huggingface_hub"""
import argparseimport sysfrom pathlib import Path
import cv2import numpy as np
# Model input dimensions (fixed for UVDoc architecture)MODEL_INPUT_HEIGHT = 720MODEL_INPUT_WIDTH = 496
def load_model(model_path: str = None): """ Load the ONNX model.
Args: model_path: Path to the ONNX model file. If None, attempts to download from HuggingFace Hub.
Returns: ONNX Runtime InferenceSession """ import onnxruntime as ort
if model_path is None: try: from huggingface_hub import hf_hub_download
print("Downloading model from HuggingFace Hub...") model_path = hf_hub_download( repo_id="YOUR_USERNAME/uvdoc-grid-onnx", # Update with actual repo filename="UVDoc_grid.onnx" ) print(f"Model downloaded to: {model_path}") except ImportError: print("Error: huggingface_hub not installed. Install it or provide --model path.") print(" pip install huggingface_hub") sys.exit(1)
print(f"Loading model from: {model_path}") session = ort.InferenceSession( model_path, providers=['CPUExecutionProvider'] )
return session
def preprocess_image(image: np.ndarray) -> np.ndarray: """ Preprocess image for UVDoc model input.
Args: image: BGR image from cv2.imread()
Returns: Preprocessed tensor of shape (1, 3, 720, 496) """ # Convert BGR to RGB img_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Resize to model input size resized = cv2.resize(img_rgb, (MODEL_INPUT_WIDTH, MODEL_INPUT_HEIGHT))
# Normalize to [0, 1] normalized = resized.astype(np.float32) / 255.0
# Convert HWC to CHW format transposed = np.transpose(normalized, (2, 0, 1))
# Add batch dimension batched = np.expand_dims(transposed, axis=0)
return batched
def apply_grid_unwarping( image: np.ndarray, grid: np.ndarray, interpolation: int = cv2.INTER_CUBIC) -> np.ndarray: """ Apply the coordinate grid to unwarp the image.
Args: image: Original BGR image (any resolution) grid: Model output grid of shape (1, 2, 45, 31) interpolation: OpenCV interpolation method
Returns: Unwarped image at original resolution """ h_orig, w_orig = image.shape[:2]
# Remove batch dimension and transpose to (H, W, 2) grid_2d = np.transpose(grid[0], (1, 2, 0)) # (45, 31, 2)
# Upscale grid to original image resolution grid_upscaled = cv2.resize( grid_2d, (w_orig, h_orig), interpolation=cv2.INTER_LINEAR )
# Convert normalized coordinates [-1, 1] to pixel coordinates # Grid channel 0 = x (width), channel 1 = y (height) map_x = ((grid_upscaled[..., 0] + 1) / 2) * (w_orig - 1) map_y = ((grid_upscaled[..., 1] + 1) / 2) * (h_orig - 1)
# Apply remapping unwarped = cv2.remap( image, map_x.astype(np.float32), map_y.astype(np.float32), interpolation=interpolation, borderMode=cv2.BORDER_REPLICATE )
return unwarped
def unwarp_document( image_path: str, output_path: str, model_path: str = None) -> None: """ Main function to unwarp a document image.
Args: image_path: Path to input warped document image output_path: Path to save unwarped result model_path: Optional path to ONNX model file """ # Load image print(f"Loading image: {image_path}") image = cv2.imread(image_path) if image is None: print(f"Error: Could not load image from {image_path}") sys.exit(1)
h, w = image.shape[:2] print(f"Image size: {w}x{h}")
# Load model session = load_model(model_path)
# Get input name input_name = session.get_inputs()[0].name print(f"Model input name: {input_name}")
# Preprocess print("Preprocessing image...") input_tensor = preprocess_image(image) print(f"Input tensor shape: {input_tensor.shape}")
# Run inference print("Running inference...") result = session.run(None, {input_name: input_tensor})[0] print(f"Output grid shape: {result.shape}") print(f"Output grid range: [{result.min():.4f}, {result.max():.4f}]")
# Apply unwarping print("Applying grid-based unwarping...") unwarped = apply_grid_unwarping(image, result)
# Save result print(f"Saving result to: {output_path}") cv2.imwrite(output_path, unwarped)
print("Done!")
def main(): parser = argparse.ArgumentParser( description="Unwarp document images using UVDoc grid-output ONNX model", formatter_class=argparse.RawDescriptionHelpFormatter, epilog="""Examples: python example.py warped_doc.jpg unwarped_doc.jpg python example.py warped_doc.jpg unwarped_doc.jpg --model UVDoc_grid.onnx """ )
parser.add_argument( "input", help="Path to input warped document image" )
parser.add_argument( "output", help="Path to save unwarped output image" )
parser.add_argument( "--model", "-m", default=None, help="Path to UVDoc_grid.onnx model file (downloads from HuggingFace if not provided)" )
args = parser.parse_args()
# Validate input file exists if not Path(args.input).exists(): print(f"Error: Input file not found: {args.input}") sys.exit(1)
unwarp_document(args.input, args.output, args.model)
if __name__ == "__main__": main()LICENSEAdded+190
README.mdAdded+151
config.jsonAdded+33
example.pyAdded+235