windowscommand-lineimagemagickmontage

Use ImageMagick montage with a file name substring variable


I have only very rudimentary programming and command line skills, hence I'm a bit stumped by the following.

I have a directory with image files like this:

abc_B.jpg
abc_G.jpg
abc_R.jpg
abc_RGB.jpg
defg_B.jpg
defg_G.jpg
defg_R.jpg
defg_RGB.jpg
etc...

I want to stitch together sets of the four R, G, B, and RGB images using ImageMagick. For an individual set of images this is pretty straightforward:

montage *_B.jpg *_G.jpg *_R.jpg *_RGB.jpg [some arguments] montage.jpg 

In fact, I've been copying sets of four images into a temp directory and run the above command. But this is of course not very efficient or practical with larger sets of images. But to run it on the entire directory there needs to be a way to take the 'abc', 'defg', etc. part of the file name and put it into a variable (let's call it %v) and run something like this:

montage %v_B.jpg %v_G.jpg %v_R.jpg %v_RGB.jpg [some arguments] %v_montage.jpg 

Now, to iterate over files in a directory there's the FOR command. But I have no idea how to handle that with groups of four files and how to extract and use a filename substring to make that work.

Some help would be greatly appreciated.


Solution

  • It might look something like this - store it as GO.BAT:

    @ECHO OFF
    FOR /F "delims=_" %%G IN ('DIR /B *_R.JPG') DO (
        ECHO MONTAGE %%G_R.JPG %%G_G.JPG %%G_B.JPG %%G_RGB.JPG ... montage_%%G.JPG
    )
    

    Sample Output

    MONTAGE abc_R.JPG abc_G.JPG abc_B.JPG abc_RGB.JPG ... montage_abc.JPG
    MONTAGE defg_R.JPG defg_G.JPG defg_B.JPG defg_RGB.JPG ... montage_defg.JPG
    

    You would remove the ECHO if you like what it does, because at the moment it does nothing except tell you what it would do!

    I use DIR /B in the command to avoid getting headers, and I only list the *_R.JPG so that each filename stem only occurs once - not four times.

    There's a handy reference here.