Creating a gif with python?

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Prelates, Moderators General

Creating a gif with python?

Postby agelessdrifter » Tue Jan 31, 2012 8:35 pm UTC

I've been doing work on a genetic algorithm for the Traveling Salesman Problem for the last month or so. It doesn't perform very well, as of yet. I recently tried to bump up my mutation operator from a 2-opt hill climb to a 3-opt, but it murdered the run-time to the point where it's not even worth trying to run the full algorithm. So now I'm going through the solutions my original 2-opt mutation algorithm came up with and implementing the 3-opt on them as a finishing to touch just to see what kind of improvement there'll be.

Something I thought would be interesting is to have my program actually draw the best path with, eg, MSPaint, and then I thought, it'd be really fun to have it draw each step in the 3-opt hill climb and then compose the images into a .gif, so I could watch the improvements occur.

I'm pretty much entirely new to python -- I just started learning at the beginning of the month. I assume something like this is possible (at least the generation of the frames for the gif, if not the actual composition of the gif), but I have no idea if it's doable with *just* python (without summoning another coding language) and I have no idea how to implement such a thing.

Does anyone know anything about this sort of thing? Can you offer some advice/direction? Thanks.
User avatar
agelessdrifter
 
Posts: 225
Joined: Mon Oct 05, 2009 8:10 pm UTC

Re: Creating a gif with python?

Postby Yakk » Tue Jan 31, 2012 8:40 pm UTC

My advice would be to pick a really simple image file format, and output to that.

Then use a tool that reads in those images, and either builds a gif (possibly through an intermediate stage).

This is a method that will result in you spending less time working on the animation than on the actual problem. :) And unix tools for manipulating images on the command line are relatively easy to find (and cygwin style ports of said environments are also easy). I'd be shocked if there wasn't a "build a gif from images" command line tool.

Have python generate the images, then call someone else's programs to meld them into a gif.

The easiest format (by far) to generate is:
PPM, PGM, PBM (or PNM)
which are so easy you can often look at small images in a text editor and see them.

Edit: Oh, and if you want to do it directly in python, google "python animated gif", and select the oddthinking link (the second one). The comments have someone doing the above (and generating SWF files) through whatever means, directly in python.
Last edited by Yakk on Tue Jan 31, 2012 9:07 pm UTC, edited 1 time in total.
One of the painful things about our time is that those who feel certainty are stupid, and those with any imagination and understanding are filled with doubt and indecision - BR

Last edited by JHVH on Fri Oct 23, 4004 BCE 6:17 pm, edited 6 times in total.
User avatar
Yakk
Poster with most posts but no title.
 
Posts: 10401
Joined: Sat Jan 27, 2007 7:27 pm UTC
Location: E pur si muove

Re: Creating a gif with python?

Postby thoughtfully » Tue Jan 31, 2012 9:45 pm UTC

I don't know if it supports animates GIFs, but an obligatory reference for anyone working with images in Python is the Python Imaging Library, which could help you out with the frames, for instance, and you could put them into an animated GIF using any number of command line tools.

A higher level tool for what you want though would be Graphviz. It's the tool I used to make the image in my signature, for instance (click on it to see the input file). There's even a Python interface.
Image
Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.
-- Antoine de Saint-Exupery
User avatar
thoughtfully
 
Posts: 2092
Joined: Thu Nov 01, 2007 12:25 am UTC
Location: Minneapolis, MN

Re: Creating a gif with python?

Postby Yakk » Tue Jan 31, 2012 10:05 pm UTC

Let me save the next person some trouble: The Python Imaging Library (PIL 1.1.5) does not support writing animated GIFs.

Maybe 1.1.7 does.
One of the painful things about our time is that those who feel certainty are stupid, and those with any imagination and understanding are filled with doubt and indecision - BR

Last edited by JHVH on Fri Oct 23, 4004 BCE 6:17 pm, edited 6 times in total.
User avatar
Yakk
Poster with most posts but no title.
 
Posts: 10401
Joined: Sat Jan 27, 2007 7:27 pm UTC
Location: E pur si muove

Re: Creating a gif with python?

Postby agelessdrifter » Tue Jan 31, 2012 10:23 pm UTC

Thanks for the replies.

Thoughtfully, that graphviz program seems like it might be ideal for what I'm trying to do, but the language is alien to me, and a quick perusal of the documentation wasn't very enlightening -- can you give me a rough idea of what it would take to get from a txt file containing an x-coordinate column and a y-coordinate column, (with each row constituting one point) to a graph where each point is connected to the points occurring immediately above and below it in the txt file?


edit 2: ignore edit 1
edit1:

And if that isn't a feasible project for graphviz, I have a quick question about PIL: There's all kinds of stuff in their documentation talking about how to open an existing image and edit it, but I can't find anything about how to generate a blank image file that doesn't already exist -- is it possible? I'd rather not have to go into bitmap and save ~1000 blank white rectangles to draw my map onto. :|
User avatar
agelessdrifter
 
Posts: 225
Joined: Mon Oct 05, 2009 8:10 pm UTC

Re: Creating a gif with python?

Postby thoughtfully » Wed Feb 01, 2012 12:06 am UTC

One of the "features" of Graphviz is that it takes care of the layout for you. Think about it. If you've got a graph with a bunch of nodes and edges, the position of those nodes isn't really relevant. You can align nodes by row or column (but not both), and there are some other features for twerking layout. If you want to have a lot of control over positioning though, you probably don't want to use Graphviz. Do you really need to?

For PIL, there are a few ways to create an image from scratch. You can make a PBM/PGM/PPM image in memory and work from that (Image.fromstring/frombuffer()), you can create a blank image (Image.new()) and use the ImageDraw module to draw graphic primitives onto it, or you can draw onto your GUI toolkit's canvas and load that into PIL. I've done it with Tkinter and pyGTK, I'd imagine most toolkits have the functionality. Tkinter's PhotoImage class works directly with PIL; I think perhaps for pyGTK it was necessary to export to PxM first and load that into PIL.
Image
Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.
-- Antoine de Saint-Exupery
User avatar
thoughtfully
 
Posts: 2092
Joined: Thu Nov 01, 2007 12:25 am UTC
Location: Minneapolis, MN

Re: Creating a gif with python?

Postby PM 2Ring » Wed Feb 01, 2012 7:10 am UTC

Despite the somewhat messy documentation, graphviz is actually pretty easy to use. I've written several programs that create output in the dot language, mostly in Python or awk, eg this thread has a simple graph-making program in Python for an extended version of rock-paper-scissors.

As thoughfully mentioned, graphviz takes care of the layout for you. OTOH, it doesn't prevent you from manually positioning any or all of the nodes, if you so desire.

I don't know which part of the graphviz documentation you looked at, but I suggest taking a look at the dot man page, and have a quick look at the simple examples given near the end of that document. I can post some more examples, if you like.

One nice thing about graphviz is that it has a wide range of output formats available, including several structured drawing formats like PostScript and SVG. I quite like using SVG because it supports tooltips on all graph elements.

If you decide to not use graphviz, I'd still recommend using a structured drawing format for output over some bitmap format. It's not that hard to generate simple PostScript or SVG files directly, and they scale and print well. And if you want to get fancy, modern browsers support SVG animation (although I must admit that I have no experience with creating such things).
User avatar
PM 2Ring
 
Posts: 3250
Joined: Mon Jan 26, 2009 3:19 pm UTC
Location: Mid north coast, NSW, Australia

Re: Creating a gif with python?

Postby agelessdrifter » Wed Feb 01, 2012 9:37 pm UTC

thoughtfully, the relative positions of the cities is pivotal to the images, unfortunately -- I need to see where/how often paths from one city to the next are crossing, and how good a job my algorithm does of fixing the crossings to shorten the tour lengths. At least, that's what I'm *interested* in seeing -- I dunno if it's particularly useful, objectively.

Fortunately getting PIL to draw the finished maps from txt files turned out to be pretty simple. Haven't gotten to scripting the gif construction, yet.

Thanks for all the input, all. This is how the maps are looking right now. Not terrifically fancy, but they get the point across.

Image

Image
User avatar
agelessdrifter
 
Posts: 225
Joined: Mon Oct 05, 2009 8:10 pm UTC

Re: Creating a gif with python?

Postby agelessdrifter » Fri Feb 03, 2012 8:43 pm UTC

Update:

Well I've got python drawing the frames for me, but the only thing I've been able to find to compile the gif is ImageMagick, which I absolutely cannot figure out how to use. It's not a python library as far as I can tell -- it runs right through the command line, but I'm using a windows box and all the tutorials I can find seem to be written for linux, and I'm getting all kinds of errors thrown trying to use them (mostly "Invalid Parameter" etc).

I downloaded a third party program (easy gif editor) to use in the interim:

Image

but I'd really like to figure this out.
User avatar
agelessdrifter
 
Posts: 225
Joined: Mon Oct 05, 2009 8:10 pm UTC

Re: Creating a gif with python?

Postby Dropzone » Fri Feb 03, 2012 10:40 pm UTC

Make sure your PATH environment variable is set correctly - you need to have the ImageMagick install directory before the Windows directories, otherwise you'll be running Windows' convert-FAT-to-NTFS tool instead of the ImageMagick program with the same name (alternatively, don't put ImageMagick in your PATH at all, and just type the full path to the program). Once you've done that, then assuming that you've got a bunch of PBM files in a directory, you should be able to make them into a GIF by running convert *.pbm out.gif in that directory. You can change the animation speed by adding -delay N before the filenames (where N is how many hundredths of a second to wait between frames). Another useful option is -layers optimize (which goes between the filenames) - it reduces the GIF's file size by only storing the differences between each frame.
User avatar
Dropzone
 
Posts: 405
Joined: Sun Dec 30, 2007 10:12 pm UTC
Location: North Lincs., UK

Re: Creating a gif with python?

Postby agelessdrifter » Fri Feb 03, 2012 11:49 pm UTC

That sounds like it's definitely the problem I'm running into, but I'm not sure I understand your suggestion about how to solve it. This is the code I was using, essentially:

Code: Select all
def animate(directory, max_gen):
   string = ""
   for i in range(0, max_gen):
      if os.stat(directory + "/image_" + str(i) + ".gif"):
         string += directory + "/image_" + str(i) + ".gif "
   os.system("convert " + string + " animation.gif")


Can you indicate what needs changing? Do you mean that I need to add the directory of ImageMagick before the 'convert' in the argument of os.system? Do you happen to know what that would be, by default, on a windows box?
User avatar
agelessdrifter
 
Posts: 225
Joined: Mon Oct 05, 2009 8:10 pm UTC

Re: Creating a gif with python?

Postby Dropzone » Sat Feb 04, 2012 1:03 am UTC

Yeah, the easiest way to fix that would be to change the last line to
Code: Select all
   os.system('"C:\\Program Files\\ImageMagick-6.7.5-Q16\\convert" ' + string + " animation.gif")
Note that the default install path is different depending on which exact version you downloaded, but it'll be something like the one above.
User avatar
Dropzone
 
Posts: 405
Joined: Sun Dec 30, 2007 10:12 pm UTC
Location: North Lincs., UK

Re: Creating a gif with python?

Postby agelessdrifter » Sat Feb 04, 2012 3:03 am UTC

Thanks a bunch, I'll give that a whirl.

edit: Solved that problem with the screwy color, and your advice worked. Thanks a million to everyone, I am very excited to finally have this working.
User avatar
agelessdrifter
 
Posts: 225
Joined: Mon Oct 05, 2009 8:10 pm UTC


Return to Coding

Who is online

Users browsing this forum: No registered users and 6 guests