rekha

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 14, 2026 License: AGPL-3.0 Imports: 25 Imported by: 0

README

Rekha

Rekha

Raster to clean SVG. Pure Go. Your image never leaves your machine.
Try it in your browser

CI Go Reference AGPL-3.0 Commercial licence available Go 1.26 Playground

Rekha converts raster images (PNG, JPEG, GIF) into editable SVG. One codebase provides a Go library, a command-line tool, an HTTP service and a WebAssembly build for the browser. It has no cgo and no dependency beyond golang.org/x/image, and it is a clean-room implementation, dual-licensed: AGPL-3.0 for open source, a commercial licence for everything else.

Contents

Features

  • Curve refinement. --refine optimises every Bézier against the image's anti-aliasing (after Yang et al., 2016), placing edges to a fraction of a pixel. On anti-aliased test images this adds 5–20 dB PSNR at about the same node count.
  • Geometric primitives. Circles become four exact arcs, rounded rectangles four lines and four arcs with one shared radius, rotated rectangles four nodes; half-discs, pie wedges and concentric bands come out as arcs with corner ends, and sharp corners are single nodes. The result edits cleanly in Illustrator, Figma or Inkscape.
  • Gradient fills. --gradients merges colour bands that follow one ramp into a single region filled by a multi-stop <linearGradient>, joined across bends, or by a <radialGradient> when the bands run round a centre, with specks inside a ramp absorbed. A region shaded more than one way (a sphere with an off-centre highlight, a rim light) is painted in layers: a base gradient under up to two translucent radial gradients that fade by stop-opacity, as an illustrator draws it. A 16-megapixel illustration drops from 155 flat paths at 36.7 dB to 82 paths at 39.8 dB with 60 % fewer bytes; flat art is byte-identical with the option on.
  • Clean colour edges. Anti-aliased pixels between two colours are recognised as their mixture and absorbed, rather than surviving as slivers of a third colour.
  • Three presets. bw for line art and scans, poster for flat-colour artwork, photo for photographs and soft shading. Every parameter can be overridden.
  • Shared boundaries. Cutout output fits each boundary between two shapes once, so neighbours carry identical coordinates; stacked output layers shapes with no seams. --stroke seals hairline seams in either mode.
  • Small text survives. On the small-glyphs fixture Rekha reaches 32.26 dB with 86 nodes against Potrace's 32.22 dB with 107.
  • Fast and deterministic. 0.1–0.25 s per 256×256 image with refinement; 1.1 s plain or 4.6 s refined for a 3.4-megapixel logo on a laptop. The same input gives the same SVG on one core or eight, arm64 or amd64.
  • Progress reporting. The library reports each stage and its count through a callback; the WebAssembly API and the demo page expose the same.
  • SVG, PDF and EPS. One trace, three files, from the same curves and gradients: --format pdf or an output ending in .pdf or .eps, in the playground too, and from an SVG Rekha wrote earlier (rekha.Convert). The PDF is one page at 0.75 pt per pixel with axial and radial shadings and soft masks for the translucent overlays; the EPS is Level 3 with shfill.
  • Runs anywhere Go runs. A single static binary, a capped HTTP service, or the browser via WebAssembly: images traced in the browser are never uploaded.

Installation

brew tap vexyl-ai/tap && brew trust vexyl-ai/tap && brew install --cask rekha   # macOS and Linux (brew trust: Homebrew 7 and later)
scoop bucket add vexyl-ai https://github.com/vexyl-ai/scoop-bucket && scoop install rekha   # Windows
docker run --rm -p 8080:8080 ghcr.io/vexyl-ai/rekha   # HTTP API in a container

Linux package repositories at vexyl-ai.github.io/packages, signed, rebuilt on every release: add one once, then install and upgrade with the system package manager.

# Debian, Ubuntu
sudo install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://vexyl-ai.github.io/packages/gpg.key | sudo tee /etc/apt/keyrings/vexyl-ai.asc > /dev/null
echo "deb [signed-by=/etc/apt/keyrings/vexyl-ai.asc] https://vexyl-ai.github.io/packages/apt stable main" | sudo tee /etc/apt/sources.list.d/vexyl-ai.list
sudo apt update && sudo apt install rekha

# Fedora, RHEL, openSUSE
sudo curl -fsSL https://vexyl-ai.github.io/packages/rpm/vexyl-ai.repo -o /etc/yum.repos.d/vexyl-ai.repo
sudo dnf install rekha

Prebuilt binaries for Linux, macOS, Windows and FreeBSD (amd64 and arm64) are on the releases page, as archives and as .deb, .rpm, .apk and Arch packages. Each archive holds rekha and rekha-serve; unpack and put them on your PATH.

sudo dpkg -i rekha_*_linux_amd64.deb        # Debian, Ubuntu
sudo rpm -i rekha_*_linux_amd64.rpm         # Fedora, RHEL, openSUSE
sudo apk add --allow-untrusted rekha_*_linux_amd64.apk   # Alpine
sudo pacman -U rekha_*_linux_amd64.pkg.tar.zst           # Arch

macOS may refuse an unsigned downloaded binary on first run; xattr -d com.apple.quarantine rekha clears that.

With Go 1.26 or later:

go install github.com/vexyl-ai/rekha/cmd/rekha@latest

Or from a checkout:

git clone https://github.com/vexyl-ai/rekha.git
cd rekha
make build        # bin/rekha and bin/rekha-serve
make test         # unit tests and goldens

Releases are built by .github/workflows/release.yml with GoReleaser when a v* tag is pushed: binaries, packages, the Homebrew cask in vexyl-ai/homebrew-tap, the Scoop manifest in vexyl-ai/scoop-bucket, and the image at ghcr.io/vexyl-ai/rekha; it then dispatches packages.yml, which signs the deb and rpm files and rebuilds the apt and yum repositories in vexyl-ai/packages (PACKAGES_GPG_KEY secret; scripts/packages-repo.sh does the work). make release-check builds the binaries and packages into dist/ locally.

Quick start

rekha image.png                                   # writes image.svg
rekha -o out.svg --threshold auto scan.png        # black and white, automatic threshold
rekha --preset poster logo.png                    # flat colours, stacked layers
rekha --preset poster --refine logo.png           # plus curve refinement and primitives
rekha --auto logo.png                             # try four settings, keep the closest to the image
rekha --preset photo --gradients artwork.jpg      # smooth shading as gradient fills
rekha --preset poster --palette "#000000,#ff0000,#ffffff" logo.png
rekha --preset poster --hierarchical cutout --stroke 0.5 logo.png
rekha --mode polygon - < in.png > out.svg         # stdin to stdout
rekha -o logo.pdf --preset poster logo.png        # PDF from the extension
rekha --format eps --preset photo --gradients artwork.jpg   # artwork.eps
rekha -o logo.pdf logo.svg                        # an SVG Rekha wrote, edited or not, to PDF

Exit codes: 0 success, 1 usage error, 2 a trace failed (remaining inputs are still processed).

Options

--preset bw|poster|photo seeds every default; any flag given on the command line overrides it.

