Convert Figma logo to code with AI

visioncortex logovtracer

Raster to Vector Graphics Converter

3,142
208
3,142
8

Top Related Projects

12,644

Reproducing images with geometric primitives.

Simple raster image tracer and vectorizer written in JavaScript.

:white_square_button: Geometrize is a desktop app that geometrizes images into geometric primitives

Quick Overview

vtracer is an open-source library and command-line tool for converting raster images to vector graphics. It uses advanced image processing and tracing algorithms to produce high-quality SVG output from various input formats. vtracer is designed to be fast, accurate, and customizable.

Pros

  • High-quality vector output with accurate color representation
  • Supports multiple input formats (PNG, JPG, BMP, etc.) and outputs SVG
  • Offers both a Rust library and a command-line interface for flexibility
  • Provides various customization options for fine-tuning the tracing process

Cons

  • Limited documentation for advanced usage and customization
  • May produce complex SVGs with many paths for intricate images
  • Requires Rust knowledge for library integration and advanced usage
  • Performance may vary depending on image complexity and chosen settings

Code Examples

  1. Basic image tracing using default settings:
use vtracer::{convert_image_to_svg, ColorMode};

let input_path = "input.png";
let output_path = "output.svg";

convert_image_to_svg(
    input_path,
    output_path,
    ColorMode::Color,
    None,
    None,
    None,
    None,
    None,
).unwrap();
  1. Customizing tracing parameters:
use vtracer::{convert_image_to_svg, ColorMode, Config};

let input_path = "input.png";
let output_path = "output.svg";

let config = Config {
    color_mode: ColorMode::Color,
    hierarchical: true,
    filter_speckle: 4,
    corner_threshold: 60,
    length_threshold: 4.0,
    max_iterations: 10,
    splice_threshold: 45,
    ..Default::default()
};

convert_image_to_svg(
    input_path,
    output_path,
    config.color_mode,
    Some(config.hierarchical),
    Some(config.filter_speckle),
    Some(config.corner_threshold),
    Some(config.length_threshold),
    Some(config.max_iterations),
).unwrap();
  1. Using the library to process image data in memory:
use vtracer::{colorspace, PathSimplifier, Tracer};
use image::DynamicImage;

let img = image::open("input.png").unwrap();
let width = img.width();
let height = img.height();
let rgba = img.to_rgba8();

let mut tracer = Tracer::new(ColorMode::Color);
tracer.set_color_mode(ColorMode::Color);
tracer.set_hierarchical(true);
tracer.set_filter_speckle(4);
tracer.set_corner_threshold(60);
tracer.set_length_threshold(4.0);
tracer.set_max_iterations(10);
tracer.set_splice_threshold(45);

let paths = tracer.trace(&rgba, width, height);
let svg = tracer.generate_svg(&paths);

Getting Started

To use vtracer as a library in your Rust project:

  1. Add vtracer to your Cargo.toml:

    [dependencies]
    vtracer = "0.3"
    
  2. Use the library in your code:

    use vtracer::{convert_image_to_svg, ColorMode};
    
    fn main() {
        convert_image_to_svg(
            "input.png",
            "output.svg",
            ColorMode::Color,
            None,
            None,
            None,
            None,
            None,
        ).unwrap();
    }
    
  3. Run your program to convert the image to SVG.

For command-line usage, install vtracer using cargo:

cargo install vtracer

Then use it from the command line:

vtracer -i input.png -o output.svg

Competitor Comparisons

12,644

Reproducing images with geometric primitives.

Pros of Primitive

  • Generates images using geometric primitives (circles, triangles, etc.), offering a unique artistic style
  • Supports multiple output formats, including SVG, PNG, and GIF
  • Allows for fine-tuning of the output through various parameters

Cons of Primitive

  • Limited to specific geometric shapes, which may not be suitable for all types of images
  • Can be slower for complex images due to the iterative nature of the algorithm
  • Requires Go programming language, which may not be as widely used as other languages

Code Comparison

Primitive:

for n := 0; n < numShapes; n++ {
    t := model.BestHillClimbShape(shapeType, alpha, n)
    model.Add(t)
}

VTracer:

let spline_pathset = SplinePathBuilder::new()
    .with_accuracy(accuracy)
    .with_splice_tolerance(splice_tolerance)
    .create_spline_paths(&path_set);

Key Differences

  • Primitive focuses on creating images using geometric shapes, while VTracer aims to convert raster images to vector graphics
  • VTracer offers more flexibility in terms of output, as it can produce complex vector paths
  • Primitive is written in Go, whereas VTracer is implemented in Rust
  • VTracer may be more suitable for accurate image tracing, while Primitive excels in creating artistic interpretations of images

Simple raster image tracer and vectorizer written in JavaScript.

Pros of ImageTracerJS

  • Pure JavaScript implementation, making it easily integrable into web projects
  • Supports multiple output formats including SVG, Canvas, and PNG
  • Provides a simple API for easy usage in various environments

Cons of ImageTracerJS

  • Less optimized for performance compared to VTracer
  • Limited advanced features and customization options
  • May produce less accurate results for complex images

Code Comparison

ImageTracerJS:

ImageTracer.imageToSVG('image.png', function(svgstr) {
  console.log(svgstr);
});

VTracer:

let mut vtracer = VTracer::new();
let svg = vtracer.trace_image("image.png")?;
println!("{}", svg);

VTracer is implemented in Rust, offering better performance and memory efficiency. It provides more advanced tracing algorithms and customization options. However, it may require additional setup for web-based projects compared to the JavaScript-based ImageTracerJS.

Both libraries aim to convert raster images to vector graphics, but VTracer generally produces more accurate results, especially for complex images. ImageTracerJS is more suitable for quick, simple conversions in web environments, while VTracer is better for applications requiring higher quality output and performance.

:white_square_button: Geometrize is a desktop app that geometrizes images into geometric primitives

Pros of Geometrize

  • Offers a wider variety of primitive shapes for image approximation, including rectangles, rotated rectangles, and circles
  • Provides a user-friendly GUI application for easier interaction and visualization
  • Supports exporting results to various formats, including SVG and JSON

Cons of Geometrize

  • Generally slower processing speed compared to vtracer
  • Less focused on vector tracing, as it's primarily an image approximation tool
  • May require more manual tweaking to achieve desired results

Code Comparison

Geometrize (JavaScript):

const imageRunner = new ImageRunner(bitmap);
const options = {
    shapeTypes: [ShapeTypes.RECTANGLE, ShapeTypes.ELLIPSE],
    candidateShapesPerStep: 50,
    shapeMutationsPerStep: 100
};
const result = imageRunner.step(options);

vtracer (Rust):

let mut vtracer = VTracer::new();
vtracer.set_corner_threshold(60.0);
vtracer.set_length_threshold(4.0);
vtracer.set_max_iterations(10);
let svg = vtracer.trace(image_data, width, height);

Both libraries offer image processing capabilities, but Geometrize focuses on image approximation using geometric primitives, while vtracer specializes in vector tracing. The code snippets demonstrate the different approaches and configuration options available in each library.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

VTracer

Raster to Vector Graphics Converter built on top of visioncortex

Article | Web App | Download

Built with 🦀 by The Vision Cortex Research Group

Introduction

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.

Comparing to Potrace 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).

Comparing to Adobe Illustrator's Image Trace, VTracer's output is much more compact (less shapes) as we adopt a stacking strategy and avoid producing shapes with holes.

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.

Technical descriptions of the tracing algorithm and clustering algorithm.

Web App

VTracer and its core library is implemented in Rust. 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.

screenshot

screenshot

Cmd App

visioncortex VTracer 0.6.0
A cmd app to convert images into vector graphics.

USAGE:
    vtracer [OPTIONS] --input <input> --output <output>

FLAGS:
    -h, --help       Prints help information
    -V, --version    Prints version information

OPTIONS:
        --colormode <color_mode>                 True color image `color` (default) or Binary image `bw`
    -p, --color_precision <color_precision>      Number of significant bits to use in an RGB channel
    -c, --corner_threshold <corner_threshold>    Minimum momentary angle (degree) to be considered a corner
    -f, --filter_speckle <filter_speckle>        Discard patches smaller than X px in size
    -g, --gradient_step <gradient_step>          Color difference between gradient layers
        --hierarchical <hierarchical>
            Hierarchical clustering `stacked` (default) or non-stacked `cutout`. Only applies to color mode.

    -i, --input <input>                          Path to input raster image
    -m, --mode <mode>                            Curver fitting mode `pixel`, `polygon`, `spline`
    -o, --output <output>                        Path to output vector graphics
        --path_precision <path_precision>        Number of decimal places to use in path string
        --preset <preset>                        Use one of the preset configs `bw`, `poster`, `photo`
    -l, --segment_length <segment_length>
            Perform iterative subdivide smooth until all segments are shorter than this length

    -s, --splice_threshold <splice_threshold>    Minimum angle displacement (degree) to splice a spline

Downloads

You can download pre-built binaries from Releases.

You can also install the program from source from crates.io/vtracer:

cargo install vtracer

You are strongly advised to not download from any other third-party sources

Usage

./vtracer --input input.jpg --output output.svg

Rust Library

You can install vtracer as a Rust library.

cargo add vtracer

Python Library

Since 0.6, vtracer is also packaged as Python native extensions, thanks to the awesome pyo3 project.

pip install vtracer

In the wild

VTracer is used by the following products (open a PR to add yours):


Smart logo design

Citations

VTracer has since been cited in a few academic papers. Please kindly let us know if you have cited our work:

How did VTracer come about?

The following content is an excerpt from my unpublished memoir.

At my teenage, two open source projects in the vector graphics space inspired me the most: Potrace and Anti-Grain Geometry (AGG).

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.

The plan was to fully develop the vectorizer: to handle color images and output splines. I recruited a very talented intern, @shpun817, to work on VTracer. I grafted the frontend of the video processing engine - the "The Clustering Algorithm" as the pre-processor.

Three months later, we published the first version on Reddit. Out of my surprise, the response of such an underwhelming project was overwhelming.

What's next?

There are several things in my mind:

  1. Path simplification. Implement a post-process filter to the output paths to further reduce the number of splines.

  2. Perfect cut-out mode. Right now in cut-out mode, the shapes do not share boundaries perfectly, but have seams.

  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.

  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.

If you are interested in working on them or willing to sponsor its development, feel free to get in touch.

NPM DownloadsLast 30 Days