Neural-Style Automator

Given that I make constant use of it, I decided to create a wrapper around the neural-style-tf main routine. This would allow me to run an image through a sweep of styles without supervision over long periods of time.

Development

After installing and testing the neural-style-tf package, we are going to create a simple wrapper that allows us to go through styles that we want to apply onto an image of our chosing. The first thing we need, is to load the libraries we will need and setup some parameters such as our working directories:

import os
import aux
import sys
import subprocess

After doing this, we setup the required variables to read from the terminal: the path to the image to stylize, the path to the folder in which the styles are stored, and the path to which we want our results exported.

(PATH_IMG, PATH_STY, PATH_OUT) = (sys.argv[1], sys.argv[2], sys.argv[3])
(IMG_SIZE, ITERATIONS) = (sys.argv[4], sys.argv[5])

The easiest way to run the neural-style-tf package automatically with different inputs without diving into the underlying programming structure, was to make iterated terminal calls from within python. To do this, we repeatedly call the neural_style.py script (of which I am not an author, so follow the link for the original reference) from our main routine. To do this, we first get the paths to the style images, and count the number of styles (for counting purposes):

stylesPaths = aux.getFilesWithExt(PATH_STY)
(imgsN, imgName) = (
        len(stylesPaths),
        os.path.splitext(os.path.basename(PATH_IMG))[0]
    )

Now, for the automation part, we iterate through the styles and generate the bash calls for the neural_style.py script according to its protocol:

for (i, imgSty) in enumerate(stylesPaths):
    # Create output folder
    styName = os.path.splitext(os.path.basename(imgSty))[0]
    outFolder = PATH_OUT + "" + imgName + "-" + "" + styName
    subprocess.Popen(['mkdir', outFolder])
    # Generate bash command
    cmd = [
            'python', 'neural_style.py',
            '--content_img', PATH_IMG,
            '--style_imgs', imgSty,
            '--img_output_dir', outFolder,
            '--max_size', str(IMG_SIZE),
            '--max_iterations', str(ITERATIONS),
            '--device', '/cpu:0'
        ]
    # Print state
    alert = "* [Running image {}/{} ({})]"
    print("*" * 150)
    print(alert.format(str(i + 1), str(imgsN), outFolder))
    print("*" * 150)
    # Run command and wait until it finishes
    p = subprocess.Popen(cmd)
    p.wait()

And we’re done! We can now iterate through images without any supervision!

Documentation and Code