summaryrefslogtreecommitdiff
path: root/examples/imagepipe/imagepipe.py
blob: 2cde2f67e1b59d9dd85511409ca16b9ec25ec75c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
from functools import update_wrapper

from PIL import Image
from PIL import ImageEnhance
from PIL import ImageFilter

import click


@click.group(chain=True)
def cli():
    """This script processes a bunch of images through pillow in a unix
    pipe.  One commands feeds into the next.

    Example:

    \b
        imagepipe open -i example01.jpg resize -w 128 display
        imagepipe open -i example02.jpg blur save
    """


@cli.resultcallback()
def process_commands(processors):
    """This result callback is invoked with an iterable of all the chained
    subcommands.  As in this example each subcommand returns a function
    we can chain them together to feed one into the other, similar to how
    a pipe on unix works.
    """
    # Start with an empty iterable.
    stream = ()

    # Pipe it through all stream processors.
    for processor in processors:
        stream = processor(stream)

    # Evaluate the stream and throw away the items.
    for _ in stream:
        pass


def processor(f):
    """Helper decorator to rewrite a function so that it returns another
    function from it.
    """

    def new_func(*args, **kwargs):
        def processor(stream):
            return f(stream, *args, **kwargs)

        return processor

    return update_wrapper(new_func, f)


def generator(f):
    """Similar to the :func:`processor` but passes through old values
    unchanged and does not pass through the values as parameter.
    """

    @processor
    def new_func(stream, *args, **kwargs):
        for item in stream:
            yield item
        for item in f(*args, **kwargs):
            yield item

    return update_wrapper(new_func, f)


def copy_filename(new, old):
    new.filename = old.filename
    return new


@cli.command("open")
@click.option(
    "-i",
    "--image",
    "images",
    type=click.Path(),
    multiple=True,
    help="The image file to open.",
)
@generator
def open_cmd(images):
    """Loads one or multiple images for processing.  The input parameter
    can be specified multiple times to load more than one image.
    """
    for image in images:
        try:
            click.echo('Opening "%s"' % image)
            if image == "-":
                img = Image.open(click.get_binary_stdin())
                img.filename = "-"
            else:
                img = Image.open(image)
            yield img
        except Exception as e:
            click.echo('Could not open image "%s": %s' % (image, e), err=True)


@cli.command("save")
@click.option(
    "--filename",
    default="processed-%04d.png",
    type=click.Path(),
    help="The format for the filename.",
    show_default=True,
)
@processor
def save_cmd(images, filename):
    """Saves all processed images to a series of files."""
    for idx, image in enumerate(images):
        try:
            fn = filename % (idx + 1)
            click.echo('Saving "%s" as "%s"' % (image.filename, fn))
            yield image.save(fn)
        except Exception as e:
            click.echo('Could not save image "%s": %s' % (image.filename, e), err=True)


@cli.command("display")
@processor
def display_cmd(images):
    """Opens all images in an image viewer."""
    for image in images:
        click.echo('Displaying "%s"' % image.filename)
        image.show()
        yield image


@cli.command("resize")
@click.option("-w", "--width", type=int, help="The new width of the image.")
@click.option("-h", "--height", type=int, help="The new height of the image.")
@processor
def resize_cmd(images, width, height):
    """Resizes an image by fitting it into the box without changing
    the aspect ratio.
    """
    for image in images:
        w, h = (width or image.size[0], height or image.size[1])
        click.echo('Resizing "%s" to %dx%d' % (image.filename, w, h))
        image.thumbnail((w, h))
        yield image


@cli.command("crop")
@click.option(
    "-b", "--border", type=int, help="Crop the image from all sides by this amount."
)
@processor
def crop_cmd(images, border):
    """Crops an image from all edges."""
    for image in images:
        box = [0, 0, image.size[0], image.size[1]]

        if border is not None:
            for idx, val in enumerate(box):
                box[idx] = max(0, val - border)
            click.echo('Cropping "%s" by %dpx' % (image.filename, border))
            yield copy_filename(image.crop(box), image)
        else:
            yield image


def convert_rotation(ctx, param, value):
    if value is None:
        return
    value = value.lower()
    if value in ("90", "r", "right"):
        return (Image.ROTATE_90, 90)
    if value in ("180", "-180"):
        return (Image.ROTATE_180, 180)
    if value in ("-90", "270", "l", "left"):
        return (Image.ROTATE_270, 270)
    raise click.BadParameter('invalid rotation "%s"' % value)


def convert_flip(ctx, param, value):
    if value is None:
        return
    value = value.lower()
    if value in ("lr", "leftright"):
        return (Image.FLIP_LEFT_RIGHT, "left to right")
    if value in ("tb", "topbottom", "upsidedown", "ud"):
        return (Image.FLIP_LEFT_RIGHT, "top to bottom")
    raise click.BadParameter('invalid flip "%s"' % value)


@cli.command("transpose")
@click.option(
    "-r", "--rotate", callback=convert_rotation, help="Rotates the image (in degrees)"
)
@click.option("-f", "--flip", callback=convert_flip, help="Flips the image  [LR / TB]")
@processor
def transpose_cmd(images, rotate, flip):
    """Transposes an image by either rotating or flipping it."""
    for image in images:
        if rotate is not None:
            mode, degrees = rotate
            click.echo('Rotate "%s" by %ddeg' % (image.filename, degrees))
            image = copy_filename(image.transpose(mode), image)
        if flip is not None:
            mode, direction = flip
            click.echo('Flip "%s" %s' % (image.filename, direction))
            image = copy_filename(image.transpose(mode), image)
        yield image


@cli.command("blur")
@click.option("-r", "--radius", default=2, show_default=True, help="The blur radius.")
@processor
def blur_cmd(images, radius):
    """Applies gaussian blur."""
    blur = ImageFilter.GaussianBlur(radius)
    for image in images:
        click.echo('Blurring "%s" by %dpx' % (image.filename, radius))
        yield copy_filename(image.filter(blur), image)


@cli.command("smoothen")
@click.option(
    "-i",
    "--iterations",
    default=1,
    show_default=True,
    help="How many iterations of the smoothen filter to run.",
)
@processor
def smoothen_cmd(images, iterations):
    """Applies a smoothening filter."""
    for image in images:
        click.echo(
            'Smoothening "%s" %d time%s'
            % (image.filename, iterations, iterations != 1 and "s" or "",)
        )
        for _ in range(iterations):
            image = copy_filename(image.filter(ImageFilter.BLUR), image)
        yield image


@cli.command("emboss")
@processor
def emboss_cmd(images):
    """Embosses an image."""
    for image in images:
        click.echo('Embossing "%s"' % image.filename)
        yield copy_filename(image.filter(ImageFilter.EMBOSS), image)


@cli.command("sharpen")
@click.option(
    "-f", "--factor", default=2.0, help="Sharpens the image.", show_default=True
)
@processor
def sharpen_cmd(images, factor):
    """Sharpens an image."""
    for image in images:
        click.echo('Sharpen "%s" by %f' % (image.filename, factor))
        enhancer = ImageEnhance.Sharpness(image)
        yield copy_filename(enhancer.enhance(max(1.0, factor)), image)


@cli.command("paste")
@click.option("-l", "--left", default=0, help="Offset from left.")
@click.option("-r", "--right", default=0, help="Offset from right.")
@processor
def paste_cmd(images, left, right):
    """Pastes the second image on the first image and leaves the rest
    unchanged.
    """
    imageiter = iter(images)
    image = next(imageiter, None)
    to_paste = next(imageiter, None)

    if to_paste is None:
        if image is not None:
            yield image
        return

    click.echo('Paste "%s" on "%s"' % (to_paste.filename, image.filename))
    mask = None
    if to_paste.mode == "RGBA" or "transparency" in to_paste.info:
        mask = to_paste
    image.paste(to_paste, (left, right), mask)
    image.filename += "+" + to_paste.filename
    yield image

    for image in imageiter:
        yield image