Skip to content
Myr

imagepipe.py

This file

Path

examples/imagepipe/imagepipe.py

266 lines · 8.2 KiB · Python

Last changed by

Not known.

History of this file

Take it

1import click2from functools import update_wrapper3from PIL import Image, ImageFilter, ImageEnhance456@click.group(chain=True)7def cli():8    """This script processes a bunch of images through pillow in a unix9    pipe.  One commands feeds into the next.1011    Example:1213    \b14        imagepipe open -i example01.jpg resize -w 128 display15        imagepipe open -i example02.jpg blur save16    """171819@cli.resultcallback()20def process_commands(processors):21    """This result callback is invoked with an iterable of all the chained22    subcommands.  As in this example each subcommand returns a function23    we can chain them together to feed one into the other, similar to how24    a pipe on unix works.25    """26    # Start with an empty iterable.27    stream = ()2829    # Pipe it through all stream processors.30    for processor in processors:31        stream = processor(stream)3233    # Evaluate the stream and throw away the items.34    for _ in stream:35        pass363738def processor(f):39    """Helper decorator to rewrite a function so that it returns another40    function from it.41    """42    def new_func(*args, **kwargs):43        def processor(stream):44            return f(stream, *args, **kwargs)45        return processor46    return update_wrapper(new_func, f)474849def generator(f):50    """Similar to the :func:`processor` but passes through old values51    unchanged and does not pass through the values as parameter.52    """53    @processor54    def new_func(stream, *args, **kwargs):55        for item in stream:56            yield item57        for item in f(*args, **kwargs):58            yield item59    return update_wrapper(new_func, f)606162def copy_filename(new, old):63    new.filename = old.filename64    return new656667@cli.command('open')68@click.option('-i', '--image', 'images', type=click.Path(),69              multiple=True, help='The image file to open.')70@generator71def open_cmd(images):72    """Loads one or multiple images for processing.  The input parameter73    can be specified multiple times to load more than one image.74    """75    for image in images:76        try:77            click.echo('Opening "%s"' % image)78            if image == '-':79                img = Image.open(click.get_binary_stdin())80                img.filename = '-'81            else:82                img = Image.open(image)83            yield img84        except Exception as e:85            click.echo('Could not open image "%s": %s' % (image, e), err=True)868788@cli.command('save')89@click.option('--filename', default='processed-%04d.png', type=click.Path(),90              help='The format for the filename.',91              show_default=True)92@processor93def save_cmd(images, filename):94    """Saves all processed images to a series of files."""95    for idx, image in enumerate(images):96        try:97            fn = filename % (idx + 1)98            click.echo('Saving "%s" as "%s"' % (image.filename, fn))99            yield image.save(fn)100        except Exception as e:101            click.echo('Could not save image "%s": %s' %102                       (image.filename, e), err=True)103104105@cli.command('display')106@processor107def display_cmd(images):108    """Opens all images in an image viewer."""109    for image in images:110        click.echo('Displaying "%s"' % image.filename)111        image.show()112        yield image113114115@cli.command('resize')116@click.option('-w', '--width', type=int, help='The new width of the image.')117@click.option('-h', '--height', type=int, help='The new height of the image.')118@processor119def resize_cmd(images, width, height):120    """Resizes an image by fitting it into the box without changing121    the aspect ratio.122    """123    for image in images:124        w, h = (width or image.size[0], height or image.size[1])125        click.echo('Resizing "%s" to %dx%d' % (image.filename, w, h))126        image.thumbnail((w, h))127        yield image128129130@cli.command('crop')131@click.option('-b', '--border', type=int, help='Crop the image from all '132              'sides by this amount.')133@processor134def crop_cmd(images, border):135    """Crops an image from all edges."""136    for image in images:137        box = [0, 0, image.size[0], image.size[1]]138139        if border is not None:140            for idx, val in enumerate(box):141                box[idx] = max(0, val - border)142            click.echo('Cropping "%s" by %dpx' % (image.filename, border))143            yield copy_filename(image.crop(box), image)144        else:145            yield image146147148def convert_rotation(ctx, param, value):149    if value is None:150        return151    value = value.lower()152    if value in ('90', 'r', 'right'):153        return (Image.ROTATE_90, 90)154    if value in ('180', '-180'):155        return (Image.ROTATE_180, 180)156    if value in ('-90', '270', 'l', 'left'):157        return (Image.ROTATE_270, 270)158    raise click.BadParameter('invalid rotation "%s"' % value)159160161def convert_flip(ctx, param, value):162    if value is None:163        return164    value = value.lower()165    if value in ('lr', 'leftright'):166        return (Image.FLIP_LEFT_RIGHT, 'left to right')167    if value in ('tb', 'topbottom', 'upsidedown', 'ud'):168        return (Image.FLIP_LEFT_RIGHT, 'top to bottom')169    raise click.BadParameter('invalid flip "%s"' % value)170171172@cli.command('transpose')173@click.option('-r', '--rotate', callback=convert_rotation,174              help='Rotates the image (in degrees)')175@click.option('-f', '--flip', callback=convert_flip,176              help='Flips the image  [LR / TB]')177@processor178def transpose_cmd(images, rotate, flip):179    """Transposes an image by either rotating or flipping it."""180    for image in images:181        if rotate is not None:182            mode, degrees = rotate183            click.echo('Rotate "%s" by %ddeg' % (image.filename, degrees))184            image = copy_filename(image.transpose(mode), image)185        if flip is not None:186            mode, direction = flip187            click.echo('Flip "%s" %s' % (image.filename, direction))188            image = copy_filename(image.transpose(mode), image)189        yield image190191192@cli.command('blur')193@click.option('-r', '--radius', default=2, show_default=True,194              help='The blur radius.')195@processor196def blur_cmd(images, radius):197    """Applies gaussian blur."""198    blur = ImageFilter.GaussianBlur(radius)199    for image in images:200        click.echo('Blurring "%s" by %dpx' % (image.filename, radius))201        yield copy_filename(image.filter(blur), image)202203204@cli.command('smoothen')205@click.option('-i', '--iterations', default=1, show_default=True,206              help='How many iterations of the smoothen filter to run.')207@processor208def smoothen_cmd(images, iterations):209    """Applies a smoothening filter."""210    for image in images:211        click.echo('Smoothening "%s" %d time%s' %212                   (image.filename, iterations, iterations != 1 and 's' or '',))213        for x in xrange(iterations):214            image = copy_filename(image.filter(ImageFilter.BLUR), image)215        yield image216217218@cli.command('emboss')219@processor220def emboss_cmd(images):221    """Embosses an image."""222    for image in images:223        click.echo('Embossing "%s"' % image.filename)224        yield copy_filename(image.filter(ImageFilter.EMBOSS), image)225226227@cli.command('sharpen')228@click.option('-f', '--factor', default=2.0,229              help='Sharpens the image.', show_default=True)230@processor231def sharpen_cmd(images, factor):232    """Sharpens an image."""233    for image in images:234        click.echo('Sharpen "%s" by %f' % (image.filename, factor))235        enhancer = ImageEnhance.Sharpness(image)236        yield copy_filename(enhancer.enhance(max(1.0, factor)), image)237238239@cli.command('paste')240@click.option('-l', '--left', default=0, help='Offset from left.')241@click.option('-r', '--right', default=0, help='Offset from right.')242@processor243def paste_cmd(images, left, right):244    """Pastes the second image on the first image and leaves the rest245    unchanged.246    """247    imageiter = iter(images)248    image = next(imageiter, None)249    to_paste = next(imageiter, None)250251    if to_paste is None:252        if image is not None:253            yield image254        return255256    click.echo('Paste "%s" on "%s"' %257               (to_paste.filename, image.filename))258    mask = None259    if to_paste.mode == 'RGBA' or 'transparency' in to_paste.info:260        mask = to_paste261    image.paste(to_paste, (left, right), mask)262    image.filename += '+' + to_paste.filename263    yield image264265    for image in imageiter:266        yield image