Wednesday, October 24, 2007

sortable directories

Let's say that you have generated directories full of images from some app like Pure Data. This is pretty basic stuff but easy to forget.

Basically - files with names in a format like file001.jpg, file002.jpg...

In PD, simply provide an sprintf-style argument like: "/file/path/frame%03d.jpg" to the 'makefilename' object. Magic.

opendir DIR, $inPath or die "cannot access $inPath\n";
@imageFilenames = sort(grep{$_ ne '.' && $_ ne '..'} readdir DIR);
closedir DIR;

Without the sort function above, the order of filenames in @imageFilenames will be farily random. That's no good if you want to maybe run through a time series of image.

You may want to append the full path to each filename entry:

my ($i, $z) = (0,0);
foreach $z (@imageFilenames) {
$imageFilenames[$i] = join("", ($inPath, $z));
print "$imageFilenames[$i] \n";
$i++;
}

To shuffle this sorted array:

use List::Util 'shuffle'; # requires Perl 5.8 or later

my @shuffledFilenames = shuffle(@imageFilenames);

Or just omit the orginal sorting function perhaps.

No comments: