Debian Codegraph @

examples/imagepipe/imagepipe.py

raw
1 from functools import update_wrapper
2
3 from PIL import Image
4 from PIL import ImageEnhance
5 from PIL import ImageFilter
6
7 import click
8
9
10 @click.group(chain=True)
11 def cli():
12 """This script processes a bunch of images through pillow in a unix
13 pipe. One commands feeds into the next.
14
15 Example:
16
17 \b
18 imagepipe open -i example01.jpg resize -w 128 display
19 imagepipe open -i example02.jpg blur save
20 """
21
22
23 @cli.result_callback()
24 def process_commands(processors):
25 """This result callback is invoked with an iterable of all the chained
26 subcommands. As in this example each subcommand returns a function
27 we can chain them together to feed one into the other, similar to how
28 a pipe on unix works.
29 """
30 # Start with an empty iterable.
31 stream = ()
32
33 # Pipe it through all stream processors.
34 for processor in processors:
35 stream = processor(stream)
36
37 # Evaluate the stream and throw away the items.
38 for _ in stream:
39 pass
40
41
42 def processor(f):
43 """Helper decorator to rewrite a function so that it returns another
44 function from it.
45 """
46
47 def new_func(*args, **kwargs):
48 def processor(stream):
49 return f(stream, *args, **kwargs)
50
51 return processor
52
53 return update_wrapper(new_func, f)
54
55
56 def generator(f):
57 """Similar to the :func:`processor` but passes through old values
58 unchanged and does not pass through the values as parameter.
59 """
60
61 @processor
62 def new_func(stream, *args, **kwargs):
63 yield from stream
64 yield from f(*args, **kwargs)
65
66 return update_wrapper(new_func, f)
67
68
69 def copy_filename(new, old):
70 new.filename = old.filename
71 return new
72
73
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 )
83 @generator
84 def open_cmd(images):
85 """Loads one or multiple images for processing. The input parameter
86 can be specified multiple times to load more than one image.
87 """
88 for image in images:
89 try:
90 click.echo(f"Opening '{image}'")
91 if image == "-":
92 img = Image.open(click.get_binary_stdin())
93 img.filename = "-"
94 else:
95 img = Image.open(image)
96 yield img
97 except Exception as e:
98 click.echo(f"Could not open image '{image}': {e}", err=True)
99
100
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 )
109 @processor
110 def save_cmd(images, filename):
111 """Saves all processed images to a series of files."""
112 for idx, image in enumerate(images):
113 try:
114 fn = filename.format(idx + 1)
115 click.echo(f"Saving '{image.filename}' as '{fn}'")
116 yield image.save(fn)
117 except Exception as e:
118 click.echo(f"Could not save image '{image.filename}': {e}", err=True)
119
120
121 @cli.command("display")
122 @processor
123 def display_cmd(images):
124 """Opens all images in an image viewer."""
125 for image in images:
126 click.echo(f"Displaying '{image.filename}'")
127 image.show()
128 yield image
129
130
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.")
134 @processor
135 def resize_cmd(images, width, height):
136 """Resizes an image by fitting it into the box without changing
137 the aspect ratio.
138 """
139 for image in images:
140 w, h = (width or image.size[0], height or image.size[1])
141 click.echo(f"Resizing '{image.filename}' to {w}x{h}")
142 image.thumbnail((w, h))
143 yield image
144
145
146 @cli.command("crop")
147 @click.option(
148 "-b", "--border", type=int, help="Crop the image from all sides by this amount."
149 )
150 @processor
151 def 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]]
155
156 if border is not None:
157 for idx, val in enumerate(box):
158 box[idx] = max(0, val - border)
159 click.echo(f"Cropping '{image.filename}' by {border}px")
160 yield copy_filename(image.crop(box), image)
161 else:
162 yield image
163
164
165 def convert_rotation(ctx, param, value):
166 if value is None:
167 return
168 value = value.lower()
169 if value in ("90", "r", "right"):
170 return (Image.ROTATE_90, 90)
171 if value in ("180", "-180"):
172 return (Image.ROTATE_180, 180)
173 if value in ("-90", "270", "l", "left"):
174 return (Image.ROTATE_270, 270)
175 raise click.BadParameter(f"invalid rotation '{value}'")
176
177
178 def convert_flip(ctx, param, value):
179 if value is None:
180 return
181 value = value.lower()
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")
186 raise click.BadParameter(f"invalid flip '{value}'")
187
188
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]")
194 @processor
195 def 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
200 click.echo(f"Rotate '{image.filename}' by {degrees}deg")
201 image = copy_filename(image.transpose(mode), image)
202 if flip is not None:
203 mode, direction = flip
204 click.echo(f"Flip '{image.filename}' {direction}")
205 image = copy_filename(image.transpose(mode), image)
206 yield image
207
208
209 @cli.command("blur")
210 @click.option("-r", "--radius", default=2, show_default=True, help="The blur radius.")
211 @processor
212 def blur_cmd(images, radius):
213 """Applies gaussian blur."""
214 blur = ImageFilter.GaussianBlur(radius)
215 for image in images:
216 click.echo(f"Blurring '{image.filename}' by {radius}px")
217 yield copy_filename(image.filter(blur), image)
218
219
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 )
228 @processor
229 def smoothen_cmd(images, iterations):
230 """Applies a smoothening filter."""
231 for image in images:
232 click.echo(
233 f"Smoothening {image.filename!r} {iterations}"
234 f" time{'s' if iterations != 1 else ''}"
235 )
236 for _ in range(iterations):
237 image = copy_filename(image.filter(ImageFilter.BLUR), image)
238 yield image
239
240
241 @cli.command("emboss")
242 @processor
243 def emboss_cmd(images):
244 """Embosses an image."""
245 for image in images:
246 click.echo(f"Embossing '{image.filename}'")
247 yield copy_filename(image.filter(ImageFilter.EMBOSS), image)
248
249
250 @cli.command("sharpen")
251 @click.option(
252 "-f", "--factor", default=2.0, help="Sharpens the image.", show_default=True
253 )
254 @processor
255 def sharpen_cmd(images, factor):
256 """Sharpens an image."""
257 for image in images:
258 click.echo(f"Sharpen '{image.filename}' by {factor}")
259 enhancer = ImageEnhance.Sharpness(image)
260 yield copy_filename(enhancer.enhance(max(1.0, factor)), image)
261
262
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.")
266 @processor
267 def paste_cmd(images, left, right):
268 """Pastes the second image on the first image and leaves the rest
269 unchanged.
270 """
271 imageiter = iter(images)
272 image = next(imageiter, None)
273 to_paste = next(imageiter, None)
274
275 if to_paste is None:
276 if image is not None:
277 yield image
278 return
279
280 click.echo(f"Paste '{to_paste.filename}' on '{image.filename}'")
281 mask = None
282 if to_paste.mode == "RGBA" or "transparency" in to_paste.info:
283 mask = to_paste
284 image.paste(to_paste, (left, right), mask)
285 image.filename += f"+{to_paste.filename}"
286 yield image
287
288 yield from imageiter