Added imagepipe example.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent 0412755 · Browse files · 5 files·+295 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+295 added−0 removed
- other:+295 added−0 removed
Provenance
- Commit
1cb9fe1- Tree
426423f- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
0412755
5 files changed+295 added−0 removed
added:examples/imagepipe/example01.jpgbinary
A binary file, added.
added:examples/imagepipe/example02.jpgbinary
A binary file, added.
added:examples/imagepipe/imagepipe.py+266 added
1+import click2+from functools import update_wrapper3+from PIL import Image, ImageFilter, ImageEnhance4+5+6+@click.group(chain=True)7+def cli():8+ """This script processes a bunch of images through pillow in a unix9+ pipe. One commands feeds into the next.10+11+ Example:12+13+ \b14+ imagepipe open -i example01.jpg resize -w 128 display15+ imagepipe open -i example02.jpg blur save16+ """17+18+19+@cli.resultcallback()20+def 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 = ()28+29+ # Pipe it through all stream processors.30+ for processor in processors:31+ stream = processor(stream)32+33+ # Evaluate the stream and throw away the items.34+ for _ in stream:35+ pass36+37+38+def 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)47+48+49+def 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)60+61+62+def copy_filename(new, old):63+ new.filename = old.filename64+ return new65+66+67+@cli.command('open')68+@click.option('-i', '--image', 'images', type=click.Path(),69+ multiple=True, help='The image file to open.')70+@generator71+def 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)86+87+88+@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+@processor93+def 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)103+104+105+@cli.command('display')106+@processor107+def 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 image113+114+115+@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+@processor119+def 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 image128+129+130+@cli.command('crop')131+@click.option('-b', '--border', type=int, help='Crop the image from all '132+ 'sides by this amount.')133+@processor134+def 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]]138+139+ 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 image146+147+148+def 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)159+160+161+def 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)170+171+172+@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+@processor178+def 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 image190+191+192+@cli.command('blur')193+@click.option('-r', '--radius', default=2, show_default=True,194+ help='The blur radius.')195+@processor196+def 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)202+203+204+@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+@processor208+def 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 image216+217+218+@cli.command('emboss')219+@processor220+def 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)225+226+227+@cli.command('sharpen')228+@click.option('-f', '--factor', default=2.0,229+ help='Sharpens the image.', show_default=True)230+@processor231+def 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)237+238+239+@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+@processor243+def 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)250+251+ if to_paste is None:252+ if image is not None:253+ yield image254+ return255+256+ 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 image264+265+ for image in imageiter:266+ yield imageadded:examples/imagepipe/README+13 added
1+$ imagepipe_2+3+ imagepipe is an example application that implements some4+ multi commands that chain image processing instructions5+ together.6+7+ This requires pillow.8+9+Usage:10+11+ $ pip install --editable .12+ $ imagepipe open -i example01.jpg resize -w 128 display13+ $ imagepipe open -i example02.jpg blur saveadded:examples/imagepipe/setup.py+16 added
1+from setuptools import setup2+3+setup(4+ name='click-example-imagepipe',5+ version='1.0',6+ py_modules=['imagepipe'],7+ include_package_data=True,8+ install_requires=[9+ 'Click',10+ 'pillow',11+ ],12+ entry_points='''13+ [console_scripts]14+ imagepipe=imagepipe:cli15+ ''',16+)