Documentation
¶
Overview ¶
Package rekha traces raster images into SVG.
Index ¶
- Constants
- func Auto(img image.Image, o Options) (*Result, Options, error)
- func Convert(r io.Reader, w io.Writer, o Options) error
- func Version() string
- type Format
- type Hierarchical
- type Mask
- type Mode
- type Options
- type Preset
- type Progress
- type RefineOptions
- type Result
- type Segmentation
- type TurnPolicy
- type ValidationError
Constants ¶
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
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 but never called from two goroutines at once. The choice does not depend on the scheduling: a tie goes to the earlier candidate.
func Convert ¶ added in v0.2.0
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.
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.
func ParseFormat ¶ added in v0.2.0
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
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 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
// Flatten merges adjacent colours that differ in lightness only
// (shades of one hue, within 0.12 of OKLab lightness) into one flat
// colour after cleanup: a region's shading collapses into its
// colour while a hue step stays an edge. The flat preset sets it;
// a fixed Palette is never flattened.
Flatten bool
// FlatLightness is how far apart in OKLab lightness (0..1) two
// adjacent shades of one hue may be and still merge under Flatten;
// default 0.12. Lower keeps more of the quantiser's shade steps as
// their own flat tones (0.05 doubles a cartoon's fills), higher
// merges more; a shade softer than ColorTolerance is gone before
// Flatten runs.
FlatLightness float64
// 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, flatten, 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 ¶
PresetOptions returns the defaults for preset p. An unknown preset returns the bw defaults with Preset set to p, which Validate rejects.
type Progress ¶
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 ¶
Trace vectorises img according to o, or, when o.Auto is set, under the candidate Auto picks.
func TraceReader ¶
TraceReader decodes an image (PNG, JPEG or GIF) and traces it.
func (*Result) Write ¶ added in v0.2.0
Write writes r in o.Format (SVG when unset) with o.PathPrecision decimals, marked with Rekha's name and version unless o.NoMark.
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 ¶
ValidationError reports the first invalid field.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
Source Files
¶
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. |
