Raster-to-Vector plus not bitching about significant whitespace

So this weekend I learned Python and implemented a basic raster to vector converter in it. It converts whatever file formats the Python PIL module supports to SVG.

Here’s the little guys from Joust embedded as SVG (This probably doesn’t work on Internet Explorer, but if you’re using IE you have bigger problems, brother)

and here’s the fruits from Pac-Man: (My favorite is the Galaxian fruit)

Specifically I implemented classical contour extraction as described in the 1985 paper “Topological Structural Analysis of Digitized Binary Images by Border Following”, which is the algorithm that OpenCV’s cvFindContours uses, modified such that it supports color images rather than black-and-white bitmaps. (This is something that I may eventually have to do at work for real, i.e. in C++, so I thought it would be a good way to learn Python and make sure my modified algorithm was actually going to work — it’s not a trivial change because color images allow two contours to be adjacent which can’t happen in a bit map image)

Here’s the code. Usage is like:

python Sprite2Svg.py “c:\work\fruits.png” “c:\work\fruits.svg” 4 “#000000”

where the last two arguments are optional. The 3rd argument is a scale factor in pixels. The 4th argument is a background color that will be removed from the output. I think there’s a bug right now in which the code doesn’t support paletted images; trivial to fix, but I wanted to fix it in some general way and then forgot about it.

Anyway, things I like about Python:

  • Significant whitespace turns out to not be annoying. (Who knew?)
  • Coroutines!… about twenty years ago I was in a class in which I had to write a compiler in a language called CLU. All I remember about CLU is that (a) I once apparently wrote a compiler in it and (b) Coroutines! — well it had the generator/yield construct, anyway. I wish C++ had generator/yield
  • It isn’t Perl. Can’t stress this one enough.

Things I don’t like about Python:

  • The thing with version 3 being better but nobody using it.
  • The issue I’m talking about here is annoying and I think the “nonlocal” declaration isn’t the best solution in the world.

4 Comments

  1. Pingback: The Curiously Recurring Gimlet Pattern » Marble Madness Madness

  2. Jurri February 27, 2015 at 12:15 pm

    Nice and easy thing. Thank you!

    Reply
  3. Jignesh Patel May 15, 2015 at 8:53 am

    How about reverse ? I want to convert SVG to JPEG or PNG using PIL lib. Can you help me with it ? Thanks.

    Reply
  4. jwez7158 May 15, 2015 at 5:18 pm

    The easiest way to convert SVG to raster from Python is to install InkScape and call out to InkScape as an external process with appropriate command line arguments. Beyond that, use the module Cairo but as I recall it is non-trivial to get Cairo working on windows. On linux however, just use Cairo.

    Reply

Leave a Reply to Jurri Cancel reply

Your email address will not be published.