ImageTracerJava

repository·master·Indexed 41 days ago

https://github.com/jankovicsandras/imagetracerjava

A Java-based tool for tracing and vectorizing raster images (such as PNG or JPG) into SVG format. It is a port of the JavaScript version and can be used as a standalone CLI program or integrated into Java applications via the ImageTracer class.

Tokens
2.7K
Snippets
3
Records
7
Agent score
50%

What's inside ImageTracerJava

  1. How the ImageTracerJava tracing process works

    master

    ImageTracerJava converts raster images to vector graphics through a multi-step pipeline:

    1. Color quantization: The colorquantization function creates an indexed image from the source.
    2. Layer separation and edge detection: The layering function creates color-specific arrays and calculates edge node types (located at the center of every 4 pixels).
    3. Pathscan: The pathscan function identifies chains of edge nodes to form paths.
    4. Interpolation: The internodes function interpolates edge node path coordinates. Every line segment in the resulting path is assigned one of 8 directions (East, North East, N, NW, W, SW, S, SE).
    5. Tracing: This stage refines the paths into smooth curves:
      • tracepath splits interpolated paths into sequences with two directions.
      • fitseq attempts to fit a straight line between the start and endpoint of a sequence. If the distance error exceeds the threshold, it identifies the point with the greatest error.
      • fitseq then attempts to fit a quadratic spline through that error point.
      • If neither a straight line nor a quadratic spline fits within the error thresholds, the sequence is split in two, and fitseq is called recursively on both parts.
    6. SVG rendering: The final coordinates are converted into SVG Paths via the getsvgstring function.
  2. Include ImageTracer in Java projects

    master

    To use ImageTracer within your Java application:

    1. Add ImageTracer.jar to your build path.
    2. Import jankovicsandras.imagetracer.ImageTracer.
    3. Use the static methods provided by the ImageTracer class.

    Basic Example:

    import jankovicsandras.imagetracer.ImageTracer;
    
    ImageTracer.saveString("output.svg", ImageTracer.imageToSVG("input.jpg", null, null));

    Advanced Example with Options and Palette: Options are passed using a HashMap<String, Float>. The palette is a byte[][] where each inner array represents an RGBA color. Note that signed byte values [-128 .. 127] will be converted to [0 .. 255] during SVG generation.

    import jankovicsandras.imagetracer.ImageTracer;
    import java.util.HashMap;
    
    // Options
    HashMap<String,Float> options = new HashMap<String,Float>();
    options.put("ltres", 1f);
    options.put("qtres", 1f);
    options.put("pathomit", 8f);
    options.put("colorsampling", 1f);
    options.put("numberofcolors", 16f);
    options.put("mincolorratio", 0.02f);
    options.put("colorquantcycles", 3f);
    options.put("scale", 1f);
    options.put("roundcoords", 1f);
    options.put("lcpr", 0f);
    options.put("qcpr", 0f);
    options.put("desc", 1f);
    options.put("viewbox", 0f);
    options.put("blurradius", 0f);
    options.put("blurdelta", 20f);
    
    // Palette (Example: grayscale)
    byte[][] palette = new byte[8][4];
    for(int colorcnt = 0; colorcnt < 8; colorcnt++){
        palette[colorcnt][0] = (byte)( -128 + colorcnt * 32); // R
        palette[colorcnt][1] = (byte)( -128 + colorcnt * 32); // G
        palette[colorcnt][2] = (byte)( -128 + colorcnt * 32); // B
        palette[colorcnt][3] = (byte)127;                    // A
    }
    
    ImageTracer.saveString("output.svg", ImageTracer.imageToSVG("input.jpg", options, palette));
  3. Achieve deterministic tracing output

    master

    By default, ImageTracerJava uses randomization during the color quantization step (K-means clustering). To ensure that the same input image always produces the exact same SVG output, you must eliminate the two sources of randomness: the initial palette generation and the cluster recycling process.

    To achieve deterministic results, use one of the following configuration strategies:

    Strategy A: Use a Custom Palette Provide a predefined palette. This is the most direct way to ensure determinism.

    Strategy B: Disable Sampling and use specific color counts If you are not using a custom palette, set colorsampling to 0 (false) and ensure the number of colors follows one of these rules:

    1. Use fewer than 8 colors (e.g., numberofcolors: 7). This forces a deterministic grayscale palette.
    2. Use a cubic number for numberofcolors (e.g., 8, 27, 64, 125...). This forces a deterministic RGB cubic grid palette.

    Strategy C: Disable Cluster Recycling To prevent the algorithm from randomly generating new cluster centers for small clusters, you must either:

    1. Set colorquantcycles to 1 (disabling repeated clustering).
    2. Set mincolorratio to 0 (disabling the recycling threshold).

    Summary of Deterministic Combinations:

    Custom Palettecolorsamplingmincolorrationumberofcolorscolorquantcycles
    YesN/AN/AN/AN/A
    No00< 8N/A
    No00$n^3$ (e.g. 8, 27)N/A
    No0N/A< 81
    No0N/A$n^3$ (e.g. 8, 27)1
  4. Run ImageTracer as a standalone program

    master

    You can run ImageTracer directly from the command line using the provided JAR file.

    Warning: If you do not specify an outfilename parameter, the program will overwrite the original file with a .svg extension.

    Basic usage:

    java -jar ImageTracer.jar smiley.png

    Usage with options: Pass options as space-separated key-value pairs following the input and output filenames.

    java -jar ImageTracer.jar smiley.png outfilename output.svg ltres 1 qtres 1 pathomit 8 colorsampling 1 numberofcolors 16 mincolorratio 0.02 colorquantcycles 3 scale 1 simplifytolerance 0 roundcoords 1 lcpr 0 qcpr 0 desc 1 viewbox 0 blurradius 0 blurdelta 20
  5. ImageTracer Main API Reference

    master

    The ImageTracer class provides several static methods for converting various image formats into SVG strings. Most methods accept an optional HashMap<String, Float> for configuration and an optional byte[][] for a custom color palette.

    // Main Functions
    String imageToSVG(String filename, HashMap<String,Float> options, byte[][] palette);
    String imageToSVG(BufferedImage image, HashMap<String,Float> options, byte[][] palette);
    String imagedataToSVG(ImageData imgd, HashMap<String,Float> options, byte[][] palette);
    
    IndexedImage imageToTracedata(String filename, HashMap<String,Float> options, byte[][] palette);
    IndexedImage imageToTracedata(BufferedImage image, HashMap<String,Float> options, byte[][] palette);
    IndexedImage imagedataToTracedata(ImageData imgd, HashMap<String,Float> options, byte[][] palette);
    
    // Helper Functions
    void saveString(String filename, String str);
    ImageData loadImageData(String filename);
    ImageData loadImageData(BufferedImage image);
  6. Configure color quantization parameters for determinism

    master

    The following parameters control the non-deterministic behaviors in the color quantization (K-means clustering) process:

    • colorsampling: Determines how the initial palette is created. Setting this to 0 (false) prevents random sampling of the input image.
    • numberofcolors: The target number of colors. If colorsampling is 0, setting this to a value < 8 results in a deterministic grayscale palette. Setting it to a cubic number (e.g., 8, 27, 64...) results in a deterministic RGB cubic grid.
    • mincolorratio: The threshold for 'recycling' clusters. If the ratio of pixels in a cluster is less than this value, the cluster center is regenerated randomly. Setting this to 0 disables recycling.
    • colorquantcycles: The number of quantization cycles. Setting this to 1 prevents the repeated clustering process that triggers recycling.
  7. Configure ImageTracer options

    master

    Options are passed to the API via a HashMap<String, Float>. Use the following keys to control the tracing and rendering process:

    OptionDefaultMeaning
    ltres1fError threshold for straight lines.
    qtres1fError threshold for quadratic splines.
    pathomit8fEdge node paths shorter than this will be discarded for noise reduction.
    colorsampling1fEnable/disable color sampling (1f = on, 0f = off).
    numberofcolors16fNumber of colors to use on palette if palette is not defined.
    mincolorratio0.02fColor quantization will randomize a color if fewer pixels than (total pixels * mincolorratio) have it.
    colorquantcycles3fNumber of times color quantization is repeated.
    blurradius0fSelective Gaussian blur preprocessing radius (1f..5f). 0f is deactivated.
    blurdelta20fRGBA delta threshold for selective Gaussian blur.
    scale1fMultiplier for every coordinate to scale the SVG.
    roundcoords1fRounding decimal places (e.g., 1f rounds to 1 decimal place like 7.3).
    viewbox0fEnable/disable SVG viewBox (1f = on, 0f = off).
    desc1fEnable/disable SVG descriptions (1f = on, 0f = off).
    lcpr0fStraight line control point radius (draws small circles if > 0).
    qcpr0fQuadratic spline control point radius (draws small circles/lines if > 0).