--auto ignores the tracing flags and races four candidates instead: poster at tolerance 0.06, poster at 0.04 with gradients, photo with gradients and a speckle filter of 2, and bw with the automatic threshold, each with --refine. Every candidate is rendered by a rasteriser built in and scored against the image (PSNR over white, the benchmark's measure), and the closest wins; a --palette adds a fifth candidate fixed to it. On a mixed set of twenty logos, cartoons and renders the race scored 1.7 dB above a fixed poster-with-gradients setting on average and fell below it on one image, by half a decibel; it costs four traces, run at once when memory allows (all four up to about four megapixels, two at eight, one at sixteen). Output flags (--path-precision, --stroke, --no-mark, --format) still apply.

Colour

Flag Default Description
--threshold 0..1|auto 0.5 bw only: cut-off between black and white; auto uses Otsu's method
--turn-policy minority bw only: how a 2×2 checkerboard connects (minority, majority, black, white)
--color-tolerance 0..1 0.08 / 0.04 OKLab distance at which colours merge (poster / photo)
--max-colors N 0 Palette cap; 0 lets the tolerance decide
--palette "#rrggbb,…" Fixed palette, up to 256 entries
--color-precision N 6 Bits per channel in the quantiser
--filter-speckle N 4 / 16 Drop components below N pixels (poster / photo)
--gradients off Colour presets: merge bands that follow one ramp into a <linearGradient> fill, a <radialGradient> when they run round a centre, or a base gradient under translucent layers (radial or linear, fading either way) when the region is shaded more than one way
--gradient-tolerance 0..1 0.03 RMS error a ramp may leave, in sRGB units (about 8/255)

Curves

Flag Default Description
--mode pixel|polygon|spline spline Output geometry
--simplify px 0.75 Polygon simplification tolerance
--corner-threshold deg 60 Angle above which a vertex is a corner
--fit-tolerance px 1.0 / 1.5 Maximum curve error in the plain fit (bw,poster / photo)
--refine off Optimise curves against the anti-aliasing; replaces recognised circles, arcs, shared radii and rectangles when the rendered error rises by no more than 2 %
--refine-passes N 3 Optimiser sweeps (1–10)

Output

Flag Default Description
--hierarchical stacked|cutout cutout / stacked Shapes with holes sharing one boundary curve, or layered shapes (bw / colour presets)
--stroke px 0 Stroke each shape in its own fill to seal hairline seams when viewed enlarged (0–4; --cutout-stroke is accepted as an alias)
--path-precision N 2 Decimals in path data
--scale 0.25..8 1 The image is this many times the size the output is for: the SVG's width and height are the image size divided by it with the viewBox at image size, and a PDF or EPS page is sized the same way. For an image upscaled before tracing to keep thin lines
--format from the output extension, else svg Output format: svg, pdf or eps. An input ending in .svg must be one Rekha wrote; it is converted rather than traced, so a file edited in the playground can still become a PDF. PDF and EPS are written from the same paths and gradients at 0.75 pt per pixel; PDF keeps every gradient (translucent overlay layers through soft masks), EPS has no transparency and leaves those overlays out
--no-mark off Leave out the generator mark: by default the root carries data-generator="rekha <version>" and a comment names Rekha and this repository; neither changes how the image renders
-o, --output <input>.svg Output file, or - for stdout

In stacked output the white page is omitted (near-white shapes at depth 0 holding at least half the depth-0 area), so transparent input stays transparent.

Library

package main

import (
	"image/png"
	"os"

	"github.com/vexyl-ai/rekha"
)

func main() {
	f, _ := os.Open("logo.png")
	img, _ := png.Decode(f)

	o := rekha.PresetOptions(rekha.PresetPoster)
	o.Refine.Enabled = true
	o.Progress = func(stage string, done, total int) { /* quantise, label, …, curves */ }

	res, err := rekha.Trace(img, o)
	if err != nil {
		panic(err)
	}
	out, _ := os.Create("logo.svg")
	defer out.Close()
	res.WriteSVG(out, o)
}

Segment and Finish split the work so a cached segmentation can be re-fitted with new curve options; TraceReader decodes PNG, JPEG or GIF from an io.Reader. See the package documentation.

Options given as text, the way the HTTP API and the playground take them, parse with the apiopts package: apiopts.Parse reads a JSON object and apiopts.FromStrings a map of string fields, both keyed by the CLI flag names in camelCase, seeded by the preset exactly as the CLI and validated with the field named in every error.

Regions decided elsewhere, by a segmentation model, a matte or a hand selection, go in through Options.ExternalMasks. Each Mask carries one coverage byte per pixel and replaces the quantiser's verdict where it covers the image: a flat fill of its own, the mean of its pixels when Fill is left zero, or nothing at all with Cut, which drops the region as if it were a transparent page. Soft edges in the coverage reach the refinement as anti-aliasing, so a matte's feathered outline is traced as a clean curve through it.

o.ExternalMasks = []rekha.Mask{
	{Coverage: background, Cut: true},       // from a matting model
	{Coverage: subject, Fill: color.NRGBA{}}, // mean colour of the subject
}

Browser and WebAssembly

The playground is hosted at vexyl-ai.github.io/rekha/demo behind the product page at vexyl-ai.github.io/rekha, both rebuilt from main by .github/workflows/pages.yml on every push. To run it locally:

make serve      # builds web/demo/rekha.wasm and serves the site on http://localhost:8080/ (playground at /demo/)

The demo page traces entirely in a Web Worker: drop, paste or choose an image, adjust the controls, compare source and SVG with a wipe, zoom and pan the canvas (ctrl/⌘ + wheel or pinch, drag, double-click, toolbar, keys + - 0 1), watch the progress bar, tidy the result (click a shape to select it, shift-click to add, double-click to take every shape of that colour; Delete removes it, the colour swatch repaints it with its gradient shading kept, Remove background drops the page behind the art, ⌘Z and ⇧⌘Z undo and redo), and download the result as SVG, PDF or EPS. Nothing is uploaded.

The WebAssembly module exposes segment, finish, trace and free on a global rekha object, each with an optional progress callback. The API, worker protocol and embedding notes are in docs/wasm.md.

HTTP API

go run ./cmd/rekha-serve -static web
curl -F image=@logo.png -F preset=poster -F refine=true localhost:8080/v1/trace > logo.svg

POST /v1/trace accepts multipart or a raw image/* body with options as fields or query parameters, and returns image/svg+xml. The server caps request bytes, decoded pixels, wall time, concurrency and queue length. Details in docs/server.md.

Quality and benchmarks

All numbers in this file are produced by make test and make bench; fixtures and commands are in the repository.

Case Result
Anti-aliased synthetics, --refine +5–20 dB PSNR over the plain fit at about the same node count
Small glyphs 32.26 dB, 86 nodes (Potrace: 32.22 dB, 107 nodes)
3.4-megapixel colour logo, --preset poster 14 paths; PSNR level with VTracer (28.95 vs 28.98 dB), white counters kept white
16-megapixel illustration, --preset photo --gradients 155 → 82 paths, 36.7 → 39.8 dB, 60 % fewer bytes
4-megapixel browser mark, --preset photo --gradients 33 paths at 36.3 dB with layered gradients (flat bands: 31 paths at 34.5 dB), half the bytes; the globe one smooth region, seams between gradients smooth
WebAssembly median 4.5× one-core native; 1.2 MB gzipped

Recorded baselines: bench/results/. Methodology and reference-tool comparison: docs/benchmark.md.

Compared with Adobe Express

Three logos, each a 2048-pixel PNG with a transparent background, traced by Rekha (--preset photo --gradients, defaults otherwise) and converted by Adobe Express's image-to-SVG tool (export of 2026-11-11). Both outputs are rendered back at the source size with librsvg and scored against the source over the logo's opaque pixels, so neither tool is charged for how it treats the transparent background. Higher PSNR is closer to the source.

Logo Rekha Adobe Express
Browser mark (radial shading, translucent layers) 33 paths, 32 kB, 34.8 dB 197 paths, 325 kB, 28.7 dB
Letter G (concentric ramps) 16 paths, 14 kB, 32.6 dB 49 paths, 78 kB, 24.0 dB
Ball (flat colours, one highlight) 5 paths, 4 kB, 33.3 dB 5 paths, 12 kB, 26.6 dB

Rekha fits shading as SVG gradients (13 on the browser mark); Adobe Express cuts shading into flat cells, which shows as tiling on anything that fades and multiplies the paths and bytes. On flat art the two agree on the shapes and differ in curve economy.

Numbers and strips: bench/results/2026-11-11-adobe-express.md. Vector Magic and Vectorizer.AI are scored the same way when their outputs are placed under bench/reference/ (see docs/benchmark.md).

Limitations

  • Photographs posterise into colour bands; --gradients smooths shading that runs along one direction, out from one centre, or in up to two translucent layers over a base, but shading with more structure than that (a third light, a texture) stays banded. An AI pre-pass is planned (roadmap phase 6).
  • Cutout output shares boundaries exactly, yet most viewers anti-alias each shape separately and let the page show faintly through shared edges at 1:1. Stacked output is therefore the default.
  • Comparisons against Vector Magic and Vectorizer.AI are produced only when their outputs are placed under bench/reference/ (see docs/benchmark.md).

Provenance

Rekha is written from published algorithms, not from existing tracer code:

  • Pipeline design after VTracer's published linear pipeline (MIT / Apache-2.0).
  • Curve fitting after Schneider, An Algorithm for Automatically Fitting Digitized Curves, Graphics Gems, 1990.
  • Refinement after Yang et al., Effective Clipart Image Vectorization Through Direct Optimization of Bezigons, IEEE TVCG 2016.

It contains no code derived from Potrace or any other GPL-licensed tracer; Potrace and VTracer are used only as black-box binaries in the benchmark harness. The clean-room rule is in CONTRIBUTING.md. Every commit carries a DCO sign-off.

Documentation

Author

Rekha is written and maintained by Anil Mathew (LinkedIn).

Package documentation: pkg.go.dev/github.com/vexyl-ai/rekha.

Licence

Dual-licensed.

  • AGPL-3.0 for open source: free to use, change, ship and host, provided what you build with it is released under the AGPL-3.0 too. See LICENSE and NOTICE.
  • Commercial licence for products, services and internal tools that will not release their source. It funds the development of the open version, and it is where the CAD and cutter exports (DXF, HPGL, G-code, Illustrator, layered PDF) will ship; the open build writes SVG, PDF and EPS. See COMMERCIAL.md.

Versions published before this change (up to commit fe2e104) remain under the Apache License 2.0 they were released with.

Documentation

Overview

Package rekha traces raster images into SVG.

Index

Constants

View Source
const (
	TurnMinority = contour.Minority
	TurnMajority = contour.Majority
	TurnBlack    = contour.Black
	TurnWhite    = contour.White
)

Turn policies.

Variables

This section is empty.

Functions

func Auto added in v0.2.0

func Auto(img image.Image, o Options) (*Result, Options, error)

Auto traces img under each of a few candidate option sets and keeps the one whose rendering is closest to the image: PSNR over white, the same measure the benchmarks use, from a renderer built in. It returns that result and the options that produced it, so the caller can write the SVG with them or run them again. The candidates, all spline mode with refinement, are the poster preset at tolerance 0.06; poster at 0.04 with gradients; photo with gradients, speckle filter 2; and bw with the automatic threshold. A palette in o adds a fifth, poster at 0.06 fixed to that palette. The candidates take o's output options (PathPrecision, Stroke, NoMark, Format, Scale, ExternalMasks, Progress) and nothing else of it. Auto costs the four or five traces and their renderings. They run at once as far as memory allows (a trace keeps about a hundred bytes a pixel: all of them on an image up to four megapixels, two on eight, one on sixteen) and never more than GOMAXPROCS, so the WebAssembly build runs them one after another; Progress sees stage "auto" counting candidates round the stages of each, interleaved when they run together. The choice does not depend on the scheduling: a tie goes to the earlier candidate.

func Convert added in v0.2.0

func Convert(r io.Reader, w io.Writer, o Options) error

Convert reads an SVG Rekha wrote, edited or not (paths removed, fills changed, gradients dropped), and writes it in o.Format with the precision the file carries. The mark follows the SVG's own, or Rekha's current version when it has none; o.NoMark removes it. SVG from other tools is refused: the reader knows only Rekha's dialect.

func Version

func Version() string

Version is the module version this binary was built from, as Go records it: a tag such as v1.2.0 when installed with go install, or "dev" from a source checkout or when the build carries no version.

Types

type Format added in v0.2.0

type Format string

Format is an output file format. The SVG is the reference: the PDF and the EPS are written from the same paths and gradients at 0.75 points per pixel (96 pixels and 72 points to the inch). PDF keeps every gradient, translucent overlays through soft masks; EPS has no transparency and leaves translucent overlay layers out.

const (
	FormatSVG Format = "svg"
	FormatPDF Format = "pdf"
	FormatEPS Format = "eps"
)

func ParseFormat added in v0.2.0

func ParseFormat(s string) (Format, error)

ParseFormat reads a format name, case-insensitively, with or without a leading dot; "" is SVG.

type Hierarchical

type Hierarchical string

Hierarchical selects how colour shapes are layered in the output.

const (
	// HierarchicalStacked paints every shape's outer contour, larger and
	// deeper shapes first, so each one covers what it encloses: no holes,
	// no seams between abutting colours.
	HierarchicalStacked Hierarchical = "stacked"
	// HierarchicalCutout paints each shape with its holes cut out, as
	// Phase 1 does for black on white.
	HierarchicalCutout Hierarchical = "cutout"
)

Layering modes.

type Mask added in v0.2.0

type Mask struct {
	Coverage []uint8
	Fill     color.NRGBA
	Cut      bool
}

Mask is one region supplied through Options.ExternalMasks. Coverage holds one value per pixel of the image, row-major: 0 outside, 255 inside, between on a soft edge. A pixel covered by half or more takes the mask's colour; a softer edge is kept as the pixel's second colour and blend, which the refinement reads as coverage. Fill is the region's colour; the zero value takes the mean of the pixels it covers. Cut drops the region instead: its pixels become the page and are not drawn. Masks apply in order, so a later one wins where two overlap.

type Mode

type Mode string

Mode selects the output geometry.

const (
	ModePixel   Mode = "pixel"
	ModePolygon Mode = "polygon"
	ModeSpline  Mode = "spline"
)

Output modes.

type Options

type Options struct {
	Preset         Preset
	Mode           Mode
	FilterSpeckle  int // pixels; 0..1024
	ColorPrecision int // bits; 1..8
	PathPrecision  int // decimals; 0..8
	MaxColors      int // palette cap; 0 = as many as ColorTolerance needs, up to 256

	Threshold         float64    // 0..1; pixels darker than this are foreground
	AutoThreshold     bool       // choose Threshold with Otsu's method
	TurnPolicy        TurnPolicy // checkerboard resolution
	SimplifyTolerance float64    // px; 0..10
	CornerThreshold   float64    // degrees; 0..180
	FitTolerance      float64    // px; 0.01..10

	ColorTolerance float64       // OKLab distance 0..1 at which colours merge (white to black is 1)
	Palette        []color.NRGBA // fixed palette, at most 256 distinct entries; empty = quantise
	Hierarchical   Hierarchical
	// ExternalMasks are regions the caller has already decided on (a
	// segmentation model's objects, a matte, a selection) that replace
	// the quantiser's verdict where they cover the image. See Mask.
	ExternalMasks []Mask

	Refine RefineOptions // spline mode only
	Stroke float64       // px, 0..4, default 0; polygon/spline colour shapes are stroked in their fill to hide hairline seams between fitted edges when viewed enlarged
	// Deprecated: use Stroke. CutoutStroke is read when Stroke is 0.
	CutoutStroke float64

	Gradients         bool    // colour presets: merge adjacent bands that form one linear ramp into a gradient fill
	GradientTolerance float64 // 0..1, default 0.03; RMS sRGB distance (channels 0..1) a ramp may leave

	// NoMark leaves out the generator mark: by default the SVG root
	// carries data-generator="rekha <version>" and a comment naming
	// Rekha and its repository. Neither changes how the image renders.
	NoMark bool

	// Format is the file format Write produces: SVG (the zero value),
	// PDF or EPS. WriteSVG, WritePDF and WriteEPS ignore it.
	Format Format

	// Scale says the image is this many times the size the output is
	// for: the SVG is written at image size ÷ Scale with the viewBox at
	// image size, and a PDF or EPS page is sized the same way. Zero
	// means 1; otherwise 0.25 to 8. A caller that upscales an image
	// before tracing (to keep thin lines) sets the factor here.
	Scale float64

	// Auto makes Trace and TraceReader race the candidate option sets
	// of Auto and keep the one closest to the image, ignoring every
	// field of these options but the output ones Auto lists. Segment
	// does not read it.
	Auto bool

	// Progress, when set, is told how far Segment and Finish have got:
	// stage names quantise, label, ramps (Segment; no count) and
	// outlines, nest, edges, refine, curves (Finish; done of total, total
	// 0 when a stage has no count). Under parallel work it may be called from several
	// goroutines at once and counts may arrive out of order. It must be
	// quick: a stage reports at most once per whole percent.
	Progress Progress
}

Options controls a trace. One struct backs the CLI, the HTTP API and the WebAssembly entry point; Validate is the single source of truth for ranges.

func DefaultOptions

func DefaultOptions() Options

DefaultOptions returns the bw/spline defaults, PresetOptions(PresetBW).

func PresetOptions

func PresetOptions(p Preset) Options

PresetOptions returns the defaults for preset p. An unknown preset returns the bw defaults with Preset set to p, which Validate rejects.

func (Options) Validate

func (o Options) Validate() error

type Preset

type Preset string

Preset selects a named bundle of defaults.

const (
	PresetBW     Preset = "bw"
	PresetPoster Preset = "poster"
	PresetPhoto  Preset = "photo"
)

Presets.

type Progress

type Progress func(stage string, done, total int)

Validate checks every field in struct order and returns the first failure as a *ValidationError, or nil. Progress receives Options.Progress reports.

type RefineOptions

type RefineOptions struct {
	Enabled    bool
	Sweeps     int            // 1..10; passes over the contour's pieces
	MaxIter    int            // 1..200; L-BFGS iterations per piece
	Weights    refine.Weights // prior weights, finite and non-negative
	MergeSplit bool           // merge smooth joints, split bad fits
	Primitives bool           // replace near-circles by exact circles
}

RefineOptions controls the Phase 3 refinement of spline output: each fitted contour is optimised against the input's anti-aliasing (Yang et al. 2016), its segments merged and split, and circles recognised.

type Result

type Result struct {
	Width, Height int
	Gradients     []svg.LinearGradient
	Radials       []svg.RadialGradient
	Paths         []svg.Path
}

Result is a traced image: filled paths in pixel coordinates, and the gradients (Options.Gradients) that some of them are filled with.

func Trace

func Trace(img image.Image, o Options) (*Result, error)

Trace vectorises img according to o, or, when o.Auto is set, under the candidate Auto picks.

func TraceReader

func TraceReader(r io.Reader, o Options) (*Result, error)

TraceReader decodes an image (PNG, JPEG or GIF) and traces it.

func (*Result) Write added in v0.2.0

func (r *Result) Write(w io.Writer, o Options) error

Write writes r in o.Format (SVG when unset) with o.PathPrecision decimals, marked with Rekha's name and version unless o.NoMark.

func (*Result) WriteEPS added in v0.2.0

func (r *Result) WriteEPS(w io.Writer, o Options) error

WriteEPS writes r as an EPS file; see Format.

func (*Result) WritePDF added in v0.2.0

func (r *Result) WritePDF(w io.Writer, o Options) error

WritePDF writes r as a one-page PDF; see Format.

func (*Result) WriteSVG

func (r *Result) WriteSVG(w io.Writer, o Options) error

WriteSVG writes r as an SVG document with o.PathPrecision decimals, marked with Rekha's name and version unless o.NoMark is set.

type Segmentation

type Segmentation struct {
	Width, Height int
	Palette       []color.NRGBA // final palette after cleanup; bw: {white, black}
	Labels        []uint8       // palette index per pixel
	Second        []uint8       // second-nearest palette index per pixel
	Blend         []uint8       // 128..255, share of Labels' colour in the pixel
	// Ramps, when Options.Gradients merged bands, has one entry per
	// palette index: the linear ramp that fills it, or nil for a flat
	// colour. Nil altogether when no option asked for ramps.
	Ramps []*gradient.Ramp
	// contains filtered or unexported fields
}

Segmentation is an image reduced to a palette and a label per pixel: the input to Finish, and the hand-off point for callers that quantise themselves.

func Segment

func Segment(img image.Image, o Options) (*Segmentation, error)

Segment reduces img to a Segmentation under o. The bw preset thresholds grey exactly as Phase 1 and labels foreground 1 on a {white, black} palette; the colour presets quantise in OKLab (or snap to o.Palette), then despeckle, absorb anti-aliasing slivers and compact the palette.

func (*Segmentation) Finish

func (s *Segmentation) Finish(o Options) (*Result, error)

Finish traces every colour of s, orders the shapes (stacked: nesting depth, outer contours only, consecutive paths of one colour sharing a <path>; cutout: colour then scan order, holes cut out, one path per shape), fits each contour under o.Mode and returns the paths with their palette fills. White shapes at depth 0 are left out.

type TurnPolicy

type TurnPolicy = contour.TurnPolicy

TurnPolicy decides how a boundary walk resolves a 2×2 checkerboard.

type ValidationError

type ValidationError struct {
	Field string
	Msg   string
}

ValidationError reports the first invalid field.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Directories

Path Synopsis
Package apiopts turns option fields given as text into rekha.Options, for the HTTP API, the playground and any embedder: a JSON object (Parse) or string fields (FromStrings, for an HTTP form or query), keyed by the CLI flag names in camelCase and seeded by the preset exactly as the CLI does.
Package apiopts turns option fields given as text into rekha.Options, for the HTTP API, the playground and any embedder: a JSON object (Parse) or string fields (FromStrings, for an HTTP form or query), keyed by the CLI flag names in camelCase and seeded by the preset exactly as the CLI does.
cmd
rekha command
Command rekha traces raster images into SVG.
Command rekha traces raster images into SVG.
rekha-bench command
Command rekha-bench runs reference tracers over the corpus and scores them.
Command rekha-bench runs reference tracers over the corpus and scores them.
rekha-serve command
Command rekha-serve is an HTTP front for Rekha: POST /v1/trace returns an SVG; caps on bytes, pixels, time, concurrency and queue keep one client from exhausting the host.
Command rekha-serve is an HTTP front for Rekha: POST /v1/trace returns an SVG; caps on bytes, pixels, time, concurrency and queue keep one client from exhausting the host.
rekha-wasm command
Command rekha-wasm is the WebAssembly build of Rekha: it installs a global "rekha" object with segment, finish, free, trace and version.
Command rekha-wasm is the WebAssembly build of Rekha: it installs a global "rekha" object with segment, finish, free, trace and version.
internal
bench
Package bench runs external tracers as black boxes over a corpus and scores their SVG output against the input pixels.
Package bench runs external tracers as black boxes over a corpus and scores their SVG output against the input pixels.
bitmap
Package bitmap holds a packed 1-bit image and the grey/threshold steps that produce it from a decoded picture.
Package bitmap holds a packed 1-bit image and the grey/threshold steps that produce it from a decoded picture.
cli
Package cli holds helpers shared by the rekha command-line entry point.
Package cli holds helpers shared by the rekha command-line entry point.
colour
Package colour converts sRGB to the OKLab perceptual colour space, in which the quantiser measures colour differences.
Package colour converts sRGB to the OKLab perceptual colour space, in which the quantiser measures colour differences.
contour
Package contour walks the boundaries between foreground and background pixels along pixel edges ("cracks") and groups the resulting loops into shapes with holes.
Package contour walks the boundaries between foreground and background pixels along pixel edges ("cracks") and groups the resulting loops into shapes with holes.
corpus
Package corpus generates the deterministic synthetic test images used by the benchmark harness.
Package corpus generates the deterministic synthetic test images used by the benchmark harness.
corpus/gen command
Command gen writes the synthetic corpus as PNG files.
Command gen writes the synthetic corpus as PNG files.
export
Package export writes a traced document as PDF or EPS, from the same paths and gradients the SVG writer uses, so the three outputs agree.
Package export writes a traced document as PDF or EPS, from the same paths and gradients the SVG writer uses, so the three outputs agree.
fit
Package fit turns dense boundary points into cubic Bézier segments using the least-squares scheme described by Schneider in Graphics Gems (1990).
Package fit turns dense boundary points into cubic Bézier segments using the least-squares scheme described by Schneider in Graphics Gems (1990).
geom
Package geom holds the lattice and vector primitives shared by the contour, simplification and fitting stages.
Package geom holds the lattice and vector primitives shared by the contour, simplification and fitting stages.
gradient
Package gradient merges adjacent quantised colour bands that together form one linear colour ramp, and fits each merged region a two-stop linear gradient in pixel coordinates.
Package gradient merges adjacent quantised colour bands that together form one linear colour ramp, and fits each merged region a two-stop linear gradient in pixel coordinates.
latency
Package latency times Segment and Finish per preset over a directory of images and prints a markdown table; the same code runs natively and under WebAssembly (go_js_wasm_exec maps os to Node's fs), so the two tables compare like for like.
Package latency times Segment and Finish per preset over a directory of images and prints a markdown table; the same code runs natively and under WebAssembly (go_js_wasm_exec maps os to Node's fs), so the two tables compare like for like.
metrics
Package metrics scores traced output: pixel fidelity and SVG size.
Package metrics scores traced output: pixel fidelity and SVG size.
par
Package par runs independent work items on GOMAXPROCS workers.
Package par runs independent work items on GOMAXPROCS workers.
planar
Package planar builds the shared-boundary map of a label image: the crack loops of every colour, cut at the vertices where three colours meet (or two meet diagonally) into arcs, each arc shared by the two regions on its sides.
Package planar builds the shared-boundary map of a label image: the crack loops of every colour, cut at the vertices where three colours meet (or two meet diagonally) into arcs, each arc shared by the two regions on its sides.
quant
Package quant builds a colour palette for an image and maps its pixels onto it.
Package quant builds a colour palette for an image and maps its pixels onto it.
rasttest
Package rasttest is a test-only nonzero-winding scanline filler, the rule SVG applies by default.
Package rasttest is a test-only nonzero-winding scanline filler, the rule SVG applies by default.
refine
Package refine moves the control points of fitted curves to match the input's anti-aliasing: a bezigon is rasterised by exact area coverage and optimised against a soft coverage mask with the priors of Yang et al.
Package refine moves the control points of fitted curves to match the input's anti-aliasing: a bezigon is rasterised by exact area coverage and optimised against a soft coverage mask with the priors of Yang et al.
region
Package region cleans a per-pixel label map before tracing: specks and anti-aliasing slivers are merged into their neighbours and the palette is compacted.
Package region cleans a per-pixel label map before tracing: specks and anti-aliasing slivers are merged into their neighbours and the palette is compacted.
render
Package render rasterises a traced document the way a browser would, near enough to score it against the source: antialiased, nonzero winding, flat and gradient fills in user space with pad spread, a translucent stop composited over what is already painted.
Package render rasterises a traced document the way a browser would, near enough to score it against the source: antialiased, nonzero winding, flat and gradient fills in user space with pad spread, a translucent stop composited over what is already painted.
svg
Package svg writes traced paths as a compact, deterministic SVG document.
Package svg writes traced paths as a compact, deterministic SVG document.
Package server puts the tracer behind HTTP with caps so one client cannot exhaust the host: POST /v1/trace returns an SVG, PDF or EPS.
Package server puts the tracer behind HTTP with caps so one client cannot exhaust the host: POST /v1/trace returns an SVG, PDF or EPS.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL