tinytrace-svg 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Shehryar Sohail
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,178 @@
1
+ Metadata-Version: 2.4
2
+ Name: tinytrace-svg
3
+ Version: 0.1.0
4
+ Summary: Convert PNG and JPG images to SVG that fits a size budget: an image vectorizer library and CLI
5
+ Author-email: Shehryar Sohail <sherryyatwork@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/itsmesherry/tinytrace
8
+ Project-URL: Repository, https://github.com/itsmesherry/tinytrace
9
+ Project-URL: Changelog, https://github.com/itsmesherry/tinytrace/blob/main/CHANGELOG.md
10
+ Project-URL: Issues, https://github.com/itsmesherry/tinytrace/issues
11
+ Keywords: svg,png-to-svg,jpg-to-svg,image-to-svg,vectorize,vectorizer,vectorization,image-tracing,raster-to-vector,svg-size
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Multimedia :: Graphics :: Graphics Conversion
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: numpy>=1.24
25
+ Requires-Dist: opencv-python-headless>=4.8
26
+ Provides-Extra: bench
27
+ Requires-Dist: scikit-image>=0.22; extra == "bench"
28
+ Requires-Dist: vtracer>=0.6; extra == "bench"
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest>=8.0; extra == "dev"
31
+ Requires-Dist: ruff>=0.10; extra == "dev"
32
+ Requires-Dist: mypy>=1.10; extra == "dev"
33
+ Requires-Dist: build>=1.0; extra == "dev"
34
+ Requires-Dist: twine>=5.0; extra == "dev"
35
+ Dynamic: license-file
36
+
37
+ <h1 align="center">tinytrace</h1>
38
+
39
+ <p align="center">
40
+ Convert PNG and JPG images to SVG that fits a size budget.<br>
41
+ You pick how many characters the SVG may have. tinytrace makes the best-looking picture that fits.
42
+ </p>
43
+
44
+ <p align="center">
45
+ <a href="https://pypi.org/project/tinytrace-svg/"><img alt="PyPI" src="https://img.shields.io/pypi/v/tinytrace-svg"></a>
46
+ <a href="https://github.com/itsmesherry/tinytrace/actions/workflows/ci.yml"><img alt="CI" src="https://github.com/itsmesherry/tinytrace/actions/workflows/ci.yml/badge.svg"></a>
47
+ <a href="https://pypi.org/project/tinytrace-svg/"><img alt="Python" src="https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue"></a>
48
+ <a href="https://github.com/itsmesherry/tinytrace/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/badge/license-MIT-blue"></a>
49
+ </p>
50
+
51
+ <p align="center">
52
+ <img src="https://raw.githubusercontent.com/itsmesherry/tinytrace/main/docs/images/hero.jpg" alt="Big Buck Bunny split down the middle: the original frame on the left, its tinytrace SVG on the right" width="100%">
53
+ </p>
54
+
55
+ tinytrace is an image vectorizer: a Python library and command line tool that
56
+ traces raster pictures (PNG, JPG, WebP and more) into vector SVG. Most tracers
57
+ try to match the picture and let the SVG grow as large as it needs to. tinytrace
58
+ works the other way round: you fix the size first, say "under
59
+ 125,000 characters", and it finds the most faithful picture that fits. That's
60
+ what you want when an SVG has a hard limit: an inline image on a web page, an
61
+ email, a config file, or a desktop backdrop with a size cap.
62
+
63
+ ```bash
64
+ pip install tinytrace-svg # the package on PyPI; the module and command are tinytrace
65
+ tinytrace picture.jpg --budget 125000
66
+ # picture.svg: 124,612 characters (budget 125,000), 9s
67
+ ```
68
+
69
+ ```python
70
+ import tinytrace
71
+
72
+ svg = tinytrace.trace("picture.jpg", budget=125_000)
73
+ ```
74
+
75
+ ## How it compares
76
+
77
+ The same frame traced by [vtracer](https://github.com/visioncortex/vtracer) and
78
+ by tinytrace, both held to 125,000 characters:
79
+
80
+ <p align="center">
81
+ <img src="https://raw.githubusercontent.com/itsmesherry/tinytrace/main/docs/images/comparison.jpg" alt="A Big Buck Bunny frame, then vtracer's and tinytrace's SVGs of it at 125,000 characters, with a zoom on the bunny's face" width="100%">
82
+ </p>
83
+
84
+ vtracer has no size setting, so it gets a fair search over its own: input size,
85
+ speck size, how much it merges similar colours, and stacked or cutout layers.
86
+ Of the 144 combinations, the one that scores best against the picture counts.
87
+ On 23 pictures tinytrace was not tuned on:
88
+
89
+ | Pictures | Colour error ↓ | Shape match ↑ | Outlines kept ↑ |
90
+ | --- | :---: | :---: | :---: |
91
+ | Cartoons (6) | **1.51** vs 2.08 | **0.98** vs 0.97 | **0.95** vs 0.89 |
92
+ | Digital art (4) | **2.79** vs 7.47 | **0.91** vs 0.82 | **0.71** vs 0.48 |
93
+ | Photos (13) | **3.86** vs 8.92 | **0.89** vs 0.75 | **0.71** vs 0.47 |
94
+
95
+ Per picture, tinytrace scored better on all three on 17 of the 23, and had the
96
+ lower colour error on 19. vtracer was a little more accurate in colour on four
97
+ very flat cartoons, where it needs far fewer characters. Colour error is the
98
+ mean CIE Lab difference after a light blur (about 2 is barely visible), shape
99
+ match is SSIM, and outlines kept is the share of the picture's strong edges the
100
+ SVG also has. See [bench/](https://github.com/itsmesherry/tinytrace/tree/main/bench)
101
+ to run it on your own pictures.
102
+
103
+ Photos come out painterly. Any tracer turns a photo into flat shapes, and at
104
+ this size tinytrace keeps them recognisable rather than photographic.
105
+
106
+ ## Examples
107
+
108
+ <!-- docs/images/*.jpg and *.svg: each picture beside its SVG, made with docs/make_examples.py -->
109
+
110
+ | Picture | tinytrace, 125,000 characters |
111
+ | --- | --- |
112
+ | <img src="https://raw.githubusercontent.com/itsmesherry/tinytrace/main/docs/images/bunny.jpg" width="400" alt="Original: a Big Buck Bunny frame"> | <img src="https://raw.githubusercontent.com/itsmesherry/tinytrace/main/docs/images/bunny.svg" width="400" alt="tinytrace SVG of a Big Buck Bunny frame, 125,000 characters"> |
113
+ | <img src="https://raw.githubusercontent.com/itsmesherry/tinytrace/main/docs/images/wave.jpg" width="400" alt="Original: Hokusai's Great Wave print"> | <img src="https://raw.githubusercontent.com/itsmesherry/tinytrace/main/docs/images/wave.svg" width="400" alt="tinytrace SVG of Hokusai's Great Wave print, 125,000 characters"> |
114
+ | <img src="https://raw.githubusercontent.com/itsmesherry/tinytrace/main/docs/images/poster.jpg" width="400" alt="Original: Toulouse-Lautrec's Divan Japonais poster"> | <img src="https://raw.githubusercontent.com/itsmesherry/tinytrace/main/docs/images/poster.svg" width="400" alt="tinytrace SVG of Toulouse-Lautrec's Divan Japonais poster, 125,000 characters"> |
115
+ | <img src="https://raw.githubusercontent.com/itsmesherry/tinytrace/main/docs/images/street.jpg" width="400" alt="Original: a city street at night"> | <img src="https://raw.githubusercontent.com/itsmesherry/tinytrace/main/docs/images/street.svg" width="400" alt="tinytrace SVG of a city street at night, 125,000 characters"> |
116
+
117
+ ## Options
118
+
119
+ | Option | Default | Meaning |
120
+ | --- | --- | --- |
121
+ | `budget` / `--budget` | 125000 | The most characters the SVG may have |
122
+ | `colors` / `--colors` | 40 | Fill palette size. More gives truer shading but leaves fewer characters for detail |
123
+ | `cover` / `--cover` | off | Fill any box the SVG is drawn in, cropping the edges (for backgrounds) |
124
+
125
+ `trace()` takes a file path or an OpenCV-style BGR `uint8` array, and raises
126
+ `tinytrace.BudgetTooSmall` when even the coarsest tracing is over the budget.
127
+ A trace takes about 10 seconds, whatever the picture's size.
128
+
129
+ ## How it works
130
+
131
+ 1. **Work at 1920 pixels wide.** Small pictures are enlarged smoothly first, so
132
+ edges follow curves instead of the source's pixel steps.
133
+ 2. **Fills.** Mean-shift flattens texture noise, k-means picks the palette in
134
+ Lab colour space, and a majority vote straightens ragged borders.
135
+ 3. **Ink.** Lines darker than their surroundings, like cartoon outlines, are
136
+ found on the unfiltered picture and painted last, on top, in a few ink
137
+ colours of their own.
138
+ 4. **Stacked layers.** Fills are painted largest first, and each may extend
139
+ under anything painted after it. Its outline then skips the holes and jaggies
140
+ later layers hide, so each border is stored about once instead of twice.
141
+ 5. **Polygons, searched to fit.** Outlines are simplified polygons written as
142
+ short relative steps. The tolerance and the smallest speck kept are searched
143
+ so the SVG fills the budget as closely as it can.
144
+
145
+ None of these steps is new on its own. tinytrace combines them and tunes them
146
+ for one goal: the most faithful picture in a fixed number of characters.
147
+
148
+ ## Example: a picture backdrop for the Claude desktop app
149
+
150
+ [examples/claude-backdrop](https://github.com/itsmesherry/tinytrace/tree/main/examples/claude-backdrop)
151
+ is a Claude desktop mod that shows a slideshow of pictures behind the chat. The
152
+ app caps a backdrop scene at 131,072 characters, which is where tinytrace came
153
+ from. It comes with three sample slides; install it with Claude Code and restart
154
+ the app:
155
+
156
+ ```bash
157
+ claude plugin marketplace add itsmesherry/tinytrace
158
+ claude plugin install picture-backdrop@tinytrace
159
+ ```
160
+
161
+ Its README shows how to use your own pictures.
162
+
163
+ ## Credits
164
+
165
+ Example pictures, each under its own licence (the MIT licence covers the code only):
166
+
167
+ - *Big Buck Bunny* frame © Blender Foundation,
168
+ [peach.blender.org](https://peach.blender.org), licensed
169
+ [CC BY 3.0](https://creativecommons.org/licenses/by/3.0/).
170
+ - *Under the Wave off Kanagawa*, Katsushika Hokusai, and *Divan Japonais*,
171
+ Henri de Toulouse-Lautrec: public domain, from
172
+ [The Metropolitan Museum of Art](https://www.metmuseum.org/about-the-met/policies-and-documents/open-access).
173
+ - City at night: photo by Jeff Golenski,
174
+ [WordPress Photo Directory](https://wordpress.org/photos/photo/3016a7fb59/), CC0.
175
+
176
+ ## License
177
+
178
+ [MIT](https://github.com/itsmesherry/tinytrace/blob/main/LICENSE)
@@ -0,0 +1,142 @@
1
+ <h1 align="center">tinytrace</h1>
2
+
3
+ <p align="center">
4
+ Convert PNG and JPG images to SVG that fits a size budget.<br>
5
+ You pick how many characters the SVG may have. tinytrace makes the best-looking picture that fits.
6
+ </p>
7
+
8
+ <p align="center">
9
+ <a href="https://pypi.org/project/tinytrace-svg/"><img alt="PyPI" src="https://img.shields.io/pypi/v/tinytrace-svg"></a>
10
+ <a href="https://github.com/itsmesherry/tinytrace/actions/workflows/ci.yml"><img alt="CI" src="https://github.com/itsmesherry/tinytrace/actions/workflows/ci.yml/badge.svg"></a>
11
+ <a href="https://pypi.org/project/tinytrace-svg/"><img alt="Python" src="https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue"></a>
12
+ <a href="https://github.com/itsmesherry/tinytrace/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/badge/license-MIT-blue"></a>
13
+ </p>
14
+
15
+ <p align="center">
16
+ <img src="https://raw.githubusercontent.com/itsmesherry/tinytrace/main/docs/images/hero.jpg" alt="Big Buck Bunny split down the middle: the original frame on the left, its tinytrace SVG on the right" width="100%">
17
+ </p>
18
+
19
+ tinytrace is an image vectorizer: a Python library and command line tool that
20
+ traces raster pictures (PNG, JPG, WebP and more) into vector SVG. Most tracers
21
+ try to match the picture and let the SVG grow as large as it needs to. tinytrace
22
+ works the other way round: you fix the size first, say "under
23
+ 125,000 characters", and it finds the most faithful picture that fits. That's
24
+ what you want when an SVG has a hard limit: an inline image on a web page, an
25
+ email, a config file, or a desktop backdrop with a size cap.
26
+
27
+ ```bash
28
+ pip install tinytrace-svg # the package on PyPI; the module and command are tinytrace
29
+ tinytrace picture.jpg --budget 125000
30
+ # picture.svg: 124,612 characters (budget 125,000), 9s
31
+ ```
32
+
33
+ ```python
34
+ import tinytrace
35
+
36
+ svg = tinytrace.trace("picture.jpg", budget=125_000)
37
+ ```
38
+
39
+ ## How it compares
40
+
41
+ The same frame traced by [vtracer](https://github.com/visioncortex/vtracer) and
42
+ by tinytrace, both held to 125,000 characters:
43
+
44
+ <p align="center">
45
+ <img src="https://raw.githubusercontent.com/itsmesherry/tinytrace/main/docs/images/comparison.jpg" alt="A Big Buck Bunny frame, then vtracer's and tinytrace's SVGs of it at 125,000 characters, with a zoom on the bunny's face" width="100%">
46
+ </p>
47
+
48
+ vtracer has no size setting, so it gets a fair search over its own: input size,
49
+ speck size, how much it merges similar colours, and stacked or cutout layers.
50
+ Of the 144 combinations, the one that scores best against the picture counts.
51
+ On 23 pictures tinytrace was not tuned on:
52
+
53
+ | Pictures | Colour error ↓ | Shape match ↑ | Outlines kept ↑ |
54
+ | --- | :---: | :---: | :---: |
55
+ | Cartoons (6) | **1.51** vs 2.08 | **0.98** vs 0.97 | **0.95** vs 0.89 |
56
+ | Digital art (4) | **2.79** vs 7.47 | **0.91** vs 0.82 | **0.71** vs 0.48 |
57
+ | Photos (13) | **3.86** vs 8.92 | **0.89** vs 0.75 | **0.71** vs 0.47 |
58
+
59
+ Per picture, tinytrace scored better on all three on 17 of the 23, and had the
60
+ lower colour error on 19. vtracer was a little more accurate in colour on four
61
+ very flat cartoons, where it needs far fewer characters. Colour error is the
62
+ mean CIE Lab difference after a light blur (about 2 is barely visible), shape
63
+ match is SSIM, and outlines kept is the share of the picture's strong edges the
64
+ SVG also has. See [bench/](https://github.com/itsmesherry/tinytrace/tree/main/bench)
65
+ to run it on your own pictures.
66
+
67
+ Photos come out painterly. Any tracer turns a photo into flat shapes, and at
68
+ this size tinytrace keeps them recognisable rather than photographic.
69
+
70
+ ## Examples
71
+
72
+ <!-- docs/images/*.jpg and *.svg: each picture beside its SVG, made with docs/make_examples.py -->
73
+
74
+ | Picture | tinytrace, 125,000 characters |
75
+ | --- | --- |
76
+ | <img src="https://raw.githubusercontent.com/itsmesherry/tinytrace/main/docs/images/bunny.jpg" width="400" alt="Original: a Big Buck Bunny frame"> | <img src="https://raw.githubusercontent.com/itsmesherry/tinytrace/main/docs/images/bunny.svg" width="400" alt="tinytrace SVG of a Big Buck Bunny frame, 125,000 characters"> |
77
+ | <img src="https://raw.githubusercontent.com/itsmesherry/tinytrace/main/docs/images/wave.jpg" width="400" alt="Original: Hokusai's Great Wave print"> | <img src="https://raw.githubusercontent.com/itsmesherry/tinytrace/main/docs/images/wave.svg" width="400" alt="tinytrace SVG of Hokusai's Great Wave print, 125,000 characters"> |
78
+ | <img src="https://raw.githubusercontent.com/itsmesherry/tinytrace/main/docs/images/poster.jpg" width="400" alt="Original: Toulouse-Lautrec's Divan Japonais poster"> | <img src="https://raw.githubusercontent.com/itsmesherry/tinytrace/main/docs/images/poster.svg" width="400" alt="tinytrace SVG of Toulouse-Lautrec's Divan Japonais poster, 125,000 characters"> |
79
+ | <img src="https://raw.githubusercontent.com/itsmesherry/tinytrace/main/docs/images/street.jpg" width="400" alt="Original: a city street at night"> | <img src="https://raw.githubusercontent.com/itsmesherry/tinytrace/main/docs/images/street.svg" width="400" alt="tinytrace SVG of a city street at night, 125,000 characters"> |
80
+
81
+ ## Options
82
+
83
+ | Option | Default | Meaning |
84
+ | --- | --- | --- |
85
+ | `budget` / `--budget` | 125000 | The most characters the SVG may have |
86
+ | `colors` / `--colors` | 40 | Fill palette size. More gives truer shading but leaves fewer characters for detail |
87
+ | `cover` / `--cover` | off | Fill any box the SVG is drawn in, cropping the edges (for backgrounds) |
88
+
89
+ `trace()` takes a file path or an OpenCV-style BGR `uint8` array, and raises
90
+ `tinytrace.BudgetTooSmall` when even the coarsest tracing is over the budget.
91
+ A trace takes about 10 seconds, whatever the picture's size.
92
+
93
+ ## How it works
94
+
95
+ 1. **Work at 1920 pixels wide.** Small pictures are enlarged smoothly first, so
96
+ edges follow curves instead of the source's pixel steps.
97
+ 2. **Fills.** Mean-shift flattens texture noise, k-means picks the palette in
98
+ Lab colour space, and a majority vote straightens ragged borders.
99
+ 3. **Ink.** Lines darker than their surroundings, like cartoon outlines, are
100
+ found on the unfiltered picture and painted last, on top, in a few ink
101
+ colours of their own.
102
+ 4. **Stacked layers.** Fills are painted largest first, and each may extend
103
+ under anything painted after it. Its outline then skips the holes and jaggies
104
+ later layers hide, so each border is stored about once instead of twice.
105
+ 5. **Polygons, searched to fit.** Outlines are simplified polygons written as
106
+ short relative steps. The tolerance and the smallest speck kept are searched
107
+ so the SVG fills the budget as closely as it can.
108
+
109
+ None of these steps is new on its own. tinytrace combines them and tunes them
110
+ for one goal: the most faithful picture in a fixed number of characters.
111
+
112
+ ## Example: a picture backdrop for the Claude desktop app
113
+
114
+ [examples/claude-backdrop](https://github.com/itsmesherry/tinytrace/tree/main/examples/claude-backdrop)
115
+ is a Claude desktop mod that shows a slideshow of pictures behind the chat. The
116
+ app caps a backdrop scene at 131,072 characters, which is where tinytrace came
117
+ from. It comes with three sample slides; install it with Claude Code and restart
118
+ the app:
119
+
120
+ ```bash
121
+ claude plugin marketplace add itsmesherry/tinytrace
122
+ claude plugin install picture-backdrop@tinytrace
123
+ ```
124
+
125
+ Its README shows how to use your own pictures.
126
+
127
+ ## Credits
128
+
129
+ Example pictures, each under its own licence (the MIT licence covers the code only):
130
+
131
+ - *Big Buck Bunny* frame © Blender Foundation,
132
+ [peach.blender.org](https://peach.blender.org), licensed
133
+ [CC BY 3.0](https://creativecommons.org/licenses/by/3.0/).
134
+ - *Under the Wave off Kanagawa*, Katsushika Hokusai, and *Divan Japonais*,
135
+ Henri de Toulouse-Lautrec: public domain, from
136
+ [The Metropolitan Museum of Art](https://www.metmuseum.org/about-the-met/policies-and-documents/open-access).
137
+ - City at night: photo by Jeff Golenski,
138
+ [WordPress Photo Directory](https://wordpress.org/photos/photo/3016a7fb59/), CC0.
139
+
140
+ ## License
141
+
142
+ [MIT](https://github.com/itsmesherry/tinytrace/blob/main/LICENSE)
@@ -0,0 +1,72 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "tinytrace-svg"
7
+ version = "0.1.0"
8
+ description = "Convert PNG and JPG images to SVG that fits a size budget: an image vectorizer library and CLI"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ authors = [
13
+ {name = "Shehryar Sohail", email = "sherryyatwork@gmail.com"}
14
+ ]
15
+ keywords = ["svg", "png-to-svg", "jpg-to-svg", "image-to-svg", "vectorize", "vectorizer", "vectorization", "image-tracing", "raster-to-vector", "svg-size"]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Intended Audience :: Developers",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.10",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Programming Language :: Python :: 3.13",
24
+ "Topic :: Multimedia :: Graphics :: Graphics Conversion",
25
+ "Typing :: Typed",
26
+ ]
27
+ dependencies = [
28
+ "numpy>=1.24",
29
+ "opencv-python-headless>=4.8",
30
+ ]
31
+
32
+ [project.optional-dependencies]
33
+ bench = [
34
+ "scikit-image>=0.22",
35
+ "vtracer>=0.6",
36
+ ]
37
+ dev = [
38
+ "pytest>=8.0",
39
+ "ruff>=0.10",
40
+ "mypy>=1.10",
41
+ "build>=1.0",
42
+ "twine>=5.0",
43
+ ]
44
+
45
+ [project.scripts]
46
+ tinytrace = "tinytrace.cli:main"
47
+
48
+ [project.urls]
49
+ Homepage = "https://github.com/itsmesherry/tinytrace"
50
+ Repository = "https://github.com/itsmesherry/tinytrace"
51
+ Changelog = "https://github.com/itsmesherry/tinytrace/blob/main/CHANGELOG.md"
52
+ Issues = "https://github.com/itsmesherry/tinytrace/issues"
53
+
54
+ [tool.setuptools.packages.find]
55
+ include = ["tinytrace*"]
56
+
57
+ [tool.setuptools.package-data]
58
+ tinytrace = ["py.typed"]
59
+
60
+ [tool.pytest.ini_options]
61
+ testpaths = ["tests"]
62
+
63
+ [tool.ruff]
64
+ line-length = 120
65
+ target-version = "py310"
66
+
67
+ [tool.ruff.lint]
68
+ select = ["E", "F", "I"]
69
+
70
+ [tool.mypy]
71
+ strict = true
72
+ ignore_missing_imports = true
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,111 @@
1
+ import shutil
2
+ import subprocess
3
+ import xml.etree.ElementTree as ET
4
+ from pathlib import Path
5
+
6
+ import cv2
7
+ import numpy as np
8
+ import pytest
9
+
10
+ from tinytrace import BudgetTooSmall, trace
11
+ from tinytrace.cli import main
12
+
13
+ SVG = "{http://www.w3.org/2000/svg}"
14
+
15
+
16
+ @pytest.fixture(scope="module")
17
+ def picture() -> np.ndarray:
18
+ """A small cartoon: sky gradient, ground, a red sun and a black-outlined house."""
19
+ img = np.zeros((450, 800, 3), np.uint8)
20
+ for y in range(300):
21
+ img[y] = (235 - y // 3, 190 - y // 6, 120) # BGR: blue sky, lighter lower down
22
+ img[300:] = (60, 150, 80)
23
+ cv2.circle(img, (650, 90), 50, (40, 40, 220), -1)
24
+ cv2.rectangle(img, (200, 180), (380, 320), (90, 200, 240), -1)
25
+ cv2.rectangle(img, (200, 180), (380, 320), (20, 20, 20), 4)
26
+ cv2.line(img, (190, 185), (290, 110), (20, 20, 20), 4)
27
+ cv2.line(img, (290, 110), (390, 185), (20, 20, 20), 4)
28
+ return img
29
+
30
+
31
+ @pytest.fixture(scope="module")
32
+ def svg(picture: np.ndarray) -> str:
33
+ return trace(picture, budget=40_000)
34
+
35
+
36
+ def colors(svg: str) -> list[tuple[int, int, int]]:
37
+ root = ET.fromstring(svg)
38
+ return [tuple(int(p.get("fill")[i : i + 2], 16) for i in (1, 3, 5)) for p in root.iter(f"{SVG}path")]
39
+
40
+
41
+ def test_fits_the_budget_and_is_valid_svg(svg: str) -> None:
42
+ assert len(svg) <= 40_000
43
+ root = ET.fromstring(svg)
44
+ assert root.tag == f"{SVG}svg"
45
+ assert root.get("viewBox") == "0 0 1920 1080"
46
+ assert len(list(root.iter(f"{SVG}path"))) > 3
47
+
48
+
49
+ def test_keeps_the_picture_colours(svg: str) -> None:
50
+ found = colors(svg)
51
+
52
+ def near(rgb: tuple[int, int, int]) -> bool:
53
+ return any(sum(abs(a - b) for a, b in zip(rgb, c)) < 40 for c in found)
54
+
55
+ assert near((220, 40, 40)), "red sun"
56
+ assert near((80, 150, 60)), "green ground"
57
+ assert near((20, 20, 20)), "black outline"
58
+
59
+
60
+ def test_a_smaller_budget_gives_a_smaller_svg(picture: np.ndarray, svg: str) -> None:
61
+ small = trace(picture, budget=8_000)
62
+ assert len(small) <= 8_000 < len(svg)
63
+
64
+
65
+ def test_too_small_a_budget_says_so(picture: np.ndarray) -> None:
66
+ with pytest.raises(BudgetTooSmall):
67
+ trace(picture, budget=300)
68
+
69
+
70
+ def test_tall_pictures_fit_too(picture: np.ndarray) -> None:
71
+ # A portrait picture has more pixels at 1920 wide; it must still fit, at a sensible size.
72
+ tall = np.ascontiguousarray(np.rot90(picture)) # 450 wide, 800 tall
73
+ svg = trace(tall, budget=40_000)
74
+ assert len(svg) <= 40_000
75
+ width, height = map(int, ET.fromstring(svg).get("viewBox").split()[2:])
76
+ assert height > width and width * height <= 1920 * 1440
77
+
78
+
79
+ def test_cover_fills_the_box(picture: np.ndarray) -> None:
80
+ assert 'preserveAspectRatio="xMidYMid slice"' in trace(picture, budget=10_000, cover=True)
81
+
82
+
83
+ def test_rejects_what_it_cannot_read(tmp_path: Path) -> None:
84
+ with pytest.raises(ValueError):
85
+ trace(tmp_path / "missing.png")
86
+ with pytest.raises(ValueError):
87
+ trace(np.zeros((10, 10), np.uint8))
88
+
89
+
90
+ def test_cli_writes_the_svg(picture: np.ndarray, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
91
+ src = tmp_path / "house.png"
92
+ cv2.imwrite(str(src), picture)
93
+ assert main([str(src), "--budget", "20000"]) == 0
94
+ out = tmp_path / "house.svg"
95
+ assert out.exists() and len(out.read_text()) <= 20_000
96
+ assert "characters" in capsys.readouterr().out
97
+ assert main([str(src), "--budget", "100"]) == 1
98
+
99
+
100
+ @pytest.mark.skipif(shutil.which("resvg") is None, reason="needs resvg to render the SVG")
101
+ def test_rendered_svg_looks_like_the_picture(picture: np.ndarray, svg: str, tmp_path: Path) -> None:
102
+ (tmp_path / "t.svg").write_text(svg)
103
+ subprocess.run(["resvg", "-w", "800", str(tmp_path / "t.svg"), str(tmp_path / "t.png")], check=True)
104
+ rendered = cv2.imread(str(tmp_path / "t.png"))
105
+ rendered = cv2.resize(rendered, (800, 450), interpolation=cv2.INTER_AREA)
106
+
107
+ def lab(img: np.ndarray) -> np.ndarray:
108
+ return cv2.cvtColor(cv2.GaussianBlur(img, (0, 0), 1.5).astype(np.float32) / 255, cv2.COLOR_BGR2LAB)
109
+
110
+ error = np.sqrt(((lab(picture) - lab(rendered)) ** 2).sum(2)).mean()
111
+ assert error < 4, f"mean colour error {error:.2f}"
@@ -0,0 +1,6 @@
1
+ """tinytrace: turn a picture into the best-looking SVG that fits a size budget."""
2
+
3
+ from .core import BudgetTooSmall, trace
4
+
5
+ __version__ = "0.1.0"
6
+ __all__ = ["BudgetTooSmall", "trace", "__version__"]
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,46 @@
1
+ """Command line: tinytrace picture.jpg [-o picture.svg] [--budget N] [--colors N] [--cover]."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ import time
8
+ from pathlib import Path
9
+
10
+ from . import __version__
11
+ from .core import BudgetTooSmall, trace
12
+
13
+
14
+ def main(argv: list[str] | None = None) -> int:
15
+ parser = argparse.ArgumentParser(
16
+ prog="tinytrace",
17
+ description="Turn a picture into the best-looking SVG that fits a size budget.",
18
+ )
19
+ parser.add_argument("image", type=Path, help="the picture to trace (jpg, png, webp, tiff, ...)")
20
+ parser.add_argument("-o", "--output", type=Path, help="where to write the SVG (default: next to the picture)")
21
+ parser.add_argument(
22
+ "-b", "--budget", type=int, default=125_000, help="most characters the SVG may have (default: 125000)"
23
+ )
24
+ parser.add_argument("-c", "--colors", type=int, default=40, help="fill palette size (default: 40)")
25
+ parser.add_argument(
26
+ "--cover", action="store_true", help="fill any box it is drawn in, cropping the edges (for backgrounds)"
27
+ )
28
+ parser.add_argument("-V", "--version", action="version", version=f"tinytrace {__version__}")
29
+ args = parser.parse_args(argv)
30
+
31
+ output = args.output or args.image.with_suffix(".svg")
32
+ if output.resolve() == args.image.resolve():
33
+ parser.error("the output would overwrite the picture; pass -o")
34
+ started = time.monotonic()
35
+ try:
36
+ svg = trace(args.image, budget=args.budget, colors=args.colors, cover=args.cover)
37
+ except (BudgetTooSmall, ValueError) as error:
38
+ print(f"tinytrace: {error}", file=sys.stderr)
39
+ return 1
40
+ output.write_text(svg, encoding="utf-8")
41
+ print(f"{output}: {len(svg):,} characters (budget {args.budget:,}), {time.monotonic() - started:.0f}s")
42
+ return 0
43
+
44
+
45
+ if __name__ == "__main__":
46
+ sys.exit(main())
@@ -0,0 +1,227 @@
1
+ """Turn a picture into the best-looking SVG that fits a fixed number of characters.
2
+
3
+ How, in order:
4
+
5
+ 1. Work at 1920 pixels wide (tall pictures at the same pixel count as a 4:3 one).
6
+ Small pictures are enlarged smoothly first, so edges follow curves instead of
7
+ the source's pixel steps.
8
+ 2. Fills: mean-shift flattens texture noise, k-means picks the palette in Lab
9
+ colour space, and a 5x5 majority vote straightens ragged borders.
10
+ 3. Ink: lines darker than their surroundings (cartoon outlines) are found on the
11
+ unfiltered picture, joined, and given a few ink colours of their own, painted
12
+ last on top.
13
+ 4. Stacked layers, largest fill first. A layer may also cover anything painted
14
+ after it, so its outline skips the holes and jaggies later layers hide (each
15
+ border is stored about once, not twice), and it reaches one pixel under later
16
+ layers so no hairline cracks show.
17
+ 5. Outlines are Douglas-Peucker polygons written as short relative integer steps.
18
+ Specks below a size are dropped. The tolerance and speck size are searched so
19
+ the result fills the budget as closely as it can.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import os
25
+ from collections.abc import Iterator
26
+ from typing import Union
27
+
28
+ import cv2
29
+ import numpy as np
30
+ from numpy.typing import NDArray
31
+
32
+ Image = Union[str, "os.PathLike[str]", NDArray[np.uint8]]
33
+
34
+ WIDTH = 1920
35
+ # Tall pictures are worked on at the same pixel count as a 4:3 one, not 1920 wide, or they couldn't fit a budget.
36
+ MAX_PIXELS = 1920 * 1440
37
+ INKS = 4
38
+
39
+
40
+ class BudgetTooSmall(ValueError):
41
+ """Even the coarsest tracing of the picture is over the budget."""
42
+
43
+
44
+ def _kmeans(px: NDArray[np.float32], k: int) -> tuple[NDArray[np.int32], NDArray[np.float32]]:
45
+ cv2.setRNGSeed(1)
46
+ criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 40, 0.2)
47
+ _, lbl, centers = cv2.kmeans(px, k, None, criteria, 3, cv2.KMEANS_PP_CENTERS)
48
+ return np.asarray(lbl, np.int32).ravel(), np.asarray(centers, np.float32)
49
+
50
+
51
+ def _majority(lbl: NDArray[np.int32], k: int) -> NDArray[np.int32]:
52
+ # Majority vote in a k x k window: straightens ragged colour borders (fewer corners to store).
53
+ best = np.zeros(lbl.shape, np.uint16)
54
+ out = lbl.copy()
55
+ for c in range(int(lbl.max()) + 1):
56
+ votes = cv2.boxFilter((lbl == c).astype(np.uint16), cv2.CV_16U, (k, k), normalize=False)
57
+ win = votes > best
58
+ best[win] = votes[win]
59
+ out[win] = c
60
+ return out
61
+
62
+
63
+ def _despeckle(lbl: NDArray[np.int32], min_area: int) -> NDArray[np.int32]:
64
+ # Specks smaller than min_area take the colour of the nearest larger region.
65
+ keep = np.ones(lbl.shape, np.uint8)
66
+ for c in range(int(lbl.max()) + 1):
67
+ _, comp, stats, _ = cv2.connectedComponentsWithStats((lbl == c).astype(np.uint8), connectivity=8)
68
+ small = np.where(stats[:, cv2.CC_STAT_AREA] < min_area)[0]
69
+ small = small[small > 0]
70
+ if len(small):
71
+ keep[np.isin(comp, small)] = 0
72
+ if keep.all():
73
+ return lbl
74
+ _, idx = cv2.distanceTransformWithLabels(1 - keep, cv2.DIST_L2, 3, labelType=cv2.DIST_LABEL_PIXEL)
75
+ ys, xs = np.nonzero(keep)
76
+ near = np.zeros(int(idx.max()) + 1, np.int32)
77
+ near[idx[ys, xs]] = lbl[ys, xs]
78
+ out: NDArray[np.int32] = near[idx]
79
+ return out
80
+
81
+
82
+ def _masks(lbl: NDArray[np.int32], order: list[int]) -> Iterator[NDArray[np.uint8]]:
83
+ # Layer i may cover pixels of later layers (they paint over it), never an earlier layer's pixels: its mask is
84
+ # everything except the parts of "not this colour" connected to earlier pixels, grown 1px under later layers.
85
+ rank = np.empty(int(lbl.max()) + 1, np.int32)
86
+ rank[order] = np.arange(len(order))
87
+ r = rank[lbl]
88
+ yield np.ones(lbl.shape, np.uint8)
89
+ for i in range(1, len(order)):
90
+ n, comp = cv2.connectedComponents((r != i).astype(np.uint8), connectivity=4)
91
+ blocked = np.zeros(n, bool)
92
+ blocked[np.unique(comp[r < i])] = True
93
+ blocked[0] = False
94
+ m = ~blocked[comp]
95
+ grown = cv2.dilate(m.astype(np.uint8), np.ones((3, 3), np.uint8)) > 0
96
+ yield (m | (grown & (r > i))).astype(np.uint8)
97
+
98
+
99
+ def _outline(mask: NDArray[np.uint8], eps: float) -> str:
100
+ # findContours on a 2x mask (so the outline sits on pixel edges, not half a pixel inside), Douglas-Peucker to
101
+ # eps pixels, then relative integer steps.
102
+ big = cv2.resize(mask, None, fx=2, fy=2, interpolation=cv2.INTER_NEAREST)
103
+ contours, _ = cv2.findContours(big, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
104
+ d: list[str] = []
105
+ px = py = 0
106
+ for contour in contours:
107
+ approx = cv2.approxPolyDP(contour, eps * 2, True)
108
+ # Small specks keep a few corners instead of collapsing to nothing.
109
+ if len(approx) < 4 and len(contour) >= 4:
110
+ approx = cv2.approxPolyDP(contour, eps / 2, True)
111
+ pts: list[tuple[int, int]] = []
112
+ for x, y in approx.reshape(-1, 2):
113
+ p = (round((x + 0.5) / 2), round((y + 0.5) / 2))
114
+ if not pts or p != pts[-1]:
115
+ pts.append(p)
116
+ if len(pts) < 3:
117
+ continue
118
+ x0, y0 = pts[0]
119
+ steps = " ".join(f"{x - a} {y - b}" for (a, b), (x, y) in zip(pts, pts[1:]))
120
+ d.append((f"m{x0 - px} {y0 - py}" if d else f"M{x0} {y0}") + "l" + steps + "z")
121
+ px, py = x0, y0
122
+ return "".join(d).replace(" -", "-")
123
+
124
+
125
+ def _load(image: Image) -> NDArray[np.uint8]:
126
+ if isinstance(image, np.ndarray):
127
+ if image.ndim != 3 or image.shape[2] != 3:
128
+ raise ValueError("expected a BGR image array of shape (height, width, 3)")
129
+ return image
130
+ src = cv2.imread(os.fspath(image))
131
+ if src is None:
132
+ raise ValueError(f"can't read {os.fspath(image)}")
133
+ return np.asarray(src, np.uint8)
134
+
135
+
136
+ def _prepare(src: NDArray[np.uint8], colors: int) -> tuple[NDArray[np.int32], NDArray[np.float32], int]:
137
+ w = min(WIDTH, round((MAX_PIXELS * src.shape[1] / src.shape[0]) ** 0.5))
138
+ h = round(src.shape[0] * w / src.shape[1])
139
+ resample = cv2.INTER_AREA if src.shape[1] >= w else cv2.INTER_CUBIC
140
+ raw = cv2.resize(src, (w, h), interpolation=resample)
141
+
142
+ # Fills.
143
+ flat = cv2.pyrMeanShiftFiltering(raw, 6, 20)
144
+ small = cv2.resize(flat, (640, round(h * 640 / w)), interpolation=cv2.INTER_AREA)
145
+ _, centers = _kmeans(cv2.cvtColor(small, cv2.COLOR_BGR2LAB).reshape(-1, 3).astype(np.float32), colors)
146
+ flat_lab = cv2.cvtColor(flat, cv2.COLOR_BGR2LAB).astype(np.float32)
147
+ lbl = ((flat_lab[:, :, None, :] - centers[None, None]) ** 2).sum(3).argmin(2).astype(np.int32)
148
+ lbl = _majority(lbl, 5)
149
+
150
+ # Ink.
151
+ lab = cv2.cvtColor(raw, cv2.COLOR_BGR2LAB)
152
+ light = lab[:, :, 0]
153
+ r = round(WIDTH / 1280 * 3)
154
+ kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * r + 1, 2 * r + 1))
155
+ dark = cv2.morphologyEx(light, cv2.MORPH_BLACKHAT, kernel)
156
+ lines = ((dark > 25) & (light < 180)).astype(np.uint8)
157
+ ink = cv2.morphologyEx(lines, cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8)) > 0
158
+ px = lab[ink].astype(np.float32)
159
+ if len(px) < 50 * INKS:
160
+ return lbl, centers, 0
161
+ il, ic = _kmeans(px, INKS)
162
+ # Each ink colour from the darker half of its group, so lines don't wash out.
163
+ groups = [px[il == j] for j in range(INKS)]
164
+ ic = np.array([np.median(g[g[:, 0] <= np.median(g[:, 0])], 0) if len(g) else ic[j] for j, g in enumerate(groups)])
165
+ # Edge pixels that only looked dark next to something brighter keep their fill colour.
166
+ il[np.sqrt(((px - ic[il]) ** 2).sum(1)) > 45] = -1
167
+ inkl = np.zeros(lbl.shape, np.uint8)
168
+ inkl[ink] = il + 1
169
+ # Thin lines from a big picture get a pixel thicker, so they stay solid strokes rather than dotted ones.
170
+ if src.shape[1] >= 1.5 * w:
171
+ inkl = np.where(inkl > 0, inkl, cv2.dilate(inkl, np.ones((2, 2), np.uint8)))
172
+ lbl[inkl > 0] = len(centers) + inkl[inkl > 0].astype(np.int32) - 1
173
+ return lbl, np.vstack([centers, ic]).astype(np.float32), INKS
174
+
175
+
176
+ def _build(lbl: NDArray[np.int32], centers: NDArray[np.float32], inks: int, s: float, cover: bool) -> str:
177
+ # s: outline tolerance in pixels; specks under ~18*s^2 pixels are dropped.
178
+ lbl = _despeckle(lbl, max(3, round(18 * s * s)))
179
+ h, w = lbl.shape
180
+ n = len(centers)
181
+ area = np.bincount(lbl.ravel(), minlength=n)
182
+ # Fills first, largest first; ink colours last.
183
+ order = sorted((c for c in range(n - inks) if area[c]), key=lambda c: -area[c])
184
+ order += sorted((c for c in range(n - inks, n) if area[c]), key=lambda c: -area[c])
185
+ rgb = cv2.cvtColor(np.clip(centers, 0, 255).reshape(1, -1, 3).astype(np.uint8), cv2.COLOR_LAB2RGB)[0]
186
+ fit = ' preserveAspectRatio="xMidYMid slice"' if cover else ""
187
+ parts = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {h}"{fit}>']
188
+ for c, m in zip(order, _masks(lbl, order)):
189
+ d = _outline(m, s)
190
+ if d:
191
+ color = "#%02x%02x%02x" % tuple(int(v) for v in rgb[c])
192
+ parts.append(f'<path fill-rule="evenodd" fill="{color}" d="{d}"/>')
193
+ return "".join(parts) + "</svg>"
194
+
195
+
196
+ def trace(image: Image, budget: int = 125_000, colors: int = 40, cover: bool = False) -> str:
197
+ """Trace ``image`` into an SVG string of at most ``budget`` characters.
198
+
199
+ Args:
200
+ image: a file path, or a BGR ``uint8`` array as OpenCV loads it.
201
+ budget: the most characters the SVG may have.
202
+ colors: fill palette size. More gives truer shading but leaves fewer
203
+ characters for detail.
204
+ cover: add ``preserveAspectRatio="xMidYMid slice"`` so the picture
205
+ fills any box it is drawn in, cropping the edges (for backgrounds).
206
+
207
+ Raises:
208
+ BudgetTooSmall: even the coarsest tracing is over ``budget``.
209
+ ValueError: the image can't be read.
210
+ """
211
+ if budget < 1:
212
+ raise ValueError("budget must be positive")
213
+ if colors < 2:
214
+ raise ValueError("colors must be at least 2")
215
+ lbl, centers, inks = _prepare(_load(image), colors)
216
+ # Coarser = fewer characters: search for the finest that fits.
217
+ lo, hi, best = 0.4, 4.0, None
218
+ for _ in range(7):
219
+ mid = (lo + hi) / 2
220
+ svg = _build(lbl, centers, inks, mid, cover)
221
+ if len(svg) <= budget:
222
+ hi, best = mid, svg
223
+ else:
224
+ lo = mid
225
+ if best is None:
226
+ raise BudgetTooSmall(f"even the coarsest tracing is over {budget} characters")
227
+ return best
File without changes
@@ -0,0 +1,178 @@
1
+ Metadata-Version: 2.4
2
+ Name: tinytrace-svg
3
+ Version: 0.1.0
4
+ Summary: Convert PNG and JPG images to SVG that fits a size budget: an image vectorizer library and CLI
5
+ Author-email: Shehryar Sohail <sherryyatwork@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/itsmesherry/tinytrace
8
+ Project-URL: Repository, https://github.com/itsmesherry/tinytrace
9
+ Project-URL: Changelog, https://github.com/itsmesherry/tinytrace/blob/main/CHANGELOG.md
10
+ Project-URL: Issues, https://github.com/itsmesherry/tinytrace/issues
11
+ Keywords: svg,png-to-svg,jpg-to-svg,image-to-svg,vectorize,vectorizer,vectorization,image-tracing,raster-to-vector,svg-size
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Multimedia :: Graphics :: Graphics Conversion
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: numpy>=1.24
25
+ Requires-Dist: opencv-python-headless>=4.8
26
+ Provides-Extra: bench
27
+ Requires-Dist: scikit-image>=0.22; extra == "bench"
28
+ Requires-Dist: vtracer>=0.6; extra == "bench"
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest>=8.0; extra == "dev"
31
+ Requires-Dist: ruff>=0.10; extra == "dev"
32
+ Requires-Dist: mypy>=1.10; extra == "dev"
33
+ Requires-Dist: build>=1.0; extra == "dev"
34
+ Requires-Dist: twine>=5.0; extra == "dev"
35
+ Dynamic: license-file
36
+
37
+ <h1 align="center">tinytrace</h1>
38
+
39
+ <p align="center">
40
+ Convert PNG and JPG images to SVG that fits a size budget.<br>
41
+ You pick how many characters the SVG may have. tinytrace makes the best-looking picture that fits.
42
+ </p>
43
+
44
+ <p align="center">
45
+ <a href="https://pypi.org/project/tinytrace-svg/"><img alt="PyPI" src="https://img.shields.io/pypi/v/tinytrace-svg"></a>
46
+ <a href="https://github.com/itsmesherry/tinytrace/actions/workflows/ci.yml"><img alt="CI" src="https://github.com/itsmesherry/tinytrace/actions/workflows/ci.yml/badge.svg"></a>
47
+ <a href="https://pypi.org/project/tinytrace-svg/"><img alt="Python" src="https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue"></a>
48
+ <a href="https://github.com/itsmesherry/tinytrace/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/badge/license-MIT-blue"></a>
49
+ </p>
50
+
51
+ <p align="center">
52
+ <img src="https://raw.githubusercontent.com/itsmesherry/tinytrace/main/docs/images/hero.jpg" alt="Big Buck Bunny split down the middle: the original frame on the left, its tinytrace SVG on the right" width="100%">
53
+ </p>
54
+
55
+ tinytrace is an image vectorizer: a Python library and command line tool that
56
+ traces raster pictures (PNG, JPG, WebP and more) into vector SVG. Most tracers
57
+ try to match the picture and let the SVG grow as large as it needs to. tinytrace
58
+ works the other way round: you fix the size first, say "under
59
+ 125,000 characters", and it finds the most faithful picture that fits. That's
60
+ what you want when an SVG has a hard limit: an inline image on a web page, an
61
+ email, a config file, or a desktop backdrop with a size cap.
62
+
63
+ ```bash
64
+ pip install tinytrace-svg # the package on PyPI; the module and command are tinytrace
65
+ tinytrace picture.jpg --budget 125000
66
+ # picture.svg: 124,612 characters (budget 125,000), 9s
67
+ ```
68
+
69
+ ```python
70
+ import tinytrace
71
+
72
+ svg = tinytrace.trace("picture.jpg", budget=125_000)
73
+ ```
74
+
75
+ ## How it compares
76
+
77
+ The same frame traced by [vtracer](https://github.com/visioncortex/vtracer) and
78
+ by tinytrace, both held to 125,000 characters:
79
+
80
+ <p align="center">
81
+ <img src="https://raw.githubusercontent.com/itsmesherry/tinytrace/main/docs/images/comparison.jpg" alt="A Big Buck Bunny frame, then vtracer's and tinytrace's SVGs of it at 125,000 characters, with a zoom on the bunny's face" width="100%">
82
+ </p>
83
+
84
+ vtracer has no size setting, so it gets a fair search over its own: input size,
85
+ speck size, how much it merges similar colours, and stacked or cutout layers.
86
+ Of the 144 combinations, the one that scores best against the picture counts.
87
+ On 23 pictures tinytrace was not tuned on:
88
+
89
+ | Pictures | Colour error ↓ | Shape match ↑ | Outlines kept ↑ |
90
+ | --- | :---: | :---: | :---: |
91
+ | Cartoons (6) | **1.51** vs 2.08 | **0.98** vs 0.97 | **0.95** vs 0.89 |
92
+ | Digital art (4) | **2.79** vs 7.47 | **0.91** vs 0.82 | **0.71** vs 0.48 |
93
+ | Photos (13) | **3.86** vs 8.92 | **0.89** vs 0.75 | **0.71** vs 0.47 |
94
+
95
+ Per picture, tinytrace scored better on all three on 17 of the 23, and had the
96
+ lower colour error on 19. vtracer was a little more accurate in colour on four
97
+ very flat cartoons, where it needs far fewer characters. Colour error is the
98
+ mean CIE Lab difference after a light blur (about 2 is barely visible), shape
99
+ match is SSIM, and outlines kept is the share of the picture's strong edges the
100
+ SVG also has. See [bench/](https://github.com/itsmesherry/tinytrace/tree/main/bench)
101
+ to run it on your own pictures.
102
+
103
+ Photos come out painterly. Any tracer turns a photo into flat shapes, and at
104
+ this size tinytrace keeps them recognisable rather than photographic.
105
+
106
+ ## Examples
107
+
108
+ <!-- docs/images/*.jpg and *.svg: each picture beside its SVG, made with docs/make_examples.py -->
109
+
110
+ | Picture | tinytrace, 125,000 characters |
111
+ | --- | --- |
112
+ | <img src="https://raw.githubusercontent.com/itsmesherry/tinytrace/main/docs/images/bunny.jpg" width="400" alt="Original: a Big Buck Bunny frame"> | <img src="https://raw.githubusercontent.com/itsmesherry/tinytrace/main/docs/images/bunny.svg" width="400" alt="tinytrace SVG of a Big Buck Bunny frame, 125,000 characters"> |
113
+ | <img src="https://raw.githubusercontent.com/itsmesherry/tinytrace/main/docs/images/wave.jpg" width="400" alt="Original: Hokusai's Great Wave print"> | <img src="https://raw.githubusercontent.com/itsmesherry/tinytrace/main/docs/images/wave.svg" width="400" alt="tinytrace SVG of Hokusai's Great Wave print, 125,000 characters"> |
114
+ | <img src="https://raw.githubusercontent.com/itsmesherry/tinytrace/main/docs/images/poster.jpg" width="400" alt="Original: Toulouse-Lautrec's Divan Japonais poster"> | <img src="https://raw.githubusercontent.com/itsmesherry/tinytrace/main/docs/images/poster.svg" width="400" alt="tinytrace SVG of Toulouse-Lautrec's Divan Japonais poster, 125,000 characters"> |
115
+ | <img src="https://raw.githubusercontent.com/itsmesherry/tinytrace/main/docs/images/street.jpg" width="400" alt="Original: a city street at night"> | <img src="https://raw.githubusercontent.com/itsmesherry/tinytrace/main/docs/images/street.svg" width="400" alt="tinytrace SVG of a city street at night, 125,000 characters"> |
116
+
117
+ ## Options
118
+
119
+ | Option | Default | Meaning |
120
+ | --- | --- | --- |
121
+ | `budget` / `--budget` | 125000 | The most characters the SVG may have |
122
+ | `colors` / `--colors` | 40 | Fill palette size. More gives truer shading but leaves fewer characters for detail |
123
+ | `cover` / `--cover` | off | Fill any box the SVG is drawn in, cropping the edges (for backgrounds) |
124
+
125
+ `trace()` takes a file path or an OpenCV-style BGR `uint8` array, and raises
126
+ `tinytrace.BudgetTooSmall` when even the coarsest tracing is over the budget.
127
+ A trace takes about 10 seconds, whatever the picture's size.
128
+
129
+ ## How it works
130
+
131
+ 1. **Work at 1920 pixels wide.** Small pictures are enlarged smoothly first, so
132
+ edges follow curves instead of the source's pixel steps.
133
+ 2. **Fills.** Mean-shift flattens texture noise, k-means picks the palette in
134
+ Lab colour space, and a majority vote straightens ragged borders.
135
+ 3. **Ink.** Lines darker than their surroundings, like cartoon outlines, are
136
+ found on the unfiltered picture and painted last, on top, in a few ink
137
+ colours of their own.
138
+ 4. **Stacked layers.** Fills are painted largest first, and each may extend
139
+ under anything painted after it. Its outline then skips the holes and jaggies
140
+ later layers hide, so each border is stored about once instead of twice.
141
+ 5. **Polygons, searched to fit.** Outlines are simplified polygons written as
142
+ short relative steps. The tolerance and the smallest speck kept are searched
143
+ so the SVG fills the budget as closely as it can.
144
+
145
+ None of these steps is new on its own. tinytrace combines them and tunes them
146
+ for one goal: the most faithful picture in a fixed number of characters.
147
+
148
+ ## Example: a picture backdrop for the Claude desktop app
149
+
150
+ [examples/claude-backdrop](https://github.com/itsmesherry/tinytrace/tree/main/examples/claude-backdrop)
151
+ is a Claude desktop mod that shows a slideshow of pictures behind the chat. The
152
+ app caps a backdrop scene at 131,072 characters, which is where tinytrace came
153
+ from. It comes with three sample slides; install it with Claude Code and restart
154
+ the app:
155
+
156
+ ```bash
157
+ claude plugin marketplace add itsmesherry/tinytrace
158
+ claude plugin install picture-backdrop@tinytrace
159
+ ```
160
+
161
+ Its README shows how to use your own pictures.
162
+
163
+ ## Credits
164
+
165
+ Example pictures, each under its own licence (the MIT licence covers the code only):
166
+
167
+ - *Big Buck Bunny* frame © Blender Foundation,
168
+ [peach.blender.org](https://peach.blender.org), licensed
169
+ [CC BY 3.0](https://creativecommons.org/licenses/by/3.0/).
170
+ - *Under the Wave off Kanagawa*, Katsushika Hokusai, and *Divan Japonais*,
171
+ Henri de Toulouse-Lautrec: public domain, from
172
+ [The Metropolitan Museum of Art](https://www.metmuseum.org/about-the-met/policies-and-documents/open-access).
173
+ - City at night: photo by Jeff Golenski,
174
+ [WordPress Photo Directory](https://wordpress.org/photos/photo/3016a7fb59/), CC0.
175
+
176
+ ## License
177
+
178
+ [MIT](https://github.com/itsmesherry/tinytrace/blob/main/LICENSE)
@@ -0,0 +1,15 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ tests/test_trace.py
5
+ tinytrace/__init__.py
6
+ tinytrace/__main__.py
7
+ tinytrace/cli.py
8
+ tinytrace/core.py
9
+ tinytrace/py.typed
10
+ tinytrace_svg.egg-info/PKG-INFO
11
+ tinytrace_svg.egg-info/SOURCES.txt
12
+ tinytrace_svg.egg-info/dependency_links.txt
13
+ tinytrace_svg.egg-info/entry_points.txt
14
+ tinytrace_svg.egg-info/requires.txt
15
+ tinytrace_svg.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ tinytrace = tinytrace.cli:main
@@ -0,0 +1,13 @@
1
+ numpy>=1.24
2
+ opencv-python-headless>=4.8
3
+
4
+ [bench]
5
+ scikit-image>=0.22
6
+ vtracer>=0.6
7
+
8
+ [dev]
9
+ pytest>=8.0
10
+ ruff>=0.10
11
+ mypy>=1.10
12
+ build>=1.0
13
+ twine>=5.0
@@ -0,0 +1 @@
1
+ tinytrace