svg_files

Loading and manipulating SVG files

Converting to Strokes

Steps:

  1. Discretize the SVG: Convert all paths (including bezier curves, etc) to a set of discrete points.
  2. Apply SVG Global Transforms: If the SVG contains something like <g transform="(scale:0.5,-0.4)">, apply that to the coordinates.
  3. Rescale: Find the min/max/range on the x and y axes. Subtract min, divide by range to get coords between 0 and 1. Multiply by target_size to get coordinates in a comprehensible range.
def svg_to_strokes(input_fname, target_size=200, total_n=1000, min_n=3):
    # convert all paths to a series of points
    all_strokes = discretize_svg(input_fname, total_n=total_n, min_n=min_n)
    # apply any global SVG transform instructions
    globally_rescaled_strokes = global_svg_transform(all_strokes, input_fname)
    # rescaled to the target image size
    rescaled_strokes = rescale_strokes(globally_rescaled_strokes, target_size)
    return rescaled_strokes

source

svg_to_strokes

 svg_to_strokes (input_fname, target_size=200, total_n=1000, min_n=3)

Discretizing SVG Paths


source

discretize_path

 discretize_path (path, total_n=1000, min_n=3)

source

to_points

 to_points (parsed_path, n)
def discretize_paths(paths, total_n=1000, min_n=3):
    all_strokes = []
    total_length = sum([p.length() for p in paths])
    for p in paths:
        # compute number of points to generate for curr path based on ratio to total path length
        path_n = int(total_n * p.length() / total_length)
        # if number of points is less than the minimum, drop it.
        if path_n < min_n:
            continue

        strokes = discretize_path(p, path_n, min_n=min_n)
        all_strokes.extend(strokes)
    return all_strokes


def discretize_svg(input_fname, **kwargs):
    paths, attributes, svg_attributes = svgpathtools.svg2paths(
        input_fname, return_svg_attributes=True
    )
    all_strokes = discretize_paths(paths, **kwargs)
    return all_strokes

source

discretize_svg

 discretize_svg (input_fname, **kwargs)

source

discretize_paths

 discretize_paths (paths, total_n=1000, min_n=3)

Rescale


source

rescale_strokes

 rescale_strokes (all_strokes, target_size)

Global Transforms


source

build_transforms

 build_transforms (tstr)

source

parse_transform_instruction

 parse_transform_instruction (item)

source

svg_to_transforms

 svg_to_transforms (svgroot)

source

parse_svg

 parse_svg (input_file)

Parse the SVG XML, to allow extracting individual elements


source

global_svg_transform

 global_svg_transform (all_strokes, input_fname)