Last active
January 5, 2022 06:19
-
-
Save zvodd/18abf5b0a43c115661b5fa791181a221 to your computer and use it in GitHub Desktop.
Converts black and white image to svg as vector pixels. Useful for converting bmp fonts. eg: `blackandwhite_to_vectorpixels.py ./bmp_glyphs/ ./svg_glyphs/ bmp`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from PIL import Image | |
import svgwrite | |
import os | |
import argparse | |
def bmp_to_svg(filename, multiply =1): | |
img = Image.open(filename) | |
w, h = img.size | |
pixel_acc = img.load() | |
generated_paths = paths_gen(pixel_acc, w,h, multiply=multiply) | |
dwg = svgwrite.Drawing(profile='tiny') | |
for path in generated_paths: | |
options = path | |
kwoptions = {} #{"fill":"black"} | |
dwg.add(dwg.polygon(options, **kwoptions)) | |
#clip_path = dwg.defs.add(dwg.clipPath()) | |
#clip_path.add(dwg.Rect(insert=(0,0), size=((w*multiply)+1, (h*multiply)+1))) | |
return dwg | |
def paths_gen(pixel_acc, w, h, multiply = 1): | |
m = multiply | |
paths = [] | |
for y in range(0,h): | |
for x in range(0,w): | |
pix = pixel_acc[x,y] | |
brightval = sum(pix) /3 | |
if brightval < 128: | |
paths.append([ | |
##top left | |
(x * m, y * m), | |
##top right | |
((x+1) * m, y * m), | |
##bottom right | |
((x+1) * m, (y+1) * m), | |
##bottom list | |
((x) * m, (y+1) * m), | |
##close back to top left | |
#(x, y), | |
]) | |
return paths | |
def main(): | |
parser = argparse.ArgumentParser( | |
description='Script to convert black and white images into vector art') | |
parser.add_argument("input_dir") | |
parser.add_argument("ouput_dir") | |
parser.add_argument("in_ext", default="bmp", help="file extension of images in input folder") | |
parser.add_argument("-m", "--multiply", default=1, type=int) | |
## TODO | |
#parser.add_argument("-u", "--union", store=True, help="unifies adjecent polgons") | |
#parser.add_argument("-s", "--simplify", store=True, help="removes points that are part of a straight line") | |
#parser.add_argument("-c", "--compress", store=True, help="same as '--union --simplify'") | |
args = parser.parse_args() | |
cdir = os.path.abspath(args.input_dir) | |
fn_gen = ( x for x in os.listdir(cdir) | |
if x.endswith('.'+args.in_ext) | |
) | |
for count, filename in enumerate(fn_gen): | |
full_filename = os.path.join(cdir, filename) | |
new_fn = "{}_.svg".format(filename) | |
new_fullfn = os.path.join(args.ouput_dir, new_fn) | |
svg = bmp_to_svg(full_filename, multiply=args.multiply) | |
print "Converted file: '{}'".format(full_filename) | |
svg.filename = new_fullfn | |
svg.save() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment