├── .gitattributes ├── .github └── workflows │ ├── python.yml │ ├── release.yml │ └── rust.yml ├── .gitignore ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE ├── README.md ├── cmdapp ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── pyproject.toml ├── src │ ├── config.rs │ ├── converter.rs │ ├── lib.rs │ ├── main.rs │ ├── python.rs │ └── svg.rs └── vtracer │ ├── README.md │ ├── __init__.py │ └── vtracer.pyi ├── docs ├── 0.bootstrap.js ├── 589cb57662b50620abca.module.wasm ├── COPYRIGHT ├── assets │ ├── apple-icon.png │ ├── samples │ │ ├── 46.svg │ │ ├── Cityscape Sunset_DFM3-01.jpg │ │ ├── Cityscape Sunset_DFM3-01.svg │ │ ├── Gum Tree Vector.jpg │ │ ├── Gum Tree Vector.svg │ │ ├── K1_drawing.jpg │ │ ├── angel-luciano-LATYeZyw88c-unsplash-s.jpg │ │ ├── angel-luciano-LATYeZyw88c-unsplash.jpg │ │ ├── tank-unit-preview.png │ │ ├── vectorstock_31191940.ai │ │ └── vectorstock_31191940.png │ ├── visioncortex-logo-light.svg │ └── visioncortex-logo.svg ├── bootstrap.js ├── images │ ├── aliyun-logo.png │ ├── screenshot-01.png │ ├── screenshot-02.png │ ├── visioncortex icon.png │ └── visioncortex-banner.png ├── index.html └── uikit │ ├── css │ ├── uikit-rtl.css │ ├── uikit-rtl.min.css │ ├── uikit.css │ └── uikit.min.css │ └── js │ ├── uikit-icons.js │ ├── uikit-icons.min.js │ ├── uikit.js │ └── uikit.min.js └── webapp ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── Readme.md ├── app ├── .gitignore ├── bootstrap.js ├── index.html ├── index.js ├── package-lock.json ├── package.json └── webpack.config.js └── src ├── canvas.rs ├── common.rs ├── conversion ├── binary_image.rs ├── color_image.rs ├── mod.rs └── util.rs ├── lib.rs ├── svg.rs └── utils.rs /.gitattributes: -------------------------------------------------------------------------------- 1 | docs/** linguist-generated 2 | -------------------------------------------------------------------------------- /.github/workflows/python.yml: -------------------------------------------------------------------------------- 1 | # This file is autogenerated by maturin v1.2.3 2 | # To update, run 3 | # 4 | # maturin generate-ci github 5 | # 6 | name: Python 7 | 8 | on: 9 | push: 10 | tags: 11 | - '*' 12 | pull_request: 13 | workflow_dispatch: 14 | 15 | permissions: 16 | contents: read 17 | 18 | jobs: 19 | linux: 20 | runs-on: ubuntu-latest 21 | strategy: 22 | matrix: 23 | target: [x86_64, x86, aarch64, armv7, s390x, ppc64le] 24 | steps: 25 | - uses: actions/checkout@v3 26 | - uses: actions/setup-python@v4 27 | with: 28 | python-version: '3.10' 29 | - name: Build wheels 30 | uses: PyO3/maturin-action@v1 31 | with: 32 | target: ${{ matrix.target }} 33 | args: -m cmdapp/Cargo.toml --release --out dist --find-interpreter 34 | sccache: 'true' 35 | manylinux: auto 36 | - name: Upload wheels 37 | uses: actions/upload-artifact@v3 38 | with: 39 | name: wheels 40 | path: dist 41 | 42 | windows: 43 | runs-on: windows-latest 44 | strategy: 45 | matrix: 46 | target: [x64, x86] 47 | steps: 48 | - uses: actions/checkout@v3 49 | - uses: actions/setup-python@v4 50 | with: 51 | python-version: '3.10' 52 | architecture: ${{ matrix.target }} 53 | - name: Build wheels 54 | uses: PyO3/maturin-action@v1 55 | with: 56 | target: ${{ matrix.target }} 57 | args: -m cmdapp/Cargo.toml --release --out dist --find-interpreter 58 | sccache: 'true' 59 | - name: Upload wheels 60 | uses: actions/upload-artifact@v3 61 | with: 62 | name: wheels 63 | path: dist 64 | 65 | macos: 66 | runs-on: macos-latest 67 | strategy: 68 | matrix: 69 | target: [x86_64, aarch64] 70 | steps: 71 | - uses: actions/checkout@v3 72 | - uses: actions/setup-python@v4 73 | with: 74 | python-version: '3.10' 75 | - name: Build wheels 76 | uses: PyO3/maturin-action@v1 77 | with: 78 | target: ${{ matrix.target }} 79 | args: -m cmdapp/Cargo.toml --release --out dist --find-interpreter 80 | sccache: 'true' 81 | - name: Upload wheels 82 | uses: actions/upload-artifact@v3 83 | with: 84 | name: wheels 85 | path: dist 86 | 87 | sdist: 88 | runs-on: ubuntu-latest 89 | steps: 90 | - uses: actions/checkout@v3 91 | - name: Build sdist 92 | uses: PyO3/maturin-action@v1 93 | with: 94 | command: sdist 95 | args: -m cmdapp/Cargo.toml --out dist 96 | - name: Upload sdist 97 | uses: actions/upload-artifact@v3 98 | with: 99 | name: wheels 100 | path: dist 101 | 102 | release: 103 | name: Release 104 | runs-on: ubuntu-latest 105 | # Specifying a GitHub environment is optional, but strongly encouraged 106 | environment: python 107 | permissions: 108 | # IMPORTANT: this permission is mandatory for trusted publishing 109 | id-token: write 110 | if: "startsWith(github.ref, 'refs/tags/')" 111 | needs: [windows, macos, sdist, linux] 112 | steps: 113 | - uses: actions/download-artifact@v3 114 | with: 115 | name: wheels 116 | - name: Publish to PyPI 117 | uses: PyO3/maturin-action@v1 118 | with: 119 | command: upload 120 | args: --non-interactive --skip-existing * 121 | # manylinux: auto 122 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | release: 5 | types: [published] 6 | 7 | jobs: 8 | release: 9 | strategy: 10 | matrix: 11 | include: 12 | - target: aarch64-unknown-linux-musl 13 | os: ubuntu-latest 14 | - target: x86_64-unknown-linux-musl 15 | os: ubuntu-latest 16 | - target: aarch64-apple-darwin 17 | os: macos-latest 18 | - target: x86_64-apple-darwin 19 | os: macos-latest 20 | - target: x86_64-pc-windows-msvc 21 | os: windows-latest 22 | runs-on: ${{ matrix.os }} 23 | steps: 24 | - uses: actions/checkout@v4 25 | - uses: taiki-e/upload-rust-binary-action@v1 26 | with: 27 | bin: vtracer 28 | target: ${{ matrix.target }} 29 | # (required) GitHub token for uploading assets to GitHub Releases. 30 | token: ${{ secrets.GITHUB_TOKEN }} -------------------------------------------------------------------------------- /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | pull_request: 5 | paths-ignore: 6 | - '**.md' 7 | - '.github/ISSUE_TEMPLATE/**' 8 | push: 9 | paths-ignore: 10 | - '**.md' 11 | - '.github/ISSUE_TEMPLATE/**' 12 | branches: 13 | - master 14 | - 0.*.x 15 | - pr/**/ci 16 | - ci-* 17 | 18 | concurrency: 19 | group: ${{ github.workflow }}-${{ github.head_ref || github.ref || github.run_id }} 20 | cancel-in-progress: true 21 | 22 | env: 23 | CARGO_TERM_COLOR: always 24 | 25 | jobs: 26 | build: 27 | 28 | runs-on: ubuntu-latest 29 | 30 | steps: 31 | - uses: actions/checkout@v2 32 | - name: Build 33 | run: cargo build --verbose 34 | - name: Run tests 35 | run: cargo test --verbose 36 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | *.sublime* 4 | .vscode -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](http://keepachangelog.com/) 6 | and this project adheres to [Semantic Versioning](http://semver.org/). 7 | 8 | ## 0.6.4 - 2024-03-29 9 | 10 | * Update `visioncortex` version to `0.8.8` 11 | 12 | ## 0.6.3 - 2023-11-21 13 | 14 | * New converter API https://github.com/visioncortex/vtracer/pull/59 15 | 16 | ## 0.6.1 - 2023-09-23 17 | 18 | * Fixed "The two lines are parallel!" 19 | 20 | ### Python Binding 21 | 22 | Thanks to the contribution of [@etjones](https://github.com/etjones), we now have an official Python binding! https://github.com/visioncortex/vtracer/pull/55 23 | 24 | https://pypi.org/project/vtracer/0.6.10/ 25 | 26 | ## 0.5.0 - 2022-10-09 27 | 28 | * Handle transparent png images (cli) https://github.com/visioncortex/vtracer/pull/23 29 | 30 | ## 0.4.0 - 2021-07-23 31 | 32 | * SVG path string numeric precision 33 | 34 | ## 0.3.0 - 2021-01-24 35 | 36 | * Added cutout mode 37 | 38 | ## 0.2.0 - 2020-11-15 39 | 40 | * Use relative & closed paths 41 | 42 | ## 0.1.1 - 2020-11-01 43 | 44 | * SVG namespace 45 | 46 | ## 0.1.0 - 2020-10-31 47 | 48 | * Initial release -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | 3 | members = [ 4 | "cmdapp", 5 | "webapp", 6 | ] 7 | resolver = "2" -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2024 TSANG, Hao Fung 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 | 4 |

VTracer

5 | 6 |

7 | Raster to Vector Graphics Converter built on top of visioncortex 8 |

9 | 10 |

11 | Article 12 | | 13 | Web App 14 | | 15 | Download 16 |

17 | 18 | Built with 🦀 by The Vision Cortex Research Group 19 |
20 | 21 | ## Introduction 22 | 23 | visioncortex VTracer is an open source software to convert raster images (like jpg & png) into vector graphics (svg). It can vectorize graphics and photographs and trace the curves to output compact vector files. 24 | 25 | Comparing to [Potrace](http://potrace.sourceforge.net/) which only accept binarized inputs (Black & White pixmap), VTracer has an image processing pipeline which can handle colored high resolution scans. tl;dr: Potrace uses a `O(n^2)` fitting algorithm, whereas `vtracer` is entirely `O(n)`. 26 | 27 | Comparing to Adobe Illustrator's [Image Trace](https://helpx.adobe.com/illustrator/using/image-trace.html), VTracer's output is much more compact (less shapes) as we adopt a stacking strategy and avoid producing shapes with holes. 28 | 29 | VTracer is originally designed for processing high resolution scans of historic blueprints up to gigapixels. At the same time, VTracer can also handle low resolution pixel art, simulating `image-rendering: pixelated` for retro game artworks. 30 | 31 | Technical descriptions of the [tracing algorithm](https://www.visioncortex.org/vtracer-docs) and [clustering algorithm](https://www.visioncortex.org/impression-docs). 32 | 33 | ## Web App 34 | 35 | VTracer and its [core library](//github.com/visioncortex/visioncortex) is implemented in [Rust](//www.rust-lang.org/). It provides us a solid foundation to develop robust and efficient algorithms and easily bring it to interactive applications. The webapp is a perfect showcase of the capability of the Rust + wasm platform. 36 | 37 | ![screenshot](docs/images/screenshot-01.png) 38 | 39 | ![screenshot](docs/images/screenshot-02.png) 40 | 41 | ## Cmd App 42 | 43 | ```sh 44 | visioncortex VTracer 0.6.0 45 | A cmd app to convert images into vector graphics. 46 | 47 | USAGE: 48 | vtracer [OPTIONS] --input --output 49 | 50 | FLAGS: 51 | -h, --help Prints help information 52 | -V, --version Prints version information 53 | 54 | OPTIONS: 55 | --colormode True color image `color` (default) or Binary image `bw` 56 | -p, --color_precision Number of significant bits to use in an RGB channel 57 | -c, --corner_threshold Minimum momentary angle (degree) to be considered a corner 58 | -f, --filter_speckle Discard patches smaller than X px in size 59 | -g, --gradient_step Color difference between gradient layers 60 | --hierarchical 61 | Hierarchical clustering `stacked` (default) or non-stacked `cutout`. Only applies to color mode. 62 | 63 | -i, --input Path to input raster image 64 | -m, --mode Curver fitting mode `pixel`, `polygon`, `spline` 65 | -o, --output Path to output vector graphics 66 | --path_precision Number of decimal places to use in path string 67 | --preset Use one of the preset configs `bw`, `poster`, `photo` 68 | -l, --segment_length 69 | Perform iterative subdivide smooth until all segments are shorter than this length 70 | 71 | -s, --splice_threshold Minimum angle displacement (degree) to splice a spline 72 | ``` 73 | 74 | ## Downloads 75 | 76 | You can download pre-built binaries from [Releases](https://github.com/visioncortex/vtracer/releases). 77 | 78 | You can also install the program from source from [crates.io/vtracer](https://crates.io/crates/vtracer): 79 | 80 | ```sh 81 | cargo install vtracer 82 | ``` 83 | 84 | > You are strongly advised to not download from any other third-party sources 85 | 86 | ### Usage 87 | 88 | ```sh 89 | ./vtracer --input input.jpg --output output.svg 90 | ``` 91 | 92 | ### Rust Library 93 | 94 | You can install [`vtracer`](https://crates.io/crates/vtracer) as a Rust library. 95 | 96 | ```sh 97 | cargo add vtracer 98 | ``` 99 | 100 | ### Python Library 101 | 102 | Since `0.6`, [`vtracer`](https://pypi.org/project/vtracer/) is also packaged as Python native extensions, thanks to the awesome [pyo3](https://github.com/PyO3/pyo3) project. 103 | 104 | ```sh 105 | pip install vtracer 106 | ``` 107 | 108 | ## In the wild 109 | 110 | VTracer is used by the following products (open a PR to add yours): 111 | 112 | 113 | 114 | 115 | 118 | 119 | 120 | 121 |
116 |
Smart logo design 117 |
122 | 123 | ## Citations 124 | 125 | VTracer has since been cited by a few academic papers in computer graphics / vision research. Please kindly let us know if you have cited our work: 126 | 127 | + SKILL 2023 [Framework to Vectorize Digital Artworks for Physical Fabrication based on Geometric Stylization Techniques](https://www.researchgate.net/publication/374448489_Framework_to_Vectorize_Digital_Artworks_for_Physical_Fabrication_based_on_Geometric_Stylization_Techniques) 128 | + arXiv 2023 [Image Vectorization: a Review](https://arxiv.org/abs/2306.06441) 129 | + arXiv 2023 [StarVector: Generating Scalable Vector Graphics Code from Images](https://arxiv.org/abs/2312.11556) 130 | + arXiv 2024 [Text-Based Reasoning About Vector Graphics](https://arxiv.org/abs/2404.06479) 131 | + arXiv 2024 [Delving into LLMs' visual understanding ability using SVG to bridge image and text](https://openreview.net/pdf?id=pwlm6Po61I) 132 | 133 | ## How did VTracer come about? 134 | 135 | > The following content is an excerpt from my [unpublished memoir](https://github.com/visioncortex/memoir). 136 | 137 | At my teenage, two open source projects in the vector graphics space inspired me the most: Potrace and Anti-Grain Geometry (AGG). 138 | 139 | Many years later, in 2020, I was developing a video processing engine. And it became evident that it requires way more investment to be commercially viable. So before abandoning the project, I wanted to publish *something* as open-source for posterity. At that time, I already developed a prototype vector graphics tracer. It can convert high-resolution scans of hand-drawn blueprints into vectors. But it can only process black and white images, and can only output polygons, not splines. 140 | 141 | The plan was to fully develop the vectorizer: to handle color images and output splines. I recruited a very talented intern, [@shpun817](https://github.com/shpun817), to work on VTracer. I grafted the frontend of the video processing engine - the ["The Clustering Algorithm"](https://www.visioncortex.org/impression-docs#the-clustering-algorithm) as the pre-processor. 142 | 143 | Three months later, we published the first version on Reddit. Out of my surprise, the response of such an underwhelming project was overwhelming. 144 | 145 | ## What's next? 146 | 147 | There are several things in my mind: 148 | 149 | 1. Path simplification. Implement a post-process filter to the output paths to further reduce the number of splines. 150 | 151 | 2. Perfect cut-out mode. Right now in cut-out mode, the shapes do not share boundaries perfectly, but have seams. 152 | 153 | 3. Pencil tracing. Instead of tracing shapes as closed paths, may be we can attempt to skeletonize the shapes as open paths. The output would be clean, fixed width strokes. 154 | 155 | 4. Image cleaning. Right now the tracer works best on losslessly compressed pngs. If an image suffered from jpeg noises, it could impact the tracing quality. We might be able to develop a pre-filtering pass that denoises the input. 156 | 157 | If you are interested in working on them or willing to sponsor its development, feel free to get in touch. 158 | -------------------------------------------------------------------------------- /cmdapp/.gitignore: -------------------------------------------------------------------------------- 1 | *.svg 2 | *.png 3 | *.jpg -------------------------------------------------------------------------------- /cmdapp/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "vtracer" 3 | version = "0.6.4" 4 | authors = ["Chris Tsang "] 5 | edition = "2021" 6 | description = "A cmd app to convert images into vector graphics." 7 | license = "MIT OR Apache-2.0" 8 | homepage = "http://www.visioncortex.org/vtracer" 9 | repository = "https://github.com/visioncortex/vtracer/" 10 | categories = ["graphics"] 11 | keywords = ["svg", "computer-graphics"] 12 | 13 | [dependencies] 14 | clap = "2.33.3" 15 | image = "0.23.10" 16 | visioncortex = { version = "0.8.8" } 17 | fastrand = "1.8" 18 | pyo3 = { version = "0.19.0", optional = true } 19 | 20 | [features] 21 | python-binding = ["pyo3"] 22 | 23 | [lib] 24 | name = "vtracer" 25 | crate-type = ["rlib", "cdylib"] -------------------------------------------------------------------------------- /cmdapp/LICENSE-APACHE: -------------------------------------------------------------------------------- 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 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 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /cmdapp/LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2023 Tsang Hao Fung 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /cmdapp/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 | 4 |

VTracer

5 | 6 |

7 | Raster to Vector Graphics Converter built on top of visioncortex 8 |

9 | 10 |

11 | Article 12 | | 13 | Demo 14 | | 15 | Download 16 |

17 | 18 | Built with 🦀 by The Vision Cortex Research Group 19 |
20 | 21 | ## Introduction 22 | 23 | visioncortex VTracer is an open source software to convert raster images (like jpg & png) into vector graphics (svg). It can vectorize graphics and photographs and trace the curves to output compact vector files. 24 | 25 | Comparing to [Potrace](http://potrace.sourceforge.net/) which only accept binarized inputs (Black & White pixmap), VTracer has an image processing pipeline which can handle colored high resolution scans. 26 | 27 | Comparing to Adobe Illustrator's [Image Trace](https://helpx.adobe.com/illustrator/using/image-trace.html), VTracer's output is much more compact (less shapes) as we adopt a stacking strategy and avoid producing shapes with holes. 28 | 29 | VTracer is originally designed for processing high resolution scans of historic blueprints up to gigapixels. At the same time, VTracer can also handle low resolution pixel art, simulating `image-rendering: pixelated` for retro game artworks. 30 | 31 | A technical description of the algorithm is on [visioncortex.org/vtracer-docs](https://www.visioncortex.org/vtracer-docs). 32 | 33 | ## Cmd App 34 | 35 | ```sh 36 | visioncortex VTracer 0.6.0 37 | A cmd app to convert images into vector graphics. 38 | 39 | USAGE: 40 | vtracer [OPTIONS] --input --output 41 | 42 | FLAGS: 43 | -h, --help Prints help information 44 | -V, --version Prints version information 45 | 46 | OPTIONS: 47 | --colormode True color image `color` (default) or Binary image `bw` 48 | -p, --color_precision Number of significant bits to use in an RGB channel 49 | -c, --corner_threshold Minimum momentary angle (degree) to be considered a corner 50 | -f, --filter_speckle Discard patches smaller than X px in size 51 | -g, --gradient_step Color difference between gradient layers 52 | --hierarchical 53 | Hierarchical clustering `stacked` (default) or non-stacked `cutout`. Only applies to color mode. 54 | 55 | -i, --input Path to input raster image 56 | -m, --mode Curver fitting mode `pixel`, `polygon`, `spline` 57 | -o, --output Path to output vector graphics 58 | --path_precision Number of decimal places to use in path string 59 | --preset Use one of the preset configs `bw`, `poster`, `photo` 60 | -l, --segment_length 61 | Perform iterative subdivide smooth until all segments are shorter than this length 62 | 63 | -s, --splice_threshold Minimum angle displacement (degree) to splice a spline 64 | ``` 65 | 66 | ### Install 67 | 68 | You can download pre-built binaries from [Releases](https://github.com/visioncortex/vtracer/releases). 69 | 70 | You can also install the program from source from [crates.io/vtracer](https://crates.io/crates/vtracer): 71 | 72 | ```sh 73 | cargo install vtracer 74 | ``` 75 | 76 | ### Usage 77 | 78 | ```sh 79 | ./vtracer --input input.jpg --output output.svg 80 | ``` 81 | 82 | ## Rust Library 83 | 84 | You can install [`vtracer`](https://crates.io/crates/vtracer) as a Rust library. 85 | 86 | ```sh 87 | cargo add vtracer 88 | ``` 89 | 90 | ## Python Library 91 | 92 | Since `0.6`, [`vtracer`](https://pypi.org/project/vtracer/) is also packaged as Python native extensions, thanks to the awesome [pyo3](https://github.com/PyO3/pyo3) project. 93 | 94 | ```sh 95 | pip install vtracer 96 | ``` 97 | -------------------------------------------------------------------------------- /cmdapp/pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "vtracer" 3 | version = "0.6.11" 4 | description = "Python bindings for the Rust Vtracer raster-to-vector library" 5 | authors = [ { name = "Chris Tsang", email = "chris.2y3@outlook.com" } ] 6 | readme = "vtracer/README.md" 7 | requires-python = ">=3.7" 8 | license = "MIT" 9 | classifiers = [ 10 | "Programming Language :: Rust", 11 | "Programming Language :: Python :: Implementation :: CPython", 12 | "Programming Language :: Python :: Implementation :: PyPy", 13 | ] 14 | 15 | [dependencies] 16 | python = "^3.7" 17 | 18 | [dev-dependencies] 19 | maturin = "^1.2" 20 | 21 | [build-system] 22 | requires = ["maturin>=1.2,<2.0"] 23 | build-backend = "maturin" 24 | 25 | [tool.maturin] 26 | features = ["pyo3/extension-module", "python-binding"] 27 | compatibility = "manylinux2014" 28 | sdist-include = ["LICENSE-MIT", "vtracer/README.md"] -------------------------------------------------------------------------------- /cmdapp/src/config.rs: -------------------------------------------------------------------------------- 1 | use std::str::FromStr; 2 | use visioncortex::PathSimplifyMode; 3 | 4 | #[derive(Debug, Clone)] 5 | pub enum Preset { 6 | Bw, 7 | Poster, 8 | Photo, 9 | } 10 | 11 | #[derive(Debug, Clone)] 12 | pub enum ColorMode { 13 | Color, 14 | Binary, 15 | } 16 | 17 | #[derive(Debug, Clone)] 18 | pub enum Hierarchical { 19 | Stacked, 20 | Cutout, 21 | } 22 | 23 | /// Converter config 24 | #[derive(Debug, Clone)] 25 | pub struct Config { 26 | pub color_mode: ColorMode, 27 | pub hierarchical: Hierarchical, 28 | pub filter_speckle: usize, 29 | pub color_precision: i32, 30 | pub layer_difference: i32, 31 | pub mode: PathSimplifyMode, 32 | pub corner_threshold: i32, 33 | pub length_threshold: f64, 34 | pub max_iterations: usize, 35 | pub splice_threshold: i32, 36 | pub path_precision: Option, 37 | } 38 | 39 | #[derive(Debug, Clone)] 40 | pub(crate) struct ConverterConfig { 41 | pub color_mode: ColorMode, 42 | pub hierarchical: Hierarchical, 43 | pub filter_speckle_area: usize, 44 | pub color_precision_loss: i32, 45 | pub layer_difference: i32, 46 | pub mode: PathSimplifyMode, 47 | pub corner_threshold: f64, 48 | pub length_threshold: f64, 49 | pub max_iterations: usize, 50 | pub splice_threshold: f64, 51 | pub path_precision: Option, 52 | } 53 | 54 | impl Default for Config { 55 | fn default() -> Self { 56 | Self { 57 | color_mode: ColorMode::Color, 58 | hierarchical: Hierarchical::Stacked, 59 | mode: PathSimplifyMode::Spline, 60 | filter_speckle: 4, 61 | color_precision: 6, 62 | layer_difference: 16, 63 | corner_threshold: 60, 64 | length_threshold: 4.0, 65 | splice_threshold: 45, 66 | max_iterations: 10, 67 | path_precision: Some(2), 68 | } 69 | } 70 | } 71 | 72 | impl FromStr for ColorMode { 73 | type Err = String; 74 | 75 | fn from_str(s: &str) -> Result { 76 | match s { 77 | "color" => Ok(Self::Color), 78 | "binary" => Ok(Self::Binary), 79 | _ => Err(format!("unknown ColorMode {}", s)), 80 | } 81 | } 82 | } 83 | 84 | impl FromStr for Hierarchical { 85 | type Err = String; 86 | 87 | fn from_str(s: &str) -> Result { 88 | match s { 89 | "stacked" => Ok(Self::Stacked), 90 | "cutout" => Ok(Self::Cutout), 91 | _ => Err(format!("unknown Hierarchical {}", s)), 92 | } 93 | } 94 | } 95 | 96 | impl FromStr for Preset { 97 | type Err = String; 98 | 99 | fn from_str(s: &str) -> Result { 100 | match s { 101 | "bw" => Ok(Self::Bw), 102 | "poster" => Ok(Self::Poster), 103 | "photo" => Ok(Self::Photo), 104 | _ => Err(format!("unknown Preset {}", s)), 105 | } 106 | } 107 | } 108 | 109 | impl Config { 110 | pub fn from_preset(preset: Preset) -> Self { 111 | match preset { 112 | Preset::Bw => Self { 113 | color_mode: ColorMode::Binary, 114 | hierarchical: Hierarchical::Stacked, 115 | filter_speckle: 4, 116 | color_precision: 6, 117 | layer_difference: 16, 118 | mode: PathSimplifyMode::Spline, 119 | corner_threshold: 60, 120 | length_threshold: 4.0, 121 | max_iterations: 10, 122 | splice_threshold: 45, 123 | path_precision: Some(2), 124 | }, 125 | Preset::Poster => Self { 126 | color_mode: ColorMode::Color, 127 | hierarchical: Hierarchical::Stacked, 128 | filter_speckle: 4, 129 | color_precision: 8, 130 | layer_difference: 16, 131 | mode: PathSimplifyMode::Spline, 132 | corner_threshold: 60, 133 | length_threshold: 4.0, 134 | max_iterations: 10, 135 | splice_threshold: 45, 136 | path_precision: Some(2), 137 | }, 138 | Preset::Photo => Self { 139 | color_mode: ColorMode::Color, 140 | hierarchical: Hierarchical::Stacked, 141 | filter_speckle: 10, 142 | color_precision: 8, 143 | layer_difference: 48, 144 | mode: PathSimplifyMode::Spline, 145 | corner_threshold: 180, 146 | length_threshold: 4.0, 147 | max_iterations: 10, 148 | splice_threshold: 45, 149 | path_precision: Some(2), 150 | }, 151 | } 152 | } 153 | 154 | pub(crate) fn into_converter_config(self) -> ConverterConfig { 155 | ConverterConfig { 156 | color_mode: self.color_mode, 157 | hierarchical: self.hierarchical, 158 | filter_speckle_area: self.filter_speckle * self.filter_speckle, 159 | color_precision_loss: 8 - self.color_precision, 160 | layer_difference: self.layer_difference, 161 | mode: self.mode, 162 | corner_threshold: deg2rad(self.corner_threshold), 163 | length_threshold: self.length_threshold, 164 | max_iterations: self.max_iterations, 165 | splice_threshold: deg2rad(self.splice_threshold), 166 | path_precision: self.path_precision, 167 | } 168 | } 169 | } 170 | 171 | fn deg2rad(deg: i32) -> f64 { 172 | deg as f64 / 180.0 * std::f64::consts::PI 173 | } 174 | -------------------------------------------------------------------------------- /cmdapp/src/converter.rs: -------------------------------------------------------------------------------- 1 | use std::path::Path; 2 | use std::{fs::File, io::Write}; 3 | 4 | use super::config::{ColorMode, Config, ConverterConfig, Hierarchical}; 5 | use super::svg::SvgFile; 6 | use fastrand::Rng; 7 | use visioncortex::color_clusters::{KeyingAction, Runner, RunnerConfig, HIERARCHICAL_MAX}; 8 | use visioncortex::{Color, ColorImage, ColorName}; 9 | 10 | const NUM_UNUSED_COLOR_ITERATIONS: usize = 6; 11 | /// The fraction of pixels in the top/bottom rows of the image that need to be transparent before 12 | /// the entire image will be keyed. 13 | const KEYING_THRESHOLD: f32 = 0.2; 14 | 15 | /// Convert an in-memory image into an in-memory SVG 16 | pub fn convert(img: ColorImage, config: Config) -> Result { 17 | let config = config.into_converter_config(); 18 | match config.color_mode { 19 | ColorMode::Color => color_image_to_svg(img, config), 20 | ColorMode::Binary => binary_image_to_svg(img, config), 21 | } 22 | } 23 | 24 | /// Convert an image file into svg file 25 | pub fn convert_image_to_svg( 26 | input_path: &Path, 27 | output_path: &Path, 28 | config: Config, 29 | ) -> Result<(), String> { 30 | let img = read_image(input_path)?; 31 | let svg = convert(img, config)?; 32 | write_svg(svg, output_path) 33 | } 34 | 35 | fn color_exists_in_image(img: &ColorImage, color: Color) -> bool { 36 | for y in 0..img.height { 37 | for x in 0..img.width { 38 | let pixel_color = img.get_pixel(x, y); 39 | if pixel_color.r == color.r && pixel_color.g == color.g && pixel_color.b == color.b { 40 | return true; 41 | } 42 | } 43 | } 44 | false 45 | } 46 | 47 | fn find_unused_color_in_image(img: &ColorImage) -> Result { 48 | let special_colors = IntoIterator::into_iter([ 49 | Color::new(255, 0, 0), 50 | Color::new(0, 255, 0), 51 | Color::new(0, 0, 255), 52 | Color::new(255, 255, 0), 53 | Color::new(0, 255, 255), 54 | Color::new(255, 0, 255), 55 | ]); 56 | let rng = Rng::new(); 57 | let random_colors = 58 | (0..NUM_UNUSED_COLOR_ITERATIONS).map(|_| Color::new(rng.u8(..), rng.u8(..), rng.u8(..))); 59 | for color in special_colors.chain(random_colors) { 60 | if !color_exists_in_image(img, color) { 61 | return Ok(color); 62 | } 63 | } 64 | Err(String::from( 65 | "unable to find unused color in image to use as key", 66 | )) 67 | } 68 | 69 | fn should_key_image(img: &ColorImage) -> bool { 70 | if img.width == 0 || img.height == 0 { 71 | return false; 72 | } 73 | 74 | // Check for transparency at several scanlines 75 | let threshold = ((img.width * 2) as f32 * KEYING_THRESHOLD) as usize; 76 | let mut num_transparent_pixels = 0; 77 | let y_positions = [ 78 | 0, 79 | img.height / 4, 80 | img.height / 2, 81 | 3 * img.height / 4, 82 | img.height - 1, 83 | ]; 84 | for y in y_positions { 85 | for x in 0..img.width { 86 | if img.get_pixel(x, y).a == 0 { 87 | num_transparent_pixels += 1; 88 | } 89 | if num_transparent_pixels >= threshold { 90 | return true; 91 | } 92 | } 93 | } 94 | 95 | false 96 | } 97 | 98 | fn color_image_to_svg(mut img: ColorImage, config: ConverterConfig) -> Result { 99 | let width = img.width; 100 | let height = img.height; 101 | 102 | let key_color = if should_key_image(&img) { 103 | let key_color = find_unused_color_in_image(&img)?; 104 | for y in 0..height { 105 | for x in 0..width { 106 | if img.get_pixel(x, y).a == 0 { 107 | img.set_pixel(x, y, &key_color); 108 | } 109 | } 110 | } 111 | key_color 112 | } else { 113 | // The default color is all zeroes, which is treated by visioncortex as a special value meaning no keying will be applied. 114 | Color::default() 115 | }; 116 | 117 | let runner = Runner::new( 118 | RunnerConfig { 119 | diagonal: config.layer_difference == 0, 120 | hierarchical: HIERARCHICAL_MAX, 121 | batch_size: 25600, 122 | good_min_area: config.filter_speckle_area, 123 | good_max_area: (width * height), 124 | is_same_color_a: config.color_precision_loss, 125 | is_same_color_b: 1, 126 | deepen_diff: config.layer_difference, 127 | hollow_neighbours: 1, 128 | key_color, 129 | keying_action: if matches!(config.hierarchical, Hierarchical::Cutout) { 130 | KeyingAction::Keep 131 | } else { 132 | KeyingAction::Discard 133 | }, 134 | }, 135 | img, 136 | ); 137 | 138 | let mut clusters = runner.run(); 139 | 140 | match config.hierarchical { 141 | Hierarchical::Stacked => {} 142 | Hierarchical::Cutout => { 143 | let view = clusters.view(); 144 | let image = view.to_color_image(); 145 | let runner = Runner::new( 146 | RunnerConfig { 147 | diagonal: false, 148 | hierarchical: 64, 149 | batch_size: 25600, 150 | good_min_area: 0, 151 | good_max_area: (image.width * image.height) as usize, 152 | is_same_color_a: 0, 153 | is_same_color_b: 1, 154 | deepen_diff: 0, 155 | hollow_neighbours: 0, 156 | key_color, 157 | keying_action: KeyingAction::Discard, 158 | }, 159 | image, 160 | ); 161 | clusters = runner.run(); 162 | } 163 | } 164 | 165 | let view = clusters.view(); 166 | 167 | let mut svg = SvgFile::new(width, height, config.path_precision); 168 | for &cluster_index in view.clusters_output.iter().rev() { 169 | let cluster = view.get_cluster(cluster_index); 170 | let paths = cluster.to_compound_path( 171 | &view, 172 | false, 173 | config.mode, 174 | config.corner_threshold, 175 | config.length_threshold, 176 | config.max_iterations, 177 | config.splice_threshold, 178 | ); 179 | svg.add_path(paths, cluster.residue_color()); 180 | } 181 | 182 | Ok(svg) 183 | } 184 | 185 | fn binary_image_to_svg(img: ColorImage, config: ConverterConfig) -> Result { 186 | let img = img.to_binary_image(|x| x.r < 128); 187 | let width = img.width; 188 | let height = img.height; 189 | 190 | let clusters = img.to_clusters(false); 191 | 192 | let mut svg = SvgFile::new(width, height, config.path_precision); 193 | for i in 0..clusters.len() { 194 | let cluster = clusters.get_cluster(i); 195 | if cluster.size() >= config.filter_speckle_area { 196 | let paths = cluster.to_compound_path( 197 | config.mode, 198 | config.corner_threshold, 199 | config.length_threshold, 200 | config.max_iterations, 201 | config.splice_threshold, 202 | ); 203 | svg.add_path(paths, Color::color(&ColorName::Black)); 204 | } 205 | } 206 | 207 | Ok(svg) 208 | } 209 | 210 | fn read_image(input_path: &Path) -> Result { 211 | let img = image::open(input_path); 212 | let img = match img { 213 | Ok(file) => file.to_rgba8(), 214 | Err(_) => return Err(String::from("No image file found at specified input path")), 215 | }; 216 | 217 | let (width, height) = (img.width() as usize, img.height() as usize); 218 | let img = ColorImage { 219 | pixels: img.as_raw().to_vec(), 220 | width, 221 | height, 222 | }; 223 | 224 | Ok(img) 225 | } 226 | 227 | fn write_svg(svg: SvgFile, output_path: &Path) -> Result<(), String> { 228 | let out_file = File::create(output_path); 229 | let mut out_file = match out_file { 230 | Ok(file) => file, 231 | Err(_) => return Err(String::from("Cannot create output file.")), 232 | }; 233 | 234 | write!(&mut out_file, "{}", svg).expect("failed to write file."); 235 | 236 | Ok(()) 237 | } 238 | -------------------------------------------------------------------------------- /cmdapp/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2023 Tsang Hao Fung. See the COPYRIGHT 2 | // file at the top-level directory of this distribution and at 3 | // http://rust-lang.org/COPYRIGHT. 4 | // 5 | // Licensed under the Apache License, Version 2.0 or the MIT license 7 | // , at your 8 | // option. This file may not be copied, modified, or distributed 9 | // except according to those terms. 10 | 11 | mod config; 12 | mod converter; 13 | #[cfg(feature = "python-binding")] 14 | mod python; 15 | mod svg; 16 | 17 | pub use config::*; 18 | pub use converter::*; 19 | #[cfg(feature = "python-binding")] 20 | pub use python::*; 21 | pub use svg::*; 22 | pub use visioncortex::ColorImage; 23 | -------------------------------------------------------------------------------- /cmdapp/src/main.rs: -------------------------------------------------------------------------------- 1 | mod config; 2 | mod converter; 3 | mod svg; 4 | 5 | use clap::{App, Arg}; 6 | use config::{ColorMode, Config, Hierarchical, Preset}; 7 | use std::path::PathBuf; 8 | use std::str::FromStr; 9 | use visioncortex::PathSimplifyMode; 10 | 11 | fn path_simplify_mode_from_str(s: &str) -> PathSimplifyMode { 12 | match s { 13 | "polygon" => PathSimplifyMode::Polygon, 14 | "spline" => PathSimplifyMode::Spline, 15 | "none" => PathSimplifyMode::None, 16 | _ => panic!("unknown PathSimplifyMode {}", s), 17 | } 18 | } 19 | 20 | pub fn config_from_args() -> (PathBuf, PathBuf, Config) { 21 | let app = App::new("visioncortex VTracer ".to_owned() + env!("CARGO_PKG_VERSION")) 22 | .about("A cmd app to convert images into vector graphics."); 23 | 24 | let app = app.arg( 25 | Arg::with_name("input") 26 | .long("input") 27 | .short("i") 28 | .takes_value(true) 29 | .help("Path to input raster image") 30 | .required(true), 31 | ); 32 | 33 | let app = app.arg( 34 | Arg::with_name("output") 35 | .long("output") 36 | .short("o") 37 | .takes_value(true) 38 | .help("Path to output vector graphics") 39 | .required(true), 40 | ); 41 | 42 | let app = app.arg( 43 | Arg::with_name("color_mode") 44 | .long("colormode") 45 | .takes_value(true) 46 | .help("True color image `color` (default) or Binary image `bw`"), 47 | ); 48 | 49 | let app = app.arg( 50 | Arg::with_name("hierarchical") 51 | .long("hierarchical") 52 | .takes_value(true) 53 | .help( 54 | "Hierarchical clustering `stacked` (default) or non-stacked `cutout`. \ 55 | Only applies to color mode. ", 56 | ), 57 | ); 58 | 59 | let app = app.arg( 60 | Arg::with_name("preset") 61 | .long("preset") 62 | .takes_value(true) 63 | .help("Use one of the preset configs `bw`, `poster`, `photo`"), 64 | ); 65 | 66 | let app = app.arg( 67 | Arg::with_name("filter_speckle") 68 | .long("filter_speckle") 69 | .short("f") 70 | .takes_value(true) 71 | .help("Discard patches smaller than X px in size"), 72 | ); 73 | 74 | let app = app.arg( 75 | Arg::with_name("color_precision") 76 | .long("color_precision") 77 | .short("p") 78 | .takes_value(true) 79 | .help("Number of significant bits to use in an RGB channel"), 80 | ); 81 | 82 | let app = app.arg( 83 | Arg::with_name("gradient_step") 84 | .long("gradient_step") 85 | .short("g") 86 | .takes_value(true) 87 | .help("Color difference between gradient layers"), 88 | ); 89 | 90 | let app = app.arg( 91 | Arg::with_name("corner_threshold") 92 | .long("corner_threshold") 93 | .short("c") 94 | .takes_value(true) 95 | .help("Minimum momentary angle (degree) to be considered a corner"), 96 | ); 97 | 98 | let app = app.arg(Arg::with_name("segment_length") 99 | .long("segment_length") 100 | .short("l") 101 | .takes_value(true) 102 | .help("Perform iterative subdivide smooth until all segments are shorter than this length")); 103 | 104 | let app = app.arg( 105 | Arg::with_name("splice_threshold") 106 | .long("splice_threshold") 107 | .short("s") 108 | .takes_value(true) 109 | .help("Minimum angle displacement (degree) to splice a spline"), 110 | ); 111 | 112 | let app = app.arg( 113 | Arg::with_name("mode") 114 | .long("mode") 115 | .short("m") 116 | .takes_value(true) 117 | .help("Curver fitting mode `pixel`, `polygon`, `spline`"), 118 | ); 119 | 120 | let app = app.arg( 121 | Arg::with_name("path_precision") 122 | .long("path_precision") 123 | .takes_value(true) 124 | .help("Number of decimal places to use in path string"), 125 | ); 126 | 127 | // Extract matches 128 | let matches = app.get_matches(); 129 | 130 | let mut config = Config::default(); 131 | let input_path = matches 132 | .value_of("input") 133 | .expect("Input path is required, please specify it by --input or -i."); 134 | let output_path = matches 135 | .value_of("output") 136 | .expect("Output path is required, please specify it by --output or -o."); 137 | 138 | let input_path = PathBuf::from(input_path); 139 | let output_path = PathBuf::from(output_path); 140 | 141 | if let Some(value) = matches.value_of("preset") { 142 | config = Config::from_preset(Preset::from_str(value).unwrap()); 143 | } 144 | 145 | if let Some(value) = matches.value_of("color_mode") { 146 | config.color_mode = ColorMode::from_str(if value.trim() == "bw" || value.trim() == "BW" { 147 | "binary" 148 | } else { 149 | "color" 150 | }) 151 | .unwrap() 152 | } 153 | 154 | if let Some(value) = matches.value_of("hierarchical") { 155 | config.hierarchical = Hierarchical::from_str(value).unwrap() 156 | } 157 | 158 | if let Some(value) = matches.value_of("mode") { 159 | let value = value.trim(); 160 | config.mode = path_simplify_mode_from_str(if value == "pixel" { 161 | "none" 162 | } else if value == "polygon" { 163 | "polygon" 164 | } else if value == "spline" { 165 | "spline" 166 | } else { 167 | panic!("Parser Error: Curve fitting mode is invalid: {}", value); 168 | }); 169 | } 170 | 171 | if let Some(value) = matches.value_of("filter_speckle") { 172 | if value.trim().parse::().is_ok() { 173 | // is numeric 174 | let value = value.trim().parse::().unwrap(); 175 | if value > 16 { 176 | panic!("Out of Range Error: Filter speckle is invalid at {}. It must be within [0,16].", value); 177 | } 178 | config.filter_speckle = value; 179 | } else { 180 | panic!( 181 | "Parser Error: Filter speckle is not a positive integer: {}.", 182 | value 183 | ); 184 | } 185 | } 186 | 187 | if let Some(value) = matches.value_of("color_precision") { 188 | if value.trim().parse::().is_ok() { 189 | // is numeric 190 | let value = value.trim().parse::().unwrap(); 191 | if value < 1 || value > 8 { 192 | panic!("Out of Range Error: Color precision is invalid at {}. It must be within [1,8].", value); 193 | } 194 | config.color_precision = value; 195 | } else { 196 | panic!( 197 | "Parser Error: Color precision is not an integer: {}.", 198 | value 199 | ); 200 | } 201 | } 202 | 203 | if let Some(value) = matches.value_of("gradient_step") { 204 | if value.trim().parse::().is_ok() { 205 | // is numeric 206 | let value = value.trim().parse::().unwrap(); 207 | if value < 0 || value > 255 { 208 | panic!("Out of Range Error: Gradient step is invalid at {}. It must be within [0,255].", value); 209 | } 210 | config.layer_difference = value; 211 | } else { 212 | panic!("Parser Error: Gradient step is not an integer: {}.", value); 213 | } 214 | } 215 | 216 | if let Some(value) = matches.value_of("corner_threshold") { 217 | if value.trim().parse::().is_ok() { 218 | // is numeric 219 | let value = value.trim().parse::().unwrap(); 220 | if value < 0 || value > 180 { 221 | panic!("Out of Range Error: Corner threshold is invalid at {}. It must be within [0,180].", value); 222 | } 223 | config.corner_threshold = value 224 | } else { 225 | panic!("Parser Error: Corner threshold is not numeric: {}.", value); 226 | } 227 | } 228 | 229 | if let Some(value) = matches.value_of("segment_length") { 230 | if value.trim().parse::().is_ok() { 231 | // is numeric 232 | let value = value.trim().parse::().unwrap(); 233 | if value < 3.5 || value > 10.0 { 234 | panic!("Out of Range Error: Segment length is invalid at {}. It must be within [3.5,10].", value); 235 | } 236 | config.length_threshold = value; 237 | } else { 238 | panic!("Parser Error: Segment length is not numeric: {}.", value); 239 | } 240 | } 241 | 242 | if let Some(value) = matches.value_of("splice_threshold") { 243 | if value.trim().parse::().is_ok() { 244 | // is numeric 245 | let value = value.trim().parse::().unwrap(); 246 | if value < 0 || value > 180 { 247 | panic!("Out of Range Error: Segment length is invalid at {}. It must be within [0,180].", value); 248 | } 249 | config.splice_threshold = value; 250 | } else { 251 | panic!("Parser Error: Segment length is not numeric: {}.", value); 252 | } 253 | } 254 | 255 | if let Some(value) = matches.value_of("path_precision") { 256 | if value.trim().parse::().is_ok() { 257 | // is numeric 258 | let value = value.trim().parse::().ok(); 259 | config.path_precision = value; 260 | } else { 261 | panic!( 262 | "Parser Error: Path precision is not an unsigned integer: {}.", 263 | value 264 | ); 265 | } 266 | } 267 | 268 | (input_path, output_path, config) 269 | } 270 | 271 | fn main() { 272 | let (input_path, output_path, config) = config_from_args(); 273 | let result = converter::convert_image_to_svg(&input_path, &output_path, config); 274 | match result { 275 | Ok(()) => { 276 | println!("Conversion successful."); 277 | } 278 | Err(msg) => { 279 | panic!("Conversion failed with error message: {}", msg); 280 | } 281 | } 282 | } 283 | -------------------------------------------------------------------------------- /cmdapp/src/python.rs: -------------------------------------------------------------------------------- 1 | use crate::*; 2 | use image::{io::Reader, ImageFormat}; 3 | use pyo3::{exceptions::PyException, prelude::*}; 4 | use std::io::{BufReader, Cursor}; 5 | use std::path::PathBuf; 6 | use visioncortex::PathSimplifyMode; 7 | 8 | /// Python binding 9 | #[pyfunction] 10 | fn convert_image_to_svg_py( 11 | image_path: &str, 12 | out_path: &str, 13 | colormode: Option<&str>, // "color" or "binary" 14 | hierarchical: Option<&str>, // "stacked" or "cutout" 15 | mode: Option<&str>, // "polygon", "spline", "none" 16 | filter_speckle: Option, // default: 4 17 | color_precision: Option, // default: 6 18 | layer_difference: Option, // default: 16 19 | corner_threshold: Option, // default: 60 20 | length_threshold: Option, // in [3.5, 10] default: 4.0 21 | max_iterations: Option, // default: 10 22 | splice_threshold: Option, // default: 45 23 | path_precision: Option, // default: 8 24 | ) -> PyResult<()> { 25 | let input_path = PathBuf::from(image_path); 26 | let output_path = PathBuf::from(out_path); 27 | 28 | let config = construct_config( 29 | colormode, 30 | hierarchical, 31 | mode, 32 | filter_speckle, 33 | color_precision, 34 | layer_difference, 35 | corner_threshold, 36 | length_threshold, 37 | max_iterations, 38 | splice_threshold, 39 | path_precision, 40 | ); 41 | 42 | convert_image_to_svg(&input_path, &output_path, config).unwrap(); 43 | Ok(()) 44 | } 45 | 46 | #[pyfunction] 47 | fn convert_raw_image_to_svg( 48 | img_bytes: Vec, 49 | img_format: Option<&str>, // Format of the image (e.g. 'jpg', 'png'... A full list of supported formats can be found [here](https://docs.rs/image/latest/image/enum.ImageFormat.html)). If not provided, the image format will be guessed based on its contents. 50 | colormode: Option<&str>, // "color" or "binary" 51 | hierarchical: Option<&str>, // "stacked" or "cutout" 52 | mode: Option<&str>, // "polygon", "spline", "none" 53 | filter_speckle: Option, // default: 4 54 | color_precision: Option, // default: 6 55 | layer_difference: Option, // default: 16 56 | corner_threshold: Option, // default: 60 57 | length_threshold: Option, // in [3.5, 10] default: 4.0 58 | max_iterations: Option, // default: 10 59 | splice_threshold: Option, // default: 45 60 | path_precision: Option, // default: 8 61 | ) -> PyResult { 62 | let config = construct_config( 63 | colormode, 64 | hierarchical, 65 | mode, 66 | filter_speckle, 67 | color_precision, 68 | layer_difference, 69 | corner_threshold, 70 | length_threshold, 71 | max_iterations, 72 | splice_threshold, 73 | path_precision, 74 | ); 75 | let mut img_reader = Reader::new(BufReader::new(Cursor::new(img_bytes))); 76 | let img_format = img_format.and_then(|ext_name| ImageFormat::from_extension(ext_name)); 77 | let img = match img_format { 78 | Some(img_format) => { 79 | img_reader.set_format(img_format); 80 | img_reader.decode() 81 | } 82 | None => img_reader 83 | .with_guessed_format() 84 | .map_err(|_| PyException::new_err("Unrecognized image format. "))? 85 | .decode(), 86 | }; 87 | let img = match img { 88 | Ok(img) => img.to_rgba8(), 89 | Err(_) => return Err(PyException::new_err("Failed to decode img_bytes. ")), 90 | }; 91 | let (width, height) = (img.width() as usize, img.height() as usize); 92 | let img = ColorImage { 93 | pixels: img.as_raw().to_vec(), 94 | width, 95 | height, 96 | }; 97 | let svg = 98 | convert(img, config).map_err(|_| PyException::new_err("Failed to convert the image. "))?; 99 | Ok(format!("{}", svg)) 100 | } 101 | 102 | #[pyfunction] 103 | fn convert_pixels_to_svg( 104 | rgba_pixels: Vec<(u8, u8, u8, u8)>, 105 | size: (usize, usize), 106 | colormode: Option<&str>, // "color" or "binary" 107 | hierarchical: Option<&str>, // "stacked" or "cutout" 108 | mode: Option<&str>, // "polygon", "spline", "none" 109 | filter_speckle: Option, // default: 4 110 | color_precision: Option, // default: 6 111 | layer_difference: Option, // default: 16 112 | corner_threshold: Option, // default: 60 113 | length_threshold: Option, // in [3.5, 10] default: 4.0 114 | max_iterations: Option, // default: 10 115 | splice_threshold: Option, // default: 45 116 | path_precision: Option, // default: 8 117 | ) -> PyResult { 118 | let expected_pixel_count = size.0 * size.1; 119 | if rgba_pixels.len() != expected_pixel_count { 120 | return Err(PyException::new_err(format!( 121 | "Length of rgba_pixels does not match given image size. Expected {} ({} * {}), got {}. ", 122 | expected_pixel_count, 123 | size.0, 124 | size.1, 125 | rgba_pixels.len() 126 | ))); 127 | } 128 | let config = construct_config( 129 | colormode, 130 | hierarchical, 131 | mode, 132 | filter_speckle, 133 | color_precision, 134 | layer_difference, 135 | corner_threshold, 136 | length_threshold, 137 | max_iterations, 138 | splice_threshold, 139 | path_precision, 140 | ); 141 | let mut flat_pixels: Vec = vec![]; 142 | for (r, g, b, a) in rgba_pixels { 143 | flat_pixels.push(r); 144 | flat_pixels.push(g); 145 | flat_pixels.push(b); 146 | flat_pixels.push(a); 147 | } 148 | let mut img = ColorImage::new(); 149 | img.pixels = flat_pixels; 150 | (img.width, img.height) = size; 151 | 152 | let svg = 153 | convert(img, config).map_err(|_| PyException::new_err("Failed to convert the image. "))?; 154 | Ok(format!("{}", svg)) 155 | } 156 | 157 | fn construct_config( 158 | colormode: Option<&str>, 159 | hierarchical: Option<&str>, 160 | mode: Option<&str>, 161 | filter_speckle: Option, 162 | color_precision: Option, 163 | layer_difference: Option, 164 | corner_threshold: Option, 165 | length_threshold: Option, 166 | max_iterations: Option, 167 | splice_threshold: Option, 168 | path_precision: Option, 169 | ) -> Config { 170 | // TODO: enforce color mode with an enum so that we only 171 | // accept the strings 'color' or 'binary' 172 | let color_mode = match colormode.unwrap_or("color") { 173 | "color" => ColorMode::Color, 174 | "binary" => ColorMode::Binary, 175 | _ => ColorMode::Color, 176 | }; 177 | 178 | let hierarchical = match hierarchical.unwrap_or("stacked") { 179 | "stacked" => Hierarchical::Stacked, 180 | "cutout" => Hierarchical::Cutout, 181 | _ => Hierarchical::Stacked, 182 | }; 183 | 184 | let mode = match mode.unwrap_or("spline") { 185 | "spline" => PathSimplifyMode::Spline, 186 | "polygon" => PathSimplifyMode::Polygon, 187 | "none" => PathSimplifyMode::None, 188 | _ => PathSimplifyMode::Spline, 189 | }; 190 | 191 | let filter_speckle = filter_speckle.unwrap_or(4); 192 | let color_precision = color_precision.unwrap_or(6); 193 | let layer_difference = layer_difference.unwrap_or(16); 194 | let corner_threshold = corner_threshold.unwrap_or(60); 195 | let length_threshold = length_threshold.unwrap_or(4.0); 196 | let splice_threshold = splice_threshold.unwrap_or(45); 197 | let max_iterations = max_iterations.unwrap_or(10); 198 | 199 | Config { 200 | color_mode, 201 | hierarchical, 202 | filter_speckle, 203 | color_precision, 204 | layer_difference, 205 | mode, 206 | corner_threshold, 207 | length_threshold, 208 | max_iterations, 209 | splice_threshold, 210 | path_precision, 211 | ..Default::default() 212 | } 213 | } 214 | 215 | /// A Python module implemented in Rust. 216 | #[pymodule] 217 | fn vtracer(_py: Python, m: &PyModule) -> PyResult<()> { 218 | m.add_function(wrap_pyfunction!(convert_image_to_svg_py, m)?)?; 219 | m.add_function(wrap_pyfunction!(convert_raw_image_to_svg, m)?)?; 220 | m.add_function(wrap_pyfunction!(convert_pixels_to_svg, m)?)?; 221 | Ok(()) 222 | } 223 | -------------------------------------------------------------------------------- /cmdapp/src/svg.rs: -------------------------------------------------------------------------------- 1 | use std::fmt; 2 | use visioncortex::{Color, CompoundPath, PointF64}; 3 | 4 | #[derive(Debug, Clone)] 5 | pub struct SvgFile { 6 | pub paths: Vec, 7 | pub width: usize, 8 | pub height: usize, 9 | pub path_precision: Option, 10 | } 11 | 12 | #[derive(Debug, Clone)] 13 | pub struct SvgPath { 14 | pub path: CompoundPath, 15 | pub color: Color, 16 | } 17 | 18 | impl SvgFile { 19 | pub fn new(width: usize, height: usize, path_precision: Option) -> Self { 20 | SvgFile { 21 | paths: vec![], 22 | width, 23 | height, 24 | path_precision, 25 | } 26 | } 27 | 28 | pub fn add_path(&mut self, path: CompoundPath, color: Color) { 29 | self.paths.push(SvgPath { path, color }) 30 | } 31 | } 32 | 33 | impl fmt::Display for SvgFile { 34 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 35 | writeln!(f, r#""#)?; 36 | writeln!( 37 | f, 38 | r#""#, 39 | env!("CARGO_PKG_VERSION") 40 | )?; 41 | writeln!( 42 | f, 43 | r#""#, 44 | self.width, self.height 45 | )?; 46 | 47 | for path in &self.paths { 48 | path.fmt_with_precision(f, self.path_precision)?; 49 | } 50 | 51 | writeln!(f, "") 52 | } 53 | } 54 | 55 | impl fmt::Display for SvgPath { 56 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 57 | self.fmt_with_precision(f, None) 58 | } 59 | } 60 | 61 | impl SvgPath { 62 | fn fmt_with_precision(&self, f: &mut fmt::Formatter, precision: Option) -> fmt::Result { 63 | let (string, offset) = self 64 | .path 65 | .to_svg_string(true, PointF64::default(), precision); 66 | writeln!( 67 | f, 68 | "", 69 | string, 70 | self.color.to_hex_string(), 71 | offset.x, 72 | offset.y 73 | ) 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /cmdapp/vtracer/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 | 4 | 5 |

VTracer: Python Binding

6 | 7 |

8 | Raster to Vector Graphics Converter built on top of visioncortex 9 |

10 | 11 |

12 | Article 13 | | 14 | Demo 15 | | 16 | Download 17 |

18 | 19 | Built with 🦀 by The Vision Cortex Research Group 20 | 21 |
22 | 23 | ## Introduction 24 | 25 | visioncortex VTracer is an open source software to convert raster images (like jpg & png) into vector graphics (svg). It can vectorize graphics and photographs and trace the curves to output compact vector files. 26 | 27 | Comparing to [Potrace](http://potrace.sourceforge.net/) which only accept binarized inputs (Black & White pixmap), VTracer has an image processing pipeline which can handle colored high resolution scans. 28 | 29 | Comparing to Adobe Illustrator's [Image Trace](https://helpx.adobe.com/illustrator/using/image-trace.html), VTracer's output is much more compact (less shapes) as we adopt a stacking strategy and avoid producing shapes with holes. 30 | 31 | VTracer is originally designed for processing high resolution scans of historic blueprints up to gigapixels. At the same time, VTracer can also handle low resolution pixel art, simulating `image-rendering: pixelated` for retro game artworks. 32 | 33 | A technical description of the algorithm is on [visioncortex.org/vtracer-docs](//www.visioncortex.org/vtracer-docs). 34 | 35 | ## Install (Python) 36 | 37 | ```shell 38 | pip install vtracer 39 | ``` 40 | 41 | ### Usage (Python) 42 | 43 | ```python 44 | import vtracer 45 | 46 | input_path = "/path/to/some_file.jpg" 47 | output_path = "/path/to/some_file.vtracer.jpg" 48 | 49 | # Minimal example: use all default values, generate a multicolor SVG 50 | vtracer.convert_image_to_svg_py(inp, out) 51 | 52 | # Single-color example. Good for line art, and much faster than full color: 53 | vtracer.convert_image_to_svg_py(inp, out, colormode='binary') 54 | 55 | # Convert from raw image bytes 56 | input_img_bytes: bytes = get_bytes() # e.g. reading bytes from a file or a HTTP request body 57 | svg_str: str = vtracer.convert_raw_image_to_svg(input_img_bytes, img_format='jpg') 58 | 59 | # Convert from RGBA image pixels 60 | from PIL import Image 61 | img = Image.open(input_path).convert('RGBA') 62 | pixels: list[tuple[int, int, int, int]] = list(img.getdata()) 63 | svg_str: str = vtracer.convert_pixels_to_svg(pixels, img.size) 64 | 65 | # All the bells & whistles, also applicable to convert_raw_image_to_svg and convert_pixels_to_svg. 66 | vtracer.convert_image_to_svg_py(inp, 67 | out, 68 | colormode = 'color', # ["color"] or "binary" 69 | hierarchical = 'stacked', # ["stacked"] or "cutout" 70 | mode = 'spline', # ["spline"] "polygon", or "none" 71 | filter_speckle = 4, # default: 4 72 | color_precision = 6, # default: 6 73 | layer_difference = 16, # default: 16 74 | corner_threshold = 60, # default: 60 75 | length_threshold = 4.0, # in [3.5, 10] default: 4.0 76 | max_iterations = 10, # default: 10 77 | splice_threshold = 45, # default: 45 78 | path_precision = 3 # default: 8 79 | ) 80 | 81 | ``` 82 | 83 | ## Rust Library 84 | 85 | The (Rust) library can be found on [crates.io/vtracer](//crates.io/crates/vtracer) and [crates.io/vtracer-webapp](//crates.io/crates/vtracer-webapp). 86 | -------------------------------------------------------------------------------- /cmdapp/vtracer/__init__.py: -------------------------------------------------------------------------------- 1 | from .vtracer import (convert_image_to_svg_py, convert_pixels_to_svg, 2 | convert_raw_image_to_svg) 3 | -------------------------------------------------------------------------------- /cmdapp/vtracer/vtracer.pyi: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | def convert_image_to_svg_py(image_path: str, 4 | out_path: str, 5 | colormode: Optional[str] = None, # ["color"] or "binary" 6 | hierarchical: Optional[str] = None, # ["stacked"] or "cutout" 7 | mode: Optional[str] = None, # ["spline"], "polygon", "none" 8 | filter_speckle: Optional[int] = None, # default: 4 9 | color_precision: Optional[int] = None, # default: 6 10 | layer_difference: Optional[int] = None, # default: 16 11 | corner_threshold: Optional[int] = None, # default: 60 12 | length_threshold: Optional[float] = None, # in [3.5, 10] default: 4.0 13 | max_iterations: Optional[int] = None, # default: 10 14 | splice_threshold: Optional[int] = None, # default: 45 15 | path_precision: Optional[int] = None, # default: 8 16 | ) -> None: 17 | ... 18 | 19 | def convert_raw_image_to_svg(img_bytes: bytes, 20 | img_format: Optional[str] = None, # Format of the image (e.g. 'jpg', 'png'... A full list of supported formats can be found [here](https://docs.rs/image/latest/image/enum.ImageFormat.html)). If not provided, the image format will be guessed based on its contents. 21 | colormode: Optional[str] = None, # ["color"] or "binary" 22 | hierarchical: Optional[str] = None, # ["stacked"] or "cutout" 23 | mode: Optional[str] = None, # ["spline"], "polygon", "none" 24 | filter_speckle: Optional[int] = None, # default: 4 25 | color_precision: Optional[int] = None, # default: 6 26 | layer_difference: Optional[int] = None, # default: 16 27 | corner_threshold: Optional[int] = None, # default: 60 28 | length_threshold: Optional[float] = None, # in [3.5, 10] default: 4.0 29 | max_iterations: Optional[int] = None, # default: 10 30 | splice_threshold: Optional[int] = None, # default: 45 31 | path_precision: Optional[int] = None, # default: 8 32 | ) -> str: 33 | ... 34 | 35 | def convert_pixels_to_svg(rgba_pixels: list[tuple[int, int, int, int]], 36 | size: tuple[int, int], 37 | colormode: Optional[str] = None, # ["color"] or "binary" 38 | hierarchical: Optional[str] = None, # ["stacked"] or "cutout" 39 | mode: Optional[str] = None, # ["spline"], "polygon", "none" 40 | filter_speckle: Optional[int] = None, # default: 4 41 | color_precision: Optional[int] = None, # default: 6 42 | layer_difference: Optional[int] = None, # default: 16 43 | corner_threshold: Optional[int] = None, # default: 60 44 | length_threshold: Optional[float] = None, # in [3.5, 10] default: 4.0 45 | max_iterations: Optional[int] = None, # default: 10 46 | splice_threshold: Optional[int] = None, # default: 45 47 | path_precision: Optional[int] = None, # default: 8 48 | ) -> str: 49 | ... -------------------------------------------------------------------------------- /docs/589cb57662b50620abca.module.wasm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visioncortex/vtracer/efa4351b2c4392584a7856628a13d0dfeb133967/docs/589cb57662b50620abca.module.wasm -------------------------------------------------------------------------------- /docs/COPYRIGHT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2020 Tsang Hao Fung 2 | 3 | The content in the /docs directory is for GitHub pages, and is not covered under open source licenses. 4 | -------------------------------------------------------------------------------- /docs/assets/apple-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visioncortex/vtracer/efa4351b2c4392584a7856628a13d0dfeb133967/docs/assets/apple-icon.png -------------------------------------------------------------------------------- /docs/assets/samples/Cityscape Sunset_DFM3-01.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visioncortex/vtracer/efa4351b2c4392584a7856628a13d0dfeb133967/docs/assets/samples/Cityscape Sunset_DFM3-01.jpg -------------------------------------------------------------------------------- /docs/assets/samples/Gum Tree Vector.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visioncortex/vtracer/efa4351b2c4392584a7856628a13d0dfeb133967/docs/assets/samples/Gum Tree Vector.jpg -------------------------------------------------------------------------------- /docs/assets/samples/K1_drawing.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visioncortex/vtracer/efa4351b2c4392584a7856628a13d0dfeb133967/docs/assets/samples/K1_drawing.jpg -------------------------------------------------------------------------------- /docs/assets/samples/angel-luciano-LATYeZyw88c-unsplash-s.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visioncortex/vtracer/efa4351b2c4392584a7856628a13d0dfeb133967/docs/assets/samples/angel-luciano-LATYeZyw88c-unsplash-s.jpg -------------------------------------------------------------------------------- /docs/assets/samples/angel-luciano-LATYeZyw88c-unsplash.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visioncortex/vtracer/efa4351b2c4392584a7856628a13d0dfeb133967/docs/assets/samples/angel-luciano-LATYeZyw88c-unsplash.jpg -------------------------------------------------------------------------------- /docs/assets/samples/tank-unit-preview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visioncortex/vtracer/efa4351b2c4392584a7856628a13d0dfeb133967/docs/assets/samples/tank-unit-preview.png -------------------------------------------------------------------------------- /docs/assets/samples/vectorstock_31191940.ai: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visioncortex/vtracer/efa4351b2c4392584a7856628a13d0dfeb133967/docs/assets/samples/vectorstock_31191940.ai -------------------------------------------------------------------------------- /docs/assets/samples/vectorstock_31191940.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visioncortex/vtracer/efa4351b2c4392584a7856628a13d0dfeb133967/docs/assets/samples/vectorstock_31191940.png -------------------------------------------------------------------------------- /docs/assets/visioncortex-logo-light.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 25 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 43 | 44 | 47 | 49 | 52 | 55 | 57 | 59 | 62 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /docs/assets/visioncortex-logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 25 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 43 | 44 | 46 | 48 | 51 | 54 | 56 | 58 | 61 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /docs/bootstrap.js: -------------------------------------------------------------------------------- 1 | /******/ (function(modules) { // webpackBootstrap 2 | /******/ // install a JSONP callback for chunk loading 3 | /******/ function webpackJsonpCallback(data) { 4 | /******/ var chunkIds = data[0]; 5 | /******/ var moreModules = data[1]; 6 | /******/ 7 | /******/ 8 | /******/ // add "moreModules" to the modules object, 9 | /******/ // then flag all "chunkIds" as loaded and fire callback 10 | /******/ var moduleId, chunkId, i = 0, resolves = []; 11 | /******/ for(;i < chunkIds.length; i++) { 12 | /******/ chunkId = chunkIds[i]; 13 | /******/ if(Object.prototype.hasOwnProperty.call(installedChunks, chunkId) && installedChunks[chunkId]) { 14 | /******/ resolves.push(installedChunks[chunkId][0]); 15 | /******/ } 16 | /******/ installedChunks[chunkId] = 0; 17 | /******/ } 18 | /******/ for(moduleId in moreModules) { 19 | /******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { 20 | /******/ modules[moduleId] = moreModules[moduleId]; 21 | /******/ } 22 | /******/ } 23 | /******/ if(parentJsonpFunction) parentJsonpFunction(data); 24 | /******/ 25 | /******/ while(resolves.length) { 26 | /******/ resolves.shift()(); 27 | /******/ } 28 | /******/ 29 | /******/ }; 30 | /******/ 31 | /******/ 32 | /******/ // The module cache 33 | /******/ var installedModules = {}; 34 | /******/ 35 | /******/ // object to store loaded and loading chunks 36 | /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched 37 | /******/ // Promise = chunk loading, 0 = chunk loaded 38 | /******/ var installedChunks = { 39 | /******/ "main": 0 40 | /******/ }; 41 | /******/ 42 | /******/ 43 | /******/ 44 | /******/ // script path function 45 | /******/ function jsonpScriptSrc(chunkId) { 46 | /******/ return __webpack_require__.p + "" + chunkId + ".bootstrap.js" 47 | /******/ } 48 | /******/ 49 | /******/ // object to store loaded and loading wasm modules 50 | /******/ var installedWasmModules = {}; 51 | /******/ 52 | /******/ function promiseResolve() { return Promise.resolve(); } 53 | /******/ 54 | /******/ var wasmImportObjects = { 55 | /******/ "../pkg/vtracer_webapp_bg.wasm": function() { 56 | /******/ return { 57 | /******/ "./vtracer_webapp_bg.js": { 58 | /******/ "__wbindgen_object_drop_ref": function(p0i32) { 59 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbindgen_object_drop_ref"](p0i32); 60 | /******/ }, 61 | /******/ "__wbindgen_string_new": function(p0i32,p1i32) { 62 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbindgen_string_new"](p0i32,p1i32); 63 | /******/ }, 64 | /******/ "__wbg_new_59cb74e423758ede": function() { 65 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbg_new_59cb74e423758ede"](); 66 | /******/ }, 67 | /******/ "__wbg_stack_558ba5917b466edd": function(p0i32,p1i32) { 68 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbg_stack_558ba5917b466edd"](p0i32,p1i32); 69 | /******/ }, 70 | /******/ "__wbg_error_4bb6c2a97407129a": function(p0i32,p1i32) { 71 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbg_error_4bb6c2a97407129a"](p0i32,p1i32); 72 | /******/ }, 73 | /******/ "__wbg_instanceof_Window_adf3196bdc02b386": function(p0i32) { 74 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbg_instanceof_Window_adf3196bdc02b386"](p0i32); 75 | /******/ }, 76 | /******/ "__wbg_document_6cc8d0b87c0a99b9": function(p0i32) { 77 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbg_document_6cc8d0b87c0a99b9"](p0i32); 78 | /******/ }, 79 | /******/ "__wbg_createElementNS_ea14cb45a87a0719": function(p0i32,p1i32,p2i32,p3i32,p4i32) { 80 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbg_createElementNS_ea14cb45a87a0719"](p0i32,p1i32,p2i32,p3i32,p4i32); 81 | /******/ }, 82 | /******/ "__wbg_getElementById_0cb6ad9511b1efc0": function(p0i32,p1i32,p2i32) { 83 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbg_getElementById_0cb6ad9511b1efc0"](p0i32,p1i32,p2i32); 84 | /******/ }, 85 | /******/ "__wbg_setAttribute_727bdb9763037624": function(p0i32,p1i32,p2i32,p3i32,p4i32) { 86 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbg_setAttribute_727bdb9763037624"](p0i32,p1i32,p2i32,p3i32,p4i32); 87 | /******/ }, 88 | /******/ "__wbg_prepend_fa995bb42f6e2983": function(p0i32,p1i32) { 89 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbg_prepend_fa995bb42f6e2983"](p0i32,p1i32); 90 | /******/ }, 91 | /******/ "__wbg_debug_d101e002eb92f20b": function(p0i32,p1i32,p2i32,p3i32) { 92 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbg_debug_d101e002eb92f20b"](p0i32,p1i32,p2i32,p3i32); 93 | /******/ }, 94 | /******/ "__wbg_error_cb872335132b1ef7": function(p0i32,p1i32,p2i32,p3i32) { 95 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbg_error_cb872335132b1ef7"](p0i32,p1i32,p2i32,p3i32); 96 | /******/ }, 97 | /******/ "__wbg_info_a25afde0ff8cd04a": function(p0i32,p1i32,p2i32,p3i32) { 98 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbg_info_a25afde0ff8cd04a"](p0i32,p1i32,p2i32,p3i32); 99 | /******/ }, 100 | /******/ "__wbg_log_3bafd82835c6de6d": function(p0i32) { 101 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbg_log_3bafd82835c6de6d"](p0i32); 102 | /******/ }, 103 | /******/ "__wbg_log_64f566ae90a6c43c": function(p0i32,p1i32,p2i32,p3i32) { 104 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbg_log_64f566ae90a6c43c"](p0i32,p1i32,p2i32,p3i32); 105 | /******/ }, 106 | /******/ "__wbg_warn_f632d7d3f55682b6": function(p0i32,p1i32,p2i32,p3i32) { 107 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbg_warn_f632d7d3f55682b6"](p0i32,p1i32,p2i32,p3i32); 108 | /******/ }, 109 | /******/ "__wbg_instanceof_CanvasRenderingContext2d_5b86ec94bce38d5b": function(p0i32) { 110 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbg_instanceof_CanvasRenderingContext2d_5b86ec94bce38d5b"](p0i32); 111 | /******/ }, 112 | /******/ "__wbg_getImageData_888c08c04395524a": function(p0i32,p1f64,p2f64,p3f64,p4f64) { 113 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbg_getImageData_888c08c04395524a"](p0i32,p1f64,p2f64,p3f64,p4f64); 114 | /******/ }, 115 | /******/ "__wbg_instanceof_HtmlCanvasElement_4f5b5ec6cd53ccf3": function(p0i32) { 116 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbg_instanceof_HtmlCanvasElement_4f5b5ec6cd53ccf3"](p0i32); 117 | /******/ }, 118 | /******/ "__wbg_width_a22f9855caa54b53": function(p0i32) { 119 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbg_width_a22f9855caa54b53"](p0i32); 120 | /******/ }, 121 | /******/ "__wbg_height_9a404a6b3c61c7ef": function(p0i32) { 122 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbg_height_9a404a6b3c61c7ef"](p0i32); 123 | /******/ }, 124 | /******/ "__wbg_getContext_37ca0870acb096d9": function(p0i32,p1i32,p2i32) { 125 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbg_getContext_37ca0870acb096d9"](p0i32,p1i32,p2i32); 126 | /******/ }, 127 | /******/ "__wbg_data_c2cd7a48734589b2": function(p0i32,p1i32) { 128 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbg_data_c2cd7a48734589b2"](p0i32,p1i32); 129 | /******/ }, 130 | /******/ "__wbg_call_8e95613cc6524977": function(p0i32,p1i32) { 131 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbg_call_8e95613cc6524977"](p0i32,p1i32); 132 | /******/ }, 133 | /******/ "__wbindgen_object_clone_ref": function(p0i32) { 134 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbindgen_object_clone_ref"](p0i32); 135 | /******/ }, 136 | /******/ "__wbg_newnoargs_f3b8a801d5d4b079": function(p0i32,p1i32) { 137 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbg_newnoargs_f3b8a801d5d4b079"](p0i32,p1i32); 138 | /******/ }, 139 | /******/ "__wbg_self_07b2f89e82ceb76d": function() { 140 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbg_self_07b2f89e82ceb76d"](); 141 | /******/ }, 142 | /******/ "__wbg_window_ba85d88572adc0dc": function() { 143 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbg_window_ba85d88572adc0dc"](); 144 | /******/ }, 145 | /******/ "__wbg_globalThis_b9277fc37e201fe5": function() { 146 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbg_globalThis_b9277fc37e201fe5"](); 147 | /******/ }, 148 | /******/ "__wbg_global_e16303fe83e1d57f": function() { 149 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbg_global_e16303fe83e1d57f"](); 150 | /******/ }, 151 | /******/ "__wbindgen_is_undefined": function(p0i32) { 152 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbindgen_is_undefined"](p0i32); 153 | /******/ }, 154 | /******/ "__wbindgen_debug_string": function(p0i32,p1i32) { 155 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbindgen_debug_string"](p0i32,p1i32); 156 | /******/ }, 157 | /******/ "__wbindgen_throw": function(p0i32,p1i32) { 158 | /******/ return installedModules["../pkg/vtracer_webapp_bg.js"].exports["__wbindgen_throw"](p0i32,p1i32); 159 | /******/ } 160 | /******/ } 161 | /******/ }; 162 | /******/ }, 163 | /******/ }; 164 | /******/ 165 | /******/ // The require function 166 | /******/ function __webpack_require__(moduleId) { 167 | /******/ 168 | /******/ // Check if module is in cache 169 | /******/ if(installedModules[moduleId]) { 170 | /******/ return installedModules[moduleId].exports; 171 | /******/ } 172 | /******/ // Create a new module (and put it into the cache) 173 | /******/ var module = installedModules[moduleId] = { 174 | /******/ i: moduleId, 175 | /******/ l: false, 176 | /******/ exports: {} 177 | /******/ }; 178 | /******/ 179 | /******/ // Execute the module function 180 | /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); 181 | /******/ 182 | /******/ // Flag the module as loaded 183 | /******/ module.l = true; 184 | /******/ 185 | /******/ // Return the exports of the module 186 | /******/ return module.exports; 187 | /******/ } 188 | /******/ 189 | /******/ // This file contains only the entry chunk. 190 | /******/ // The chunk loading function for additional chunks 191 | /******/ __webpack_require__.e = function requireEnsure(chunkId) { 192 | /******/ var promises = []; 193 | /******/ 194 | /******/ 195 | /******/ // JSONP chunk loading for javascript 196 | /******/ 197 | /******/ var installedChunkData = installedChunks[chunkId]; 198 | /******/ if(installedChunkData !== 0) { // 0 means "already installed". 199 | /******/ 200 | /******/ // a Promise means "currently loading". 201 | /******/ if(installedChunkData) { 202 | /******/ promises.push(installedChunkData[2]); 203 | /******/ } else { 204 | /******/ // setup Promise in chunk cache 205 | /******/ var promise = new Promise(function(resolve, reject) { 206 | /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; 207 | /******/ }); 208 | /******/ promises.push(installedChunkData[2] = promise); 209 | /******/ 210 | /******/ // start chunk loading 211 | /******/ var script = document.createElement('script'); 212 | /******/ var onScriptComplete; 213 | /******/ 214 | /******/ script.charset = 'utf-8'; 215 | /******/ script.timeout = 120; 216 | /******/ if (__webpack_require__.nc) { 217 | /******/ script.setAttribute("nonce", __webpack_require__.nc); 218 | /******/ } 219 | /******/ script.src = jsonpScriptSrc(chunkId); 220 | /******/ 221 | /******/ // create error before stack unwound to get useful stacktrace later 222 | /******/ var error = new Error(); 223 | /******/ onScriptComplete = function (event) { 224 | /******/ // avoid mem leaks in IE. 225 | /******/ script.onerror = script.onload = null; 226 | /******/ clearTimeout(timeout); 227 | /******/ var chunk = installedChunks[chunkId]; 228 | /******/ if(chunk !== 0) { 229 | /******/ if(chunk) { 230 | /******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); 231 | /******/ var realSrc = event && event.target && event.target.src; 232 | /******/ error.message = 'Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')'; 233 | /******/ error.name = 'ChunkLoadError'; 234 | /******/ error.type = errorType; 235 | /******/ error.request = realSrc; 236 | /******/ chunk[1](error); 237 | /******/ } 238 | /******/ installedChunks[chunkId] = undefined; 239 | /******/ } 240 | /******/ }; 241 | /******/ var timeout = setTimeout(function(){ 242 | /******/ onScriptComplete({ type: 'timeout', target: script }); 243 | /******/ }, 120000); 244 | /******/ script.onerror = script.onload = onScriptComplete; 245 | /******/ document.head.appendChild(script); 246 | /******/ } 247 | /******/ } 248 | /******/ 249 | /******/ // Fetch + compile chunk loading for webassembly 250 | /******/ 251 | /******/ var wasmModules = {"0":["../pkg/vtracer_webapp_bg.wasm"]}[chunkId] || []; 252 | /******/ 253 | /******/ wasmModules.forEach(function(wasmModuleId) { 254 | /******/ var installedWasmModuleData = installedWasmModules[wasmModuleId]; 255 | /******/ 256 | /******/ // a Promise means "currently loading" or "already loaded". 257 | /******/ if(installedWasmModuleData) 258 | /******/ promises.push(installedWasmModuleData); 259 | /******/ else { 260 | /******/ var importObject = wasmImportObjects[wasmModuleId](); 261 | /******/ var req = fetch(__webpack_require__.p + "" + {"../pkg/vtracer_webapp_bg.wasm":"589cb57662b50620abca"}[wasmModuleId] + ".module.wasm"); 262 | /******/ var promise; 263 | /******/ if(importObject instanceof Promise && typeof WebAssembly.compileStreaming === 'function') { 264 | /******/ promise = Promise.all([WebAssembly.compileStreaming(req), importObject]).then(function(items) { 265 | /******/ return WebAssembly.instantiate(items[0], items[1]); 266 | /******/ }); 267 | /******/ } else if(typeof WebAssembly.instantiateStreaming === 'function') { 268 | /******/ promise = WebAssembly.instantiateStreaming(req, importObject); 269 | /******/ } else { 270 | /******/ var bytesPromise = req.then(function(x) { return x.arrayBuffer(); }); 271 | /******/ promise = bytesPromise.then(function(bytes) { 272 | /******/ return WebAssembly.instantiate(bytes, importObject); 273 | /******/ }); 274 | /******/ } 275 | /******/ promises.push(installedWasmModules[wasmModuleId] = promise.then(function(res) { 276 | /******/ return __webpack_require__.w[wasmModuleId] = (res.instance || res).exports; 277 | /******/ })); 278 | /******/ } 279 | /******/ }); 280 | /******/ return Promise.all(promises); 281 | /******/ }; 282 | /******/ 283 | /******/ // expose the modules object (__webpack_modules__) 284 | /******/ __webpack_require__.m = modules; 285 | /******/ 286 | /******/ // expose the module cache 287 | /******/ __webpack_require__.c = installedModules; 288 | /******/ 289 | /******/ // define getter function for harmony exports 290 | /******/ __webpack_require__.d = function(exports, name, getter) { 291 | /******/ if(!__webpack_require__.o(exports, name)) { 292 | /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); 293 | /******/ } 294 | /******/ }; 295 | /******/ 296 | /******/ // define __esModule on exports 297 | /******/ __webpack_require__.r = function(exports) { 298 | /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { 299 | /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); 300 | /******/ } 301 | /******/ Object.defineProperty(exports, '__esModule', { value: true }); 302 | /******/ }; 303 | /******/ 304 | /******/ // create a fake namespace object 305 | /******/ // mode & 1: value is a module id, require it 306 | /******/ // mode & 2: merge all properties of value into the ns 307 | /******/ // mode & 4: return value when already ns object 308 | /******/ // mode & 8|1: behave like require 309 | /******/ __webpack_require__.t = function(value, mode) { 310 | /******/ if(mode & 1) value = __webpack_require__(value); 311 | /******/ if(mode & 8) return value; 312 | /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; 313 | /******/ var ns = Object.create(null); 314 | /******/ __webpack_require__.r(ns); 315 | /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); 316 | /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); 317 | /******/ return ns; 318 | /******/ }; 319 | /******/ 320 | /******/ // getDefaultExport function for compatibility with non-harmony modules 321 | /******/ __webpack_require__.n = function(module) { 322 | /******/ var getter = module && module.__esModule ? 323 | /******/ function getDefault() { return module['default']; } : 324 | /******/ function getModuleExports() { return module; }; 325 | /******/ __webpack_require__.d(getter, 'a', getter); 326 | /******/ return getter; 327 | /******/ }; 328 | /******/ 329 | /******/ // Object.prototype.hasOwnProperty.call 330 | /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; 331 | /******/ 332 | /******/ // __webpack_public_path__ 333 | /******/ __webpack_require__.p = ""; 334 | /******/ 335 | /******/ // on error function for async loading 336 | /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; 337 | /******/ 338 | /******/ // object with all WebAssembly.instance exports 339 | /******/ __webpack_require__.w = {}; 340 | /******/ 341 | /******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || []; 342 | /******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray); 343 | /******/ jsonpArray.push = webpackJsonpCallback; 344 | /******/ jsonpArray = jsonpArray.slice(); 345 | /******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]); 346 | /******/ var parentJsonpFunction = oldJsonpFunction; 347 | /******/ 348 | /******/ 349 | /******/ // Load entry module and return exports 350 | /******/ return __webpack_require__(__webpack_require__.s = "./bootstrap.js"); 351 | /******/ }) 352 | /************************************************************************/ 353 | /******/ ({ 354 | 355 | /***/ "./bootstrap.js": 356 | /*!**********************!*\ 357 | !*** ./bootstrap.js ***! 358 | \**********************/ 359 | /*! no static exports found */ 360 | /***/ (function(module, exports, __webpack_require__) { 361 | 362 | eval("// A dependency graph that contains any wasm must all be imported\n// asynchronously. This `bootstrap.js` file does the single async import, so\n// that no one else needs to worry about it again.\n__webpack_require__.e(/*! import() */ 0).then(__webpack_require__.bind(null, /*! ./index.js */ \"./index.js\"))\n .catch(e => console.error(\"Error importing `index.js`:\", e));\n\n\n//# sourceURL=webpack:///./bootstrap.js?"); 363 | 364 | /***/ }) 365 | 366 | /******/ }); -------------------------------------------------------------------------------- /docs/images/aliyun-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visioncortex/vtracer/efa4351b2c4392584a7856628a13d0dfeb133967/docs/images/aliyun-logo.png -------------------------------------------------------------------------------- /docs/images/screenshot-01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visioncortex/vtracer/efa4351b2c4392584a7856628a13d0dfeb133967/docs/images/screenshot-01.png -------------------------------------------------------------------------------- /docs/images/screenshot-02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visioncortex/vtracer/efa4351b2c4392584a7856628a13d0dfeb133967/docs/images/screenshot-02.png -------------------------------------------------------------------------------- /docs/images/visioncortex icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visioncortex/vtracer/efa4351b2c4392584a7856628a13d0dfeb133967/docs/images/visioncortex icon.png -------------------------------------------------------------------------------- /docs/images/visioncortex-banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visioncortex/vtracer/efa4351b2c4392584a7856628a13d0dfeb133967/docs/images/visioncortex-banner.png -------------------------------------------------------------------------------- /docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | VTracer 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 21 | 132 | 133 | 134 | 135 | 136 |
137 |
138 |
139 | 140 | 141 |   142 | / VTracer 143 |
144 |
145 | Article 146 |    147 | GitHub 148 |    149 | Download as SVG 150 |
151 |
152 | 155 |
156 |
157 |
158 |
159 |

Drag an image here, Cmd-V to paste or Select file

160 |
161 | 162 | 163 |
164 |
165 | 175 |
176 |
177 | 178 |
179 |   180 |
181 | 182 |

183 | 184 |
185 |
186 | Clustering 187 |
188 |
189 | 190 |
191 |
192 | 193 | 194 |
195 |
196 | 197 |
198 |
199 | 200 | 201 |
202 |
203 | 204 |
205 |
206 | Filter Speckle (Cleaner) 207 |
208 |
209 |
210 | 4 211 |
212 |
213 | 214 |
215 | 216 |
217 |
218 | Color Precision (More accurate) 219 |
220 |
221 |
222 | 6 223 |
224 |
225 | 226 |
227 | 228 |
229 |
230 | Gradient Step (Less layers) 231 |
232 |
233 |
234 | 16 235 |
236 |
237 | 238 |
239 | 240 |
241 |
242 | Curve Fitting 243 |
244 |
245 | 246 |
247 |
248 | 249 | 250 | 251 |
252 |
253 | 254 |
255 |
256 | Corner Threshold (Smoother) 257 |
258 |
259 |
260 | 60 261 |
262 |
263 | 264 |
265 | 266 |
267 |
268 | Segment Length (More coarse) 269 |
270 |
271 |
272 | 4 273 |
274 |
275 | 276 |
277 | 278 |
279 |
280 | Splice Threshold (Less accurate) 281 |
282 |
283 |
284 | 45 285 |
286 |
287 | 288 |
289 | 290 |
291 |
292 |
293 | Path Precision (More digits) 294 |
295 |
296 |
297 | 8 298 |
299 |
300 | 301 |
302 |
303 |
304 |
305 | 306 |
307 |
308 |

Image Credits

309 |
310 |
311 | 312 | 318 | 319 | 320 | 321 | -------------------------------------------------------------------------------- /webapp/.gitignore: -------------------------------------------------------------------------------- 1 | pkg 2 | wasm-pack.log -------------------------------------------------------------------------------- /webapp/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "vtracer-webapp" 3 | version = "0.4.0" 4 | authors = ["Chris Tsang "] 5 | edition = "2021" 6 | description = "A web app to convert images into vector graphics." 7 | license = "MIT OR Apache-2.0" 8 | homepage = "http://www.visioncortex.org/vtracer" 9 | repository = "https://github.com/visioncortex/vtracer/" 10 | categories = ["graphics"] 11 | keywords = ["svg", "computer-graphics"] 12 | 13 | [lib] 14 | crate-type = ["cdylib"] 15 | 16 | [features] 17 | default = ["console_error_panic_hook"] 18 | 19 | [dependencies] 20 | cfg-if = "0.1" 21 | console_log = { version = "0.2", features = ["color"] } 22 | wasm-bindgen = { version = "0.2", features = ["serde-serialize"] } 23 | serde = { version = "1.0", features = ["derive"] } 24 | serde_json = "1.0" 25 | visioncortex = "0.8.1" 26 | 27 | # The `console_error_panic_hook` crate provides better debugging of panics by 28 | # logging them with `console.error`. This is great for development, but requires 29 | # all the `std::fmt` and `std::panicking` infrastructure, so isn't great for 30 | # code size when deploying. 31 | console_error_panic_hook = { version = "0.1", optional = true } 32 | 33 | [dependencies.web-sys] 34 | version = "0.3" 35 | features = [ 36 | "CanvasRenderingContext2d", 37 | "console", 38 | "Document", 39 | "HtmlElement", 40 | "HtmlCanvasElement", 41 | "ImageData", 42 | "Window", 43 | ] 44 | -------------------------------------------------------------------------------- /webapp/LICENSE-APACHE: -------------------------------------------------------------------------------- 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 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 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /webapp/LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2020 Tsang Hao Fung 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /webapp/Readme.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |
4 | 5 | # visioncortex VTracer 6 | 7 | A web app to convert raster images into vector graphics. 8 | 9 | ## Setup 10 | 11 | 0. `sudo apt install git build-essential` 12 | 1. https://www.rust-lang.org/tools/install 13 | 2. https://rustwasm.github.io/wasm-pack/installer/ 14 | 3. https://github.com/nvm-sh/nvm 15 | ``` 16 | nvm install --lts 17 | ``` 18 | 19 | ## Getting Started 20 | 21 | 0. Setup 22 | ``` 23 | cd app 24 | npm install 25 | ``` 26 | 27 | 1. Build wasm 28 | ``` 29 | wasm-pack build 30 | ``` 31 | 32 | 2. Start development server 33 | ``` 34 | cd app 35 | npm run start 36 | ``` 37 | Open browser on http://localhost:8080/ 38 | 39 | 3. Release 40 | ``` 41 | npm run build 42 | ``` -------------------------------------------------------------------------------- /webapp/app/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist -------------------------------------------------------------------------------- /webapp/app/bootstrap.js: -------------------------------------------------------------------------------- 1 | // A dependency graph that contains any wasm must all be imported 2 | // asynchronously. This `bootstrap.js` file does the single async import, so 3 | // that no one else needs to worry about it again. 4 | import("./index.js") 5 | .catch(e => console.error("Error importing `index.js`:", e)); 6 | -------------------------------------------------------------------------------- /webapp/app/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | VTracer 6 | 7 | 8 | 54 | 55 | 56 | 57 | 58 |
59 | 62 |
63 |
64 |
65 |
66 |

Drag an image here or Select file

67 |
68 | 69 | 70 |
71 |
72 |
73 |
74 |
75 | Download as SVG 76 |
77 | 78 |

79 | 80 |
81 |
82 | Clustering 83 |
84 |
85 | 86 |
87 |
88 | 89 | 90 |
91 |
92 | 93 |
94 |
95 | 96 | 97 |
98 |
99 | 100 |
101 |
102 | Filter Speckle (Cleaner) 103 |
104 |
105 |
106 | 4 107 |
108 |
109 | 110 |
111 | 112 |
113 |
114 | Color Precision (More accurate) 115 |
116 |
117 |
118 | 6 119 |
120 |
121 | 122 |
123 | 124 |
125 |
126 | Gradient Step (Less layers) 127 |
128 |
129 |
130 | 16 131 |
132 |
133 | 134 |
135 | 136 |

137 | 138 |
139 |
140 | Curve Fitting 141 |
142 |
143 | 144 |
145 |
146 | 147 | 148 | 149 |
150 |
151 | 152 |
153 |
154 | Corner Threshold (Smoother) 155 |
156 |
157 |
158 | 60 159 |
160 |
161 | 162 |
163 | 164 |
165 |
166 | Segment Length (More coarse) 167 |
168 |
169 |
170 | 4 171 |
172 |
173 | 174 |
175 | 176 |
177 |
178 | Splice Threshold (More accurate) 179 |
180 |
181 |
182 | 45 183 |
184 |
185 | 186 |
187 | 188 |
189 |
190 |
191 | Path Precision (More digits) 192 |
193 |
194 |
195 | 8 196 |
197 |
198 | 199 |
200 |
201 |
202 |
203 | 204 | 205 | 206 | -------------------------------------------------------------------------------- /webapp/app/index.js: -------------------------------------------------------------------------------- 1 | import { BinaryImageConverter, ColorImageConverter } from 'vtracer'; 2 | 3 | let runner; 4 | const canvas = document.getElementById('frame'); 5 | const ctx = canvas.getContext('2d'); 6 | const svg = document.getElementById('svg'); 7 | const img = new Image(); 8 | const progress = document.getElementById('progressbar'); 9 | const progressregion = document.getElementById('progressregion'); 10 | let mode = 'spline', clustering_mode = 'color', clustering_hierarchical = 'stacked'; 11 | 12 | // Hide canas and svg on load 13 | canvas.style.display = 'none'; 14 | svg.style.display = 'none'; 15 | 16 | // Paste from clipboard 17 | document.addEventListener('paste', function (e) { 18 | if (e.clipboardData) { 19 | var items = e.clipboardData.items; 20 | if (!items) return; 21 | 22 | //access data directly 23 | for (var i = 0; i < items.length; i++) { 24 | if (items[i].type.indexOf("image") !== -1) { 25 | //image 26 | var blob = items[i].getAsFile(); 27 | var URLObj = window.URL || window.webkitURL; 28 | var source = URLObj.createObjectURL(blob); 29 | setSourceAndRestart(source); 30 | } 31 | } 32 | e.preventDefault(); 33 | } 34 | }); 35 | 36 | // Download as SVG 37 | document.getElementById('export').addEventListener('click', function (e) { 38 | const blob = new Blob([ 39 | `\n`, 40 | `\n`, 41 | new XMLSerializer().serializeToString(svg) 42 | ], {type: 'octet/stream'}), 43 | url = window.URL.createObjectURL(blob); 44 | 45 | this.href = url; 46 | this.target = '_blank'; 47 | 48 | this.download = 'export-' + new Date().toISOString().slice(0, 19).replace(/:/g, '').replace('T', ' ') + '.svg'; 49 | }); 50 | 51 | // Store template config 52 | var presetConfigs = [ 53 | { 54 | src: 'assets/samples/K1_drawing.jpg', 55 | clustering_mode: 'binary', 56 | clustering_hierarchical: 'stacked', 57 | filter_speckle: 4, 58 | color_precision: 6, 59 | path_precision: 8, 60 | layer_difference: 16, 61 | mode: 'spline', 62 | corner_threshold: 60, 63 | length_threshold: 4, 64 | splice_threshold: 45, 65 | source: 'https://commons.wikimedia.org/wiki/File:K1_drawing.jpg', 66 | credit: 'Wikimedia', 67 | }, 68 | { 69 | src: 'assets/samples/Cityscape Sunset_DFM3-01.jpg', 70 | clustering_mode: 'color', 71 | clustering_hierarchical: 'stacked', 72 | filter_speckle: 4, 73 | color_precision: 8, 74 | path_precision: 8, 75 | layer_difference: 25, 76 | mode: 'spline', 77 | corner_threshold: 60, 78 | length_threshold: 4, 79 | splice_threshold: 45, 80 | source: 'https://www.vecteezy.com/vector-art/227400-beautiful-cityscape-at-sunset', 81 | credit: 'Building Vectors by Vecteezy', 82 | }, 83 | { 84 | src: 'assets/samples/Gum Tree Vector.jpg', 85 | clustering_mode: 'color', 86 | clustering_hierarchical: 'stacked', 87 | filter_speckle: 4, 88 | color_precision: 8, 89 | path_precision: 8, 90 | layer_difference: 28, 91 | mode: 'spline', 92 | corner_threshold: 60, 93 | length_threshold: 4, 94 | splice_threshold: 45, 95 | source: 'https://www.vecteezy.com/vector-art/172177-gum-tree-vector', 96 | credit: 'Nature Vectors by Vecteezy', 97 | }, 98 | { 99 | src: 'assets/samples/vectorstock_31191940.png', 100 | clustering_mode: 'color', 101 | clustering_hierarchical: 'stacked', 102 | filter_speckle: 8, 103 | color_precision: 7, 104 | path_precision: 8, 105 | layer_difference: 64, 106 | mode: 'spline', 107 | corner_threshold: 60, 108 | length_threshold: 4, 109 | splice_threshold: 45, 110 | source: 'https://www.vectorstock.com/royalty-free-vector/dessert-poster-design-with-chocolate-cake-mousses-vector-31191940', 111 | credit: 'Vector image by VectorStock / vectorstock', 112 | }, 113 | { 114 | src: 'assets/samples/angel-luciano-LATYeZyw88c-unsplash-s.jpg', 115 | clustering_mode: 'color', 116 | clustering_hierarchical: 'stacked', 117 | filter_speckle: 10, 118 | color_precision: 8, 119 | path_precision: 8, 120 | layer_difference: 48, 121 | mode: 'spline', 122 | corner_threshold: 180, 123 | length_threshold: 4, 124 | splice_threshold: 45, 125 | source: 'https://unsplash.com/photos/LATYeZyw88c', 126 | credit: 'Photo by Angel Luciano on Unsplash', 127 | }, 128 | { 129 | src: 'assets/samples/tank-unit-preview.png', 130 | clustering_mode: 'color', 131 | clustering_hierarchical: 'stacked', 132 | filter_speckle: 0, 133 | color_precision: 8, 134 | path_precision: 8, 135 | layer_difference: 0, 136 | mode: 'none', 137 | corner_threshold: 180, 138 | length_threshold: 4, 139 | splice_threshold: 45, 140 | source: 'https://opengameart.org/content/sideview-sci-fi-patreon-collection', 141 | credit: 'Artwork by Luis Zuno on opengameart.org', 142 | }, 143 | ]; 144 | 145 | // Insert gallery items dynamically 146 | if (document.getElementById('galleryslider')) { 147 | for (let i = 0; i < presetConfigs.length; i++) { 148 | document.getElementById('galleryslider').innerHTML += 149 | `
  • 150 |
    151 | 152 | 153 | 154 |
    155 |
  • `; 156 | document.getElementById('credits-modal-content').innerHTML += 157 | `

    ${presetConfigs[i].credit}

    `; 158 | } 159 | } 160 | 161 | // Function to load a given config WITHOUT restarting 162 | function loadConfig(config) { 163 | mode = config.mode; 164 | clustering_mode = config.clustering_mode; 165 | clustering_hierarchical = config.clustering_hierarchical; 166 | 167 | globalcorner = config.corner_threshold; 168 | document.getElementById('cornervalue').innerHTML = globalcorner; 169 | document.getElementById('corner').value = globalcorner; 170 | 171 | globallength = config.length_threshold; 172 | document.getElementById('lengthvalue').innerHTML = globallength; 173 | document.getElementById('length').value = globallength; 174 | 175 | globalsplice = config.splice_threshold; 176 | document.getElementById('splicevalue').innerHTML = globalsplice; 177 | document.getElementById('splice').value = globalsplice; 178 | 179 | globalfilterspeckle = config.filter_speckle; 180 | document.getElementById('filterspecklevalue').innerHTML = globalfilterspeckle; 181 | document.getElementById('filterspeckle').value = globalfilterspeckle; 182 | 183 | globalcolorprecision = config.color_precision; 184 | document.getElementById('colorprecisionvalue').innerHTML = globalcolorprecision; 185 | document.getElementById('colorprecision').value = globalcolorprecision; 186 | 187 | globallayerdifference = config.layer_difference; 188 | document.getElementById('layerdifferencevalue').innerHTML = globallayerdifference; 189 | document.getElementById('layerdifference').value = globallayerdifference; 190 | 191 | globalpathprecision = config.path_precision; 192 | document.getElementById('pathprecisionvalue').innerHTML = globalpathprecision; 193 | document.getElementById('pathprecision').value = globalpathprecision; 194 | } 195 | 196 | // Choose template from gallery 197 | let chooseGalleryButtons = document.querySelectorAll('.galleryitem a'); 198 | chooseGalleryButtons.forEach(item => { 199 | item.addEventListener('click', function (e) { 200 | // Load preset template config 201 | let i = Array.prototype.indexOf.call(chooseGalleryButtons, item); 202 | if (presetConfigs.length > i) { 203 | loadConfig(presetConfigs[i]); 204 | } 205 | 206 | // Set source as specified 207 | setSourceAndRestart(this.firstElementChild.src); 208 | }); 209 | }); 210 | 211 | // Upload button 212 | var imageSelect = document.getElementById('imageSelect'), 213 | imageInput = document.getElementById('imageInput'); 214 | imageSelect.addEventListener('click', function (e) { 215 | imageInput.click(); 216 | e.preventDefault(); 217 | }); 218 | 219 | imageInput.addEventListener('change', function (e) { 220 | setSourceAndRestart(this.files[0]); 221 | }); 222 | 223 | // Drag-n-Drop 224 | var drop = document.getElementById('drop'); 225 | var droptext = document.getElementById('droptext'); 226 | drop.addEventListener('dragenter', function (e) { 227 | if (e.preventDefault) e.preventDefault(); 228 | e.dataTransfer.dropEffect = 'copy'; 229 | droptext.classList.add('hovering'); 230 | return false; 231 | }); 232 | 233 | drop.addEventListener('dragleave', function (e) { 234 | if (e.preventDefault) e.preventDefault(); 235 | e.dataTransfer.dropEffect = 'copy'; 236 | droptext.classList.remove('hovering'); 237 | return false; 238 | }); 239 | 240 | drop.addEventListener('dragover', function (e) { 241 | if (e.preventDefault) e.preventDefault(); 242 | e.dataTransfer.dropEffect = 'copy'; 243 | droptext.classList.add('hovering'); 244 | return false; 245 | }); 246 | 247 | drop.addEventListener('drop', function (e) { 248 | if (e.preventDefault) e.preventDefault(); 249 | droptext.classList.remove('hovering'); 250 | setSourceAndRestart(e.dataTransfer.files[0]); 251 | return false; 252 | }); 253 | 254 | // Get Input from UI controls 255 | var globalcorner = parseInt(document.getElementById('corner').value), 256 | globallength = parseFloat(document.getElementById('length').value), 257 | globalsplice = parseInt(document.getElementById('splice').value), 258 | globalfilterspeckle = parseInt(document.getElementById('filterspeckle').value), 259 | globalcolorprecision = parseInt(document.getElementById('colorprecision').value), 260 | globallayerdifference = parseInt(document.getElementById('layerdifference').value), 261 | globalpathprecision = parseInt(document.getElementById('pathprecision').value); 262 | 263 | // Load past inputs from localStorage 264 | /* 265 | if (localStorage.VSsettings) { 266 | var settings = JSON.parse(localStorage.VSsettings); 267 | document.getElementById('cornervalue').innerHTML = document.getElementById('corner').value = globalcorner = settings.globalcorner; 268 | document.getElementById('lengthvalue').innerHTML = document.getElementById('length').value = globallength = settings.globallength; 269 | document.getElementById('splicevalue').innerHTML = document.getElementById('splice').value = globalsplice = settings.globalsplice; 270 | } 271 | */ 272 | 273 | document.getElementById('none').addEventListener('click', function (e) { 274 | mode = 'none'; 275 | restart(); 276 | }, false); 277 | 278 | document.getElementById('polygon').addEventListener('click', function (e) { 279 | mode = 'polygon'; 280 | restart(); 281 | }, false); 282 | 283 | document.getElementById('spline').addEventListener('click', function (e) { 284 | mode = 'spline'; 285 | restart(); 286 | }, false); 287 | 288 | document.getElementById('clustering-binary').addEventListener('click', function (e) { 289 | clustering_mode = 'binary'; 290 | restart(); 291 | }, false); 292 | 293 | document.getElementById('clustering-color').addEventListener('click', function (e) { 294 | clustering_mode = 'color'; 295 | restart(); 296 | }, false); 297 | 298 | document.getElementById('clustering-cutout').addEventListener('click', function (e) { 299 | clustering_hierarchical = 'cutout'; 300 | restart(); 301 | }, false); 302 | 303 | document.getElementById('clustering-stacked').addEventListener('click', function (e) { 304 | clustering_hierarchical = 'stacked'; 305 | restart(); 306 | }, false); 307 | 308 | document.getElementById('filterspeckle').addEventListener('change', function (e) { 309 | globalfilterspeckle = parseInt(this.value); 310 | document.getElementById('filterspecklevalue').innerHTML = this.value; 311 | restart(); 312 | }); 313 | 314 | document.getElementById('colorprecision').addEventListener('change', function (e) { 315 | globalcolorprecision = parseInt(this.value); 316 | document.getElementById('colorprecisionvalue').innerHTML = this.value; 317 | restart(); 318 | }); 319 | 320 | document.getElementById('layerdifference').addEventListener('change', function (e) { 321 | globallayerdifference = parseInt(this.value); 322 | document.getElementById('layerdifferencevalue').innerHTML = this.value; 323 | restart(); 324 | }); 325 | 326 | document.getElementById('corner').addEventListener('change', function (e) { 327 | globalcorner = parseInt(this.value); 328 | document.getElementById('cornervalue').innerHTML = this.value; 329 | restart(); 330 | }); 331 | 332 | document.getElementById('length').addEventListener('change', function (e) { 333 | globallength = parseFloat(this.value); 334 | document.getElementById('lengthvalue').innerHTML = this.value; 335 | restart(); 336 | }); 337 | 338 | document.getElementById('splice').addEventListener('change', function (e) { 339 | globalsplice = parseInt(this.value); 340 | document.getElementById('splicevalue').innerHTML = this.value; 341 | restart(); 342 | }); 343 | 344 | document.getElementById('pathprecision').addEventListener('change', function (e) { 345 | globalpathprecision = parseInt(this.value); 346 | document.getElementById('pathprecisionvalue').innerHTML = this.value; 347 | restart(); 348 | }); 349 | 350 | // Save inputs before unloading 351 | /* 352 | window.addEventListener('beforeunload', function () { 353 | localStorage.VSsettings = JSON.stringify({ 354 | globalcorner: globalcorner, 355 | globallength: globallength, 356 | globalsplice: globalsplice, 357 | }); 358 | }); 359 | */ 360 | 361 | function setSourceAndRestart(source) { 362 | img.src = source instanceof File ? URL.createObjectURL(source) : source; 363 | img.onload = function () { 364 | const width = img.naturalWidth, height = img.naturalHeight; 365 | svg.setAttribute('viewBox', `0 0 ${width} ${height}`); 366 | canvas.width = img.naturalWidth; 367 | canvas.height = img.naturalHeight; 368 | if (height > width) { 369 | document.getElementById('canvas-container').style.width = '50%'; 370 | document.getElementById('canvas-container').style.marginBottom = (height / width * 50) + '%'; 371 | } else { 372 | document.getElementById('canvas-container').style.width = ''; 373 | document.getElementById('canvas-container').style.marginBottom = (height / width * 100) + '%'; 374 | } 375 | ctx.drawImage(img, 0, 0, canvas.width, canvas.height); 376 | ctx.getImageData(0, 0, canvas.width, canvas.height); 377 | restart(); 378 | } 379 | // Show display 380 | canvas.style.display = 'block'; 381 | svg.style.display = 'block'; 382 | // Hide upload text 383 | droptext.style.display = 'none'; 384 | } 385 | 386 | function restart() { 387 | document.getElementById('clustering-binary').classList.remove('selected'); 388 | document.getElementById('clustering-color').classList.remove('selected'); 389 | document.getElementById('clustering-' + clustering_mode).classList.add('selected'); 390 | Array.from(document.getElementsByClassName('clustering-color-options')).forEach((el) => { 391 | el.style.display = clustering_mode == 'color' ? '' : 'none'; 392 | }); 393 | 394 | document.getElementById('clustering-cutout').classList.remove('selected'); 395 | document.getElementById('clustering-stacked').classList.remove('selected'); 396 | document.getElementById('clustering-' + clustering_hierarchical).classList.add('selected'); 397 | 398 | document.getElementById('none').classList.remove('selected'); 399 | document.getElementById('polygon').classList.remove('selected'); 400 | document.getElementById('spline').classList.remove('selected'); 401 | document.getElementById(mode).classList.add('selected'); 402 | Array.from(document.getElementsByClassName('spline-options')).forEach((el) => { 403 | el.style.display = mode == 'spline' ? '' : 'none'; 404 | }); 405 | 406 | if (!img.src) { 407 | return; 408 | } 409 | while (svg.firstChild) { 410 | svg.removeChild(svg.firstChild); 411 | } 412 | ctx.clearRect(0, 0, canvas.width, canvas.height); 413 | ctx.drawImage(img, 0, 0); 414 | let converter_params = JSON.stringify({ 415 | 'canvas_id': canvas.id, 416 | 'svg_id': svg.id, 417 | 'mode': mode, 418 | 'clustering_mode': clustering_mode, 419 | 'hierarchical': clustering_hierarchical, 420 | 'corner_threshold': deg2rad(globalcorner), 421 | 'length_threshold': globallength, 422 | 'max_iterations': 10, 423 | 'splice_threshold': deg2rad(globalsplice), 424 | 'filter_speckle': globalfilterspeckle*globalfilterspeckle, 425 | 'color_precision': 8-globalcolorprecision, 426 | 'layer_difference': globallayerdifference, 427 | 'path_precision': globalpathprecision, 428 | }); 429 | if (runner) { 430 | runner.stop(); 431 | } 432 | runner = new ConverterRunner(converter_params); 433 | progress.value = 0; 434 | progressregion.style.display = 'block'; 435 | runner.run(); 436 | } 437 | 438 | function deg2rad(deg) { 439 | return deg/180*3.141592654; 440 | } 441 | 442 | class ConverterRunner { 443 | constructor (converter_params) { 444 | this.converter = 445 | clustering_mode == 'color' ? 446 | ColorImageConverter.new_with_string(converter_params): 447 | BinaryImageConverter.new_with_string(converter_params); 448 | this.converter.init(); 449 | this.stopped = false; 450 | if (clustering_mode == 'binary') { 451 | svg.style.background = '#fff'; 452 | canvas.style.display = 'none'; 453 | } else { 454 | svg.style.background = ''; 455 | canvas.style.display = ''; 456 | } 457 | canvas.style.opacity = ''; 458 | } 459 | 460 | run () { 461 | const This = this; 462 | setTimeout(function tick () { 463 | if (!This.stopped) { 464 | let done = false; 465 | const startTick = performance.now(); 466 | while (!(done = This.converter.tick()) && 467 | performance.now() - startTick < 25) { 468 | } 469 | progress.value = This.converter.progress(); 470 | if (progress.value >= 50) { 471 | canvas.style.display = 'none'; 472 | } else { 473 | canvas.style.opacity = (50 - progress.value) / 25; 474 | } 475 | if (progress.value >= progress.max) { 476 | progressregion.style.display = 'none'; 477 | progress.value = 0; 478 | } 479 | if (!done) { 480 | setTimeout(tick, 1); 481 | } 482 | } 483 | }, 1); 484 | } 485 | 486 | stop () { 487 | this.stopped = true; 488 | this.converter.free(); 489 | } 490 | } -------------------------------------------------------------------------------- /webapp/app/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "vtracer-app", 3 | "version": "0.1.0", 4 | "description": "VTracer Webapp", 5 | "author": "Chris Tsang ", 6 | "license": "proprietary", 7 | "private": true, 8 | "main": "index.js", 9 | "scripts": { 10 | "start": "webpack-dev-server", 11 | "build": "webpack" 12 | }, 13 | "keywords": [ 14 | "rust", 15 | "wasm" 16 | ], 17 | "dependencies": { 18 | "vtracer": "file:../pkg", 19 | "webpack": "^4.41.5" 20 | }, 21 | "devDependencies": { 22 | "webpack-cli": "^3.3.11", 23 | "webpack-dev-server": "^3.10.1" 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /webapp/app/webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | 3 | module.exports = { 4 | entry: "./bootstrap.js", 5 | output: { 6 | path: path.resolve(__dirname, "dist"), 7 | filename: "bootstrap.js", 8 | }, 9 | mode: "development", 10 | devServer: { 11 | //host: "0.0.0.0", 12 | port: 8080, 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /webapp/src/canvas.rs: -------------------------------------------------------------------------------- 1 | use wasm_bindgen::{JsCast}; 2 | use web_sys::{console, CanvasRenderingContext2d, HtmlCanvasElement}; 3 | use visioncortex::{ColorImage}; 4 | 5 | use super::common::document; 6 | 7 | pub struct Canvas { 8 | html_canvas: HtmlCanvasElement, 9 | cctx: CanvasRenderingContext2d, 10 | } 11 | 12 | impl Canvas { 13 | pub fn new_from_id(canvas_id: &str) -> Canvas { 14 | let html_canvas = document().get_element_by_id(canvas_id).unwrap(); 15 | let html_canvas: HtmlCanvasElement = html_canvas 16 | .dyn_into::() 17 | .map_err(|_| ()) 18 | .unwrap(); 19 | 20 | let cctx = html_canvas 21 | .get_context("2d") 22 | .unwrap() 23 | .unwrap() 24 | .dyn_into::() 25 | .unwrap(); 26 | 27 | Canvas { 28 | html_canvas, 29 | cctx, 30 | } 31 | } 32 | 33 | pub fn width(&self) -> usize { 34 | self.html_canvas.width() as usize 35 | } 36 | 37 | pub fn height(&self) -> usize { 38 | self.html_canvas.height() as usize 39 | } 40 | 41 | pub fn get_image_data(&self, x: u32, y: u32, width: u32, height: u32) -> Vec { 42 | let image = self 43 | .cctx 44 | .get_image_data(x as f64, y as f64, width as f64, height as f64) 45 | .unwrap(); 46 | image.data().to_vec() 47 | } 48 | 49 | pub fn get_image_data_as_color_image(&self, x: u32, y: u32, width: u32, height: u32) -> ColorImage { 50 | ColorImage { 51 | pixels: self.get_image_data(x, y, width, height), 52 | width: width as usize, 53 | height: height as usize, 54 | } 55 | } 56 | 57 | pub fn log(&self, string: &str) { 58 | console::log_1(&wasm_bindgen::JsValue::from_str(string)); 59 | } 60 | } -------------------------------------------------------------------------------- /webapp/src/common.rs: -------------------------------------------------------------------------------- 1 | pub fn window() -> web_sys::Window { 2 | web_sys::window().unwrap() 3 | } 4 | 5 | pub fn document() -> web_sys::Document { 6 | window().document().unwrap() 7 | } -------------------------------------------------------------------------------- /webapp/src/conversion/binary_image.rs: -------------------------------------------------------------------------------- 1 | use wasm_bindgen::prelude::*; 2 | use visioncortex::{clusters::Clusters, Color, ColorName, PathSimplifyMode}; 3 | 4 | use crate::{canvas::*}; 5 | use crate::svg::*; 6 | 7 | use serde::Deserialize; 8 | use super::util; 9 | 10 | #[derive(Debug, Deserialize)] 11 | pub struct BinaryImageConverterParams { 12 | pub canvas_id: String, 13 | pub svg_id: String, 14 | pub mode: String, 15 | pub corner_threshold: f64, 16 | pub length_threshold: f64, 17 | pub max_iterations: usize, 18 | pub splice_threshold: f64, 19 | pub filter_speckle: usize, 20 | pub path_precision: u32, 21 | } 22 | 23 | #[wasm_bindgen] 24 | pub struct BinaryImageConverter { 25 | canvas: Canvas, 26 | svg: Svg, 27 | clusters: Clusters, 28 | counter: usize, 29 | mode: PathSimplifyMode, 30 | params: BinaryImageConverterParams, 31 | } 32 | 33 | impl BinaryImageConverter { 34 | pub fn new(params: BinaryImageConverterParams) -> Self { 35 | let canvas = Canvas::new_from_id(¶ms.canvas_id); 36 | let svg = Svg::new_from_id(¶ms.svg_id); 37 | Self { 38 | canvas, 39 | svg, 40 | clusters: Clusters::default(), 41 | counter: 0, 42 | mode: util::path_simplify_mode(¶ms.mode), 43 | params, 44 | } 45 | } 46 | } 47 | 48 | #[wasm_bindgen] 49 | impl BinaryImageConverter { 50 | pub fn new_with_string(params: String) -> Self { 51 | let params: BinaryImageConverterParams = serde_json::from_str(params.as_str()).unwrap(); 52 | Self::new(params) 53 | } 54 | 55 | pub fn init(&mut self) { 56 | let width = self.canvas.width() as u32; 57 | let height = self.canvas.height() as u32; 58 | let image = self.canvas.get_image_data_as_color_image(0, 0, width, height); 59 | let binary_image = image.to_binary_image(|x| x.r < 128); 60 | self.clusters = binary_image.to_clusters(false); 61 | self.canvas.log(&format!( 62 | "clusters.len() = {}, self.clusters.rect.left = {}", 63 | self.clusters.len(), 64 | self.clusters.rect.left 65 | )); 66 | } 67 | 68 | pub fn tick(&mut self) -> bool { 69 | if self.counter < self.clusters.len() { 70 | self.canvas.log(&format!("tick {}", self.counter)); 71 | let cluster = self.clusters.get_cluster(self.counter); 72 | if cluster.size() >= self.params.filter_speckle { 73 | let paths = cluster.to_compound_path( 74 | self.mode, 75 | self.params.corner_threshold, 76 | self.params.length_threshold, 77 | self.params.max_iterations, 78 | self.params.splice_threshold 79 | ); 80 | let color = Color::color(&ColorName::Black); 81 | self.svg.prepend_path( 82 | &paths, 83 | &color, 84 | Some(self.params.path_precision), 85 | ); 86 | } 87 | self.counter += 1; 88 | false 89 | } else { 90 | self.canvas.log("done"); 91 | true 92 | } 93 | } 94 | 95 | pub fn progress(&self) -> u32 { 96 | 100 * self.counter as u32 / self.clusters.len() as u32 97 | } 98 | } -------------------------------------------------------------------------------- /webapp/src/conversion/color_image.rs: -------------------------------------------------------------------------------- 1 | use wasm_bindgen::prelude::*; 2 | use visioncortex::{Color, ColorImage, PathSimplifyMode}; 3 | use visioncortex::color_clusters::{Clusters, Runner, RunnerConfig, HIERARCHICAL_MAX, IncrementalBuilder, KeyingAction}; 4 | 5 | use crate::canvas::*; 6 | use crate::svg::*; 7 | 8 | use serde::Deserialize; 9 | use super::util; 10 | 11 | const KEYING_THRESHOLD: f32 = 0.2; 12 | 13 | #[derive(Debug, Deserialize)] 14 | pub struct ColorImageConverterParams { 15 | pub canvas_id: String, 16 | pub svg_id: String, 17 | pub mode: String, 18 | pub hierarchical: String, 19 | pub corner_threshold: f64, 20 | pub length_threshold: f64, 21 | pub max_iterations: usize, 22 | pub splice_threshold: f64, 23 | pub filter_speckle: usize, 24 | pub color_precision: i32, 25 | pub layer_difference: i32, 26 | pub path_precision: u32, 27 | } 28 | 29 | #[wasm_bindgen] 30 | pub struct ColorImageConverter { 31 | canvas: Canvas, 32 | svg: Svg, 33 | stage: Stage, 34 | counter: usize, 35 | mode: PathSimplifyMode, 36 | params: ColorImageConverterParams, 37 | } 38 | 39 | pub enum Stage { 40 | New, 41 | Clustering(IncrementalBuilder), 42 | Reclustering(IncrementalBuilder), 43 | Vectorize(Clusters), 44 | } 45 | 46 | impl ColorImageConverter { 47 | pub fn new(params: ColorImageConverterParams) -> Self { 48 | let canvas = Canvas::new_from_id(¶ms.canvas_id); 49 | let svg = Svg::new_from_id(¶ms.svg_id); 50 | Self { 51 | canvas, 52 | svg, 53 | stage: Stage::New, 54 | counter: 0, 55 | mode: util::path_simplify_mode(¶ms.mode), 56 | params, 57 | } 58 | } 59 | } 60 | 61 | #[wasm_bindgen] 62 | impl ColorImageConverter { 63 | 64 | pub fn new_with_string(params: String) -> Self { 65 | let params: ColorImageConverterParams = serde_json::from_str(params.as_str()).unwrap(); 66 | Self::new(params) 67 | } 68 | 69 | pub fn init(&mut self) { 70 | let width = self.canvas.width() as u32; 71 | let height = self.canvas.height() as u32; 72 | let mut image = self.canvas.get_image_data_as_color_image(0, 0, width, height); 73 | 74 | let key_color = if Self::should_key_image(&image) { 75 | if let Ok(key_color) = Self::find_unused_color_in_image(&image) { 76 | for y in 0..height as usize { 77 | for x in 0..width as usize { 78 | if image.get_pixel(x, y).a == 0 { 79 | image.set_pixel(x, y, &key_color); 80 | } 81 | } 82 | } 83 | key_color 84 | } else { 85 | Color::default() 86 | } 87 | } else { 88 | // The default color is all zeroes, which is treated by visioncortex as a special value meaning no keying will be applied. 89 | Color::default() 90 | }; 91 | 92 | let runner = Runner::new(RunnerConfig { 93 | diagonal: self.params.layer_difference == 0, 94 | hierarchical: HIERARCHICAL_MAX, 95 | batch_size: 25600, 96 | good_min_area: self.params.filter_speckle, 97 | good_max_area: (width * height) as usize, 98 | is_same_color_a: self.params.color_precision, 99 | is_same_color_b: 1, 100 | deepen_diff: self.params.layer_difference, 101 | hollow_neighbours: 1, 102 | key_color, 103 | keying_action: if self.params.hierarchical == "cutout" { 104 | KeyingAction::Keep 105 | } else { 106 | KeyingAction::Discard 107 | }, 108 | }, image); 109 | self.stage = Stage::Clustering(runner.start()); 110 | } 111 | 112 | pub fn tick(&mut self) -> bool { 113 | match &mut self.stage { 114 | Stage::New => { 115 | panic!("uninitialized"); 116 | }, 117 | Stage::Clustering(builder) => { 118 | self.canvas.log("Clustering tick"); 119 | if builder.tick() { 120 | match self.params.hierarchical.as_str() { 121 | "stacked" => { 122 | self.stage = Stage::Vectorize(builder.result()); 123 | }, 124 | "cutout" => { 125 | let clusters = builder.result(); 126 | let view = clusters.view(); 127 | let image = view.to_color_image(); 128 | let runner = Runner::new(RunnerConfig { 129 | diagonal: false, 130 | hierarchical: 64, 131 | batch_size: 25600, 132 | good_min_area: 0, 133 | good_max_area: (image.width * image.height) as usize, 134 | is_same_color_a: 0, 135 | is_same_color_b: 1, 136 | deepen_diff: 0, 137 | hollow_neighbours: 0, 138 | key_color: Default::default(), 139 | keying_action: KeyingAction::Discard, 140 | }, image); 141 | self.stage = Stage::Reclustering(runner.start()); 142 | }, 143 | _ => panic!("unknown hierarchical `{}`", self.params.hierarchical) 144 | } 145 | } 146 | false 147 | }, 148 | Stage::Reclustering(builder) => { 149 | self.canvas.log("Reclustering tick"); 150 | if builder.tick() { 151 | self.stage = Stage::Vectorize(builder.result()) 152 | } 153 | false 154 | }, 155 | Stage::Vectorize(clusters) => { 156 | let view = clusters.view(); 157 | if self.counter < view.clusters_output.len() { 158 | self.canvas.log("Vectorize tick"); 159 | let cluster = view.get_cluster(view.clusters_output[self.counter]); 160 | let paths = cluster.to_compound_path( 161 | &view, false, self.mode, 162 | self.params.corner_threshold, 163 | self.params.length_threshold, 164 | self.params.max_iterations, 165 | self.params.splice_threshold 166 | ); 167 | self.svg.prepend_path( 168 | &paths, 169 | &cluster.residue_color(), 170 | Some(self.params.path_precision), 171 | ); 172 | self.counter += 1; 173 | false 174 | } else { 175 | self.canvas.log("done"); 176 | true 177 | } 178 | } 179 | } 180 | } 181 | 182 | pub fn progress(&self) -> i32 { 183 | (match &self.stage { 184 | Stage::New => { 185 | 0 186 | }, 187 | Stage::Clustering(builder) => { 188 | builder.progress() / 2 189 | }, 190 | Stage::Reclustering(_builder) => { 191 | 50 192 | }, 193 | Stage::Vectorize(clusters) => { 194 | 50 + 50 * self.counter as u32 / clusters.view().clusters_output.len() as u32 195 | } 196 | }) as i32 197 | } 198 | 199 | fn color_exists_in_image(img: &ColorImage, color: Color) -> bool { 200 | for y in 0..img.height { 201 | for x in 0..img.width { 202 | let pixel_color = img.get_pixel(x, y); 203 | if pixel_color.r == color.r && pixel_color.g == color.g && pixel_color.b == color.b { 204 | return true 205 | } 206 | } 207 | } 208 | false 209 | } 210 | 211 | fn find_unused_color_in_image(img: &ColorImage) -> Result { 212 | let special_colors = IntoIterator::into_iter([ 213 | Color::new(255, 0, 0), 214 | Color::new(0, 255, 0), 215 | Color::new(0, 0, 255), 216 | Color::new(255, 255, 0), 217 | Color::new(0, 255, 255), 218 | Color::new(255, 0, 255), 219 | Color::new(128, 128, 128), 220 | ]); 221 | for color in special_colors { 222 | if !Self::color_exists_in_image(img, color) { 223 | return Ok(color); 224 | } 225 | } 226 | Err(String::from("unable to find unused color in image to use as key")) 227 | } 228 | 229 | fn should_key_image(img: &ColorImage) -> bool { 230 | if img.width == 0 || img.height == 0 { 231 | return false; 232 | } 233 | 234 | // Check for transparency at several scanlines 235 | let threshold = ((img.width * 2) as f32 * KEYING_THRESHOLD) as usize; 236 | let mut num_transparent_pixels = 0; 237 | let y_positions = [0, img.height / 4, img.height / 2, 3 * img.height / 4, img.height - 1]; 238 | for y in y_positions { 239 | for x in 0..img.width { 240 | if img.get_pixel(x, y).a == 0 { 241 | num_transparent_pixels += 1; 242 | } 243 | if num_transparent_pixels >= threshold { 244 | return true; 245 | } 246 | } 247 | } 248 | 249 | false 250 | } 251 | } -------------------------------------------------------------------------------- /webapp/src/conversion/mod.rs: -------------------------------------------------------------------------------- 1 | mod binary_image; 2 | mod color_image; 3 | mod util; 4 | -------------------------------------------------------------------------------- /webapp/src/conversion/util.rs: -------------------------------------------------------------------------------- 1 | use visioncortex::PathSimplifyMode; 2 | 3 | pub fn path_simplify_mode(s: &str) -> PathSimplifyMode { 4 | match s { 5 | "polygon" => PathSimplifyMode::Polygon, 6 | "spline" => PathSimplifyMode::Spline, 7 | "none" => PathSimplifyMode::None, 8 | _ => panic!("unknown PathSimplifyMode {}", s), 9 | } 10 | } -------------------------------------------------------------------------------- /webapp/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2020 Tsang Hao Fung. See the COPYRIGHT 2 | // file at the top-level directory of this distribution and at 3 | // http://rust-lang.org/COPYRIGHT. 4 | // 5 | // Licensed under the Apache License, Version 2.0 or the MIT license 7 | // , at your 8 | // option. This file may not be copied, modified, or distributed 9 | // except according to those terms. 10 | #![doc( 11 | html_logo_url = "https://github.com/visioncortex/vtracer/raw/master/docs/images/visioncortex icon.png" 12 | )] 13 | use wasm_bindgen::prelude::*; 14 | 15 | mod conversion; 16 | mod canvas; 17 | mod common; 18 | mod svg; 19 | mod utils; 20 | 21 | #[wasm_bindgen(start)] 22 | pub fn main() { 23 | utils::set_panic_hook(); 24 | console_log::init().unwrap(); 25 | } -------------------------------------------------------------------------------- /webapp/src/svg.rs: -------------------------------------------------------------------------------- 1 | use web_sys::Element; 2 | use visioncortex::{Color, CompoundPath, PointF64}; 3 | use super::common::document; 4 | 5 | pub struct Svg { 6 | element: Element, 7 | } 8 | 9 | impl Svg { 10 | pub fn new_from_id(svg_id: &str) -> Self { 11 | let element = document().get_element_by_id(svg_id).unwrap(); 12 | 13 | Self { element } 14 | } 15 | 16 | pub fn prepend_path(&mut self, paths: &CompoundPath, color: &Color, precision: Option) { 17 | let path = document() 18 | .create_element_ns(Some("http://www.w3.org/2000/svg"), "path") 19 | .unwrap(); 20 | let (string, offset) = paths.to_svg_string(true, PointF64::default(), precision); 21 | path.set_attribute("d", &string).unwrap(); 22 | path.set_attribute( 23 | "transform", 24 | format!("translate({},{})", offset.x, offset.y).as_str(), 25 | ) 26 | .unwrap(); 27 | path.set_attribute( 28 | "style", 29 | format!("fill: {};", color.to_hex_string()).as_str(), 30 | ) 31 | .unwrap(); 32 | self.element.prepend_with_node_1(&path).unwrap(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /webapp/src/utils.rs: -------------------------------------------------------------------------------- 1 | extern crate cfg_if; 2 | 3 | cfg_if::cfg_if! { 4 | // When the `console_error_panic_hook` feature is enabled, we can call the 5 | // `set_panic_hook` function to get better error messages if we ever panic. 6 | if #[cfg(feature = "console_error_panic_hook")] { 7 | extern crate console_error_panic_hook; 8 | pub use self::console_error_panic_hook::set_once as set_panic_hook; 9 | } else { 10 | #[inline] 11 | pub fn set_panic_hook() {} 12 | } 13 | } 14 | --------------------------------------------------------------------------------