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.