richard kappler wrote: > Starting to work through "Programming Computer Vision with Python" in my > -summer of learning python- quest. As I read through the intro to the PIL > library, I came across the below code. When I read it, I said to my self > "I don't see how that calls a set of files, there's no specificity. How > does that know where to call from?" Then I convinced myself that, because > I'm a beginner, I must be missing something, and ran it through the > interpreter. Of course, I got an error message telling me filelist isn't > defined. But now I'm kinda lost. > > If the directory holding the pics I want to work on is called > practicephotos, should I declare something along the lines of filelist = > ~/practicephotos/ or what?
In the draft of the book the author shows a way to create a list of images in the next example import os def get_imlist(path): """ Returns a list of filenames for all jpg images in a directory. """ return [os.path.join(path,f) for f in os.listdir(path) if f.endswith(".jpg")] I you follow his instructions the snippet you provided could become > [code] with indentation and outfile assignment fixed > from PIL import Image > import os import imtools filelist = imtools.get_imlist(".") > for infile in filelist: > outfile = os.path.splitext(infile)[0] + ".jpg" > if infile != outfile: > try: > Image.open(infile).save(outfile) > except IOError: > print "cannot convert", infile > [/code] However, he was a bit careless and the two examples don't exactly dovetail. get_imlist() only returns files ending with .jpg -- and these are skipped by the code you posted. You can fix that by changing get_imlist() as follows: IMAGE_SUFFIXES = (".jpg", ".png", ".gif") # add more as needed def get_imlist(path): """ Returns a list of filenames for images in a directory. """ return [os.path.join(path,f) for f in os.listdir(path) if f.endswith(IMAGE_SUFFIXES)] This is still not very robust (what if the filename of an image ends with ".JPG" or ".jpeg" or ".something_completely_different"?) but at least you have something that you can invoke with the python interpreter and that will have an effect. After that experience you should have learned to take the proviso in the introduction seriously: """ What you need to know - Basic programming experience. You need to know how to use an editor and run scripts, how to structure code as well as basic data types. Familiarity with Python [...] will help. """ Not only will it help, you won't have much fun with the book without it. I suggest that you work through a general python tutorial before you go back to the book. http://wiki.python.org/moin/BeginnersGuide _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor