Skip to content
Myr

imagepipe.py

This file

Path

examples/imagepipe/imagepipe.py

288 lines · 8.1 KiB · Python

Last changed by

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

History of this file

Take it

The walk stopped after 200 commits: lines older than 5210849 point at it.

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 1–2why, one step back
1from functools import update_wrapper
2

Merge branch '7.x'David Lordbefore adoption7239794

lines 3–5why, one step back
3from PIL import Image
4from PIL import ImageEnhance5from PIL import ImageFilter

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

line 6why, one step back
6

Merge branch '7.x'David Lordbefore adoption7239794

lines 7–9why, one step back
7import click
89

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 10–45why, one step back
10@click.group(chain=True)
11def cli():12 """This script processes a bunch of images through pillow in a unix13 pipe. One commands feeds into the next.1415 Example:1617 \b18 imagepipe open -i example01.jpg resize -w 128 display19 imagepipe open -i example02.jpg blur save20 """212223@cli.resultcallback()24def process_commands(processors):25 """This result callback is invoked with an iterable of all the chained26 subcommands. As in this example each subcommand returns a function27 we can chain them together to feed one into the other, similar to how28 a pipe on unix works.29 """30 # Start with an empty iterable.31 stream = ()3233 # Pipe it through all stream processors.34 for processor in processors:35 stream = processor(stream)3637 # Evaluate the stream and throw away the items.38 for _ in stream:39 pass404142def processor(f):43 """Helper decorator to rewrite a function so that it returns another44 function from it.45 """

Merge branch '7.x'David Lordbefore adoption7239794

line 46why, one step back
46

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 47–49why, one step back
47 def new_func(*args, **kwargs):
48 def processor(stream):49 return f(stream, *args, **kwargs)

Merge branch '7.x'David Lordbefore adoption7239794

line 50why, one step back
50

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

line 51why, one step back
51 return processor

Merge branch '7.x'David Lordbefore adoption7239794

line 52why, one step back
52

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 53–59why, one step back
53 return update_wrapper(new_func, f)
545556def generator(f):57 """Similar to the :func:`processor` but passes through old values58 unchanged and does not pass through the values as parameter.59 """

Merge branch '7.x'David Lordbefore adoption7239794

line 60why, one step back
60

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 61–62why, one step back
61 @processor
62 def new_func(stream, *args, **kwargs):

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

lines 63–64why, one step back
63 yield from stream
64 yield from f(*args, **kwargs)

Merge branch '7.x'David Lordbefore adoption7239794

line 65why, one step back
65

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 66–73why, one step back
66 return update_wrapper(new_func, f)
676869def copy_filename(new, old):70 new.filename = old.filename71 return new7273

Merge branch '7.x'David Lordbefore adoption7239794

lines 74–82why, one step back
74@cli.command("open")
75@click.option(76 "-i",77 "--image",78 "images",79 type=click.Path(),80 multiple=True,81 help="The image file to open.",82)

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 83–89why, one step back
83@generator
84def open_cmd(images):85 """Loads one or multiple images for processing. The input parameter86 can be specified multiple times to load more than one image.87 """88 for image in images:89 try:

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 90why, one step back
90 click.echo(f"Opening '{image}'")

Merge branch '7.x'David Lordbefore adoption7239794

line 91why, one step back
91 if image == "-":

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

line 92why, one step back
92 img = Image.open(click.get_binary_stdin())

Merge branch '7.x'David Lordbefore adoption7239794

line 93why, one step back
93 img.filename = "-"

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 94–97why, one step back
94 else:
95 img = Image.open(image)96 yield img97 except Exception as e:

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 98why, one step back
98 click.echo(f"Could not open image '{image}': {e}", err=True)

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 99–100why, one step back
99
100

Merge branch '7.x'David Lordbefore adoption7239794

lines 101–108why, one step back
101@cli.command("save")
102@click.option(103 "--filename",104 default="processed-{:04}.png",105 type=click.Path(),106 help="The format for the filename.",107 show_default=True,108)

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 109–113why, one step back
109@processor
110def save_cmd(images, filename):111 """Saves all processed images to a series of files."""112 for idx, image in enumerate(images):113 try:

Merge branch '7.x'David Lordbefore adoption7239794

line 114why, one step back
114 fn = filename.format(idx + 1)

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 115why, one step back
115 click.echo(f"Saving '{image.filename}' as '{fn}'")

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 116–117why, one step back
116 yield image.save(fn)
117 except Exception as e:

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 118why, one step back
118 click.echo(f"Could not save image '{image.filename}': {e}", err=True)

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 119–120why, one step back
119
120

Merge branch '7.x'David Lordbefore adoption7239794

line 121why, one step back
121@cli.command("display")

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 122–125why, one step back
122@processor
123def display_cmd(images):124 """Opens all images in an image viewer."""125 for image in images:

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 126why, one step back
126 click.echo(f"Displaying '{image.filename}'")

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 127–130why, one step back
127 image.show()
128 yield image129130

Merge branch '7.x'David Lordbefore adoption7239794

lines 131–133why, one step back
131@cli.command("resize")
132@click.option("-w", "--width", type=int, help="The new width of the image.")133@click.option("-h", "--height", type=int, help="The new height of the image.")

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 134–140why, one step back
134@processor
135def resize_cmd(images, width, height):136 """Resizes an image by fitting it into the box without changing137 the aspect ratio.138 """139 for image in images:140 w, h = (width or image.size[0], height or image.size[1])

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 141why, one step back
141 click.echo(f"Resizing '{image.filename}' to {w}x{h}")

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 142–145why, one step back
142 image.thumbnail((w, h))
143 yield image144145

Merge branch '7.x'David Lordbefore adoption7239794

lines 146–149why, one step back
146@cli.command("crop")
147@click.option(148 "-b", "--border", type=int, help="Crop the image from all sides by this amount."149)

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 150–158why, one step back
150@processor
151def crop_cmd(images, border):152 """Crops an image from all edges."""153 for image in images:154 box = [0, 0, image.size[0], image.size[1]]155156 if border is not None:157 for idx, val in enumerate(box):158 box[idx] = max(0, val - border)

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 159why, one step back
159 click.echo(f"Cropping '{image.filename}' by {border}px")

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 160–168why, one step back
160 yield copy_filename(image.crop(box), image)
161 else:162 yield image163164165def convert_rotation(ctx, param, value):166 if value is None:167 return168 value = value.lower()

Merge branch '7.x'David Lordbefore adoption7239794

line 169why, one step back
169 if value in ("90", "r", "right"):

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

line 170why, one step back
170 return (Image.ROTATE_90, 90)

Merge branch '7.x'David Lordbefore adoption7239794

line 171why, one step back
171 if value in ("180", "-180"):

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

line 172why, one step back
172 return (Image.ROTATE_180, 180)

Merge branch '7.x'David Lordbefore adoption7239794

line 173why, one step back
173 if value in ("-90", "270", "l", "left"):

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

line 174why, one step back
174 return (Image.ROTATE_270, 270)

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 175why, one step back
175 raise click.BadParameter(f"invalid rotation '{value}'")

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 176–181why, one step back
176
177178def convert_flip(ctx, param, value):179 if value is None:180 return181 value = value.lower()

Merge branch '7.x'David Lordbefore adoption7239794

lines 182–185why, one step back
182 if value in ("lr", "leftright"):
183 return (Image.FLIP_LEFT_RIGHT, "left to right")184 if value in ("tb", "topbottom", "upsidedown", "ud"):185 return (Image.FLIP_LEFT_RIGHT, "top to bottom")

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 186why, one step back
186 raise click.BadParameter(f"invalid flip '{value}'")

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 187–188why, one step back
187
188

Merge branch '7.x'David Lordbefore adoption7239794

lines 189–193why, one step back
189@cli.command("transpose")
190@click.option(191 "-r", "--rotate", callback=convert_rotation, help="Rotates the image (in degrees)"192)193@click.option("-f", "--flip", callback=convert_flip, help="Flips the image [LR / TB]")

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 194–199why, one step back
194@processor
195def transpose_cmd(images, rotate, flip):196 """Transposes an image by either rotating or flipping it."""197 for image in images:198 if rotate is not None:199 mode, degrees = rotate

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 200why, one step back
200 click.echo(f"Rotate '{image.filename}' by {degrees}deg")

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 201–203why, one step back
201 image = copy_filename(image.transpose(mode), image)
202 if flip is not None:203 mode, direction = flip

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 204why, one step back
204 click.echo(f"Flip '{image.filename}' {direction}")

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 205–208why, one step back
205 image = copy_filename(image.transpose(mode), image)
206 yield image207208

Merge branch '7.x'David Lordbefore adoption7239794

lines 209–210why, one step back
209@cli.command("blur")
210@click.option("-r", "--radius", default=2, show_default=True, help="The blur radius.")

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 211–215why, one step back
211@processor
212def blur_cmd(images, radius):213 """Applies gaussian blur."""214 blur = ImageFilter.GaussianBlur(radius)215 for image in images:

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 216why, one step back
216 click.echo(f"Blurring '{image.filename}' by {radius}px")

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 217–219why, one step back
217 yield copy_filename(image.filter(blur), image)
218219

Merge branch '7.x'David Lordbefore adoption7239794

lines 220–227why, one step back
220@cli.command("smoothen")
221@click.option(222 "-i",223 "--iterations",224 default=1,225 show_default=True,226 help="How many iterations of the smoothen filter to run.",227)

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 228–231why, one step back
228@processor
229def smoothen_cmd(images, iterations):230 """Applies a smoothening filter."""231 for image in images:

Merge branch '7.x'David Lordbefore adoption7239794

line 232why, one step back
232 click.echo(

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

lines 233–234why, one step back
233 f"Smoothening {image.filename!r} {iterations}"
234 f" time{'s' if iterations != 1 else ''}"

Merge branch '7.x'David Lordbefore adoption7239794

lines 235–236why, one step back
235 )
236 for _ in range(iterations):

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 237–240why, one step back
237 image = copy_filename(image.filter(ImageFilter.BLUR), image)
238 yield image239240

Merge branch '7.x'David Lordbefore adoption7239794

line 241why, one step back
241@cli.command("emboss")

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 242–245why, one step back
242@processor
243def emboss_cmd(images):244 """Embosses an image."""245 for image in images:

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 246why, one step back
246 click.echo(f"Embossing '{image.filename}'")

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 247–249why, one step back
247 yield copy_filename(image.filter(ImageFilter.EMBOSS), image)
248249

Merge branch '7.x'David Lordbefore adoption7239794

lines 250–253why, one step back
250@cli.command("sharpen")
251@click.option(252 "-f", "--factor", default=2.0, help="Sharpens the image.", show_default=True253)

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 254–257why, one step back
254@processor
255def sharpen_cmd(images, factor):256 """Sharpens an image."""257 for image in images:

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 258why, one step back
258 click.echo(f"Sharpen '{image.filename}' by {factor}")

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 259–262why, one step back
259 enhancer = ImageEnhance.Sharpness(image)
260 yield copy_filename(enhancer.enhance(max(1.0, factor)), image)261262

Merge branch '7.x'David Lordbefore adoption7239794

lines 263–265why, one step back
263@cli.command("paste")
264@click.option("-l", "--left", default=0, help="Offset from left.")265@click.option("-r", "--right", default=0, help="Offset from right.")

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 266–279why, one step back
266@processor
267def paste_cmd(images, left, right):268 """Pastes the second image on the first image and leaves the rest269 unchanged.270 """271 imageiter = iter(images)272 image = next(imageiter, None)273 to_paste = next(imageiter, None)274275 if to_paste is None:276 if image is not None:277 yield image278 return279

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 280why, one step back
280 click.echo(f"Paste '{to_paste.filename}' on '{image.filename}'")

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

line 281why, one step back
281 mask = None

Merge branch '7.x'David Lordbefore adoption7239794

line 282why, one step back
282 if to_paste.mode == "RGBA" or "transparency" in to_paste.info:

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 283–284why, one step back
283 mask = to_paste
284 image.paste(to_paste, (left, right), mask)

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 285why, one step back
285 image.filename += f"+{to_paste.filename}"

Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849

lines 286–287why, one step back
286 yield image
287

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 288why, one step back
288 yield from imageiter