def svg_to_strokes(input_fname, target_size=200, total_n=1000, min_n=3):
# convert all paths to a series of points
= discretize_svg(input_fname, total_n=total_n, min_n=min_n)
all_strokes # apply any global SVG transform instructions
= global_svg_transform(all_strokes, input_fname)
globally_rescaled_strokes # rescaled to the target image size
= rescale_strokes(globally_rescaled_strokes, target_size)
rescaled_strokes return rescaled_strokes
svg_files
Loading and manipulating SVG files
Converting to Strokes
Steps:
- Discretize the SVG: Convert all paths (including bezier curves, etc) to a set of discrete points.
- Apply SVG Global Transforms: If the SVG contains something like
<g transform="(scale:0.5,-0.4)">
, apply that to the coordinates. - 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.
svg_to_strokes
svg_to_strokes (input_fname, target_size=200, total_n=1000, min_n=3)
Discretizing SVG Paths
discretize_path
discretize_path (path, total_n=1000, min_n=3)
to_points
to_points (parsed_path, n)
def discretize_paths(paths, total_n=1000, min_n=3):
= []
all_strokes = sum([p.length() for p in paths])
total_length for p in paths:
# compute number of points to generate for curr path based on ratio to total path length
= int(total_n * p.length() / total_length)
path_n # if number of points is less than the minimum, drop it.
if path_n < min_n:
continue
= discretize_path(p, path_n, min_n=min_n)
strokes
all_strokes.extend(strokes)return all_strokes
def discretize_svg(input_fname, **kwargs):
= svgpathtools.svg2paths(
paths, attributes, svg_attributes =True
input_fname, return_svg_attributes
)= discretize_paths(paths, **kwargs)
all_strokes return all_strokes
discretize_svg
discretize_svg (input_fname, **kwargs)
discretize_paths
discretize_paths (paths, total_n=1000, min_n=3)
Rescale
rescale_strokes
rescale_strokes (all_strokes, target_size)
Global Transforms
build_transforms
build_transforms (tstr)
parse_transform_instruction
parse_transform_instruction (item)
svg_to_transforms
svg_to_transforms (svgroot)
parse_svg
parse_svg (input_file)
Parse the SVG XML, to allow extracting individual elements
global_svg_transform
global_svg_transform (all_strokes, input_fname)