File: reference.rst

package info (click to toggle)
willow 1.11.0-0.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,952 kB
  • sloc: xml: 20,346; python: 3,969; makefile: 153; sh: 11
file content (425 lines) | stat: -rw-r--r-- 12,484 bytes parent folder | download
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
Reference
=========


The ``Image`` class
-------------------

.. class:: Image

.. classmethod:: open(file)

    Opens the provided image file detects the format from the image header using
    Python's :mod:`filetype` module.

    Returns a subclass of :class:`ImageFile`

    If the image format is unrecognized, this throws a :class:`willow.image.UnrecognisedImageFormatError`
    (a subclass of :class:`IOError`)

.. classmethod:: operation

    A decorator for registering operations.

    The operations will be automatically registered when the image class is registered.

    .. code-block:: python

        from willow.image import Image

        class MyImage(Image):

            @Image.operation
            def resize(self, size):
                return MyImage(self.image.resize(size))

.. classmethod:: converter_from(other_classes, cost=100)

    A decorator for registering a "from" converter, which is a classmethod that
    converts an instance of another image class into an instance of this one.

    The ``other_classes`` parameter specifies which classes this converter can
    convert from. It can be a single class or a list.

    .. code-block:: python

        from willow.image import Image

        class MyImage(Image):
            ...

            @classmethod
            @Image.converter_from(JPEGImageFile)
            def open_jpeg_file(cls, image_file):
                return cls(image=open_jpeg(image_file.f))


    It can also be applied multiple times to the same function allowing different
    costs to be specified for different classes:

    .. code-block:: python

        @classmethod
        @Image.converter_from([JPEGImageFile, PNGImageFile])
        @Image.converter_from(GIFImageFile, cost=200)
        def open_file(cls, image_file):
            ...

.. classmethod:: converter_to(other_class, cost=100)

    A decorator for registering a "to" converter, which is a method that converts
    this image into an instance of another class.

    The ``other_class`` parameter specifies which class this function converts to.
    An individual "to" converter can only convert to a single class.

    .. code-block:: python

        from willow.image import Image

        class MyImage(Image):
            ...

            @Image.converter_to(PillowImage)
            def convert_to_pillow(self):
                image = PIL.Image()  # Code to create PIL image object here
                return PillowImage(image)

Builtin operations
------------------

Here's a full list of operations provided by Willow out of the box:

.. method:: get_size()

    Returns the size of the image as a tuple of two integers:

    .. code-block:: python

        width, height = image.get_size()

.. method:: get_frame_count()

    Returns the number of frames in an animated image:

    .. code-block:: python

        number_of_frames = image.get_frame_count()

.. method:: has_alpha

    Returns ``True`` if the image has an alpha channel.

    .. code-block:: python

        if image.has_alpha():
            # Image has alpha

.. method:: has_animation

    Returns ``True`` if the image is animated.

    .. code-block:: python

        if image.has_animation():
            # Image has animation

.. method:: resize(size)

    (supported natively for SVG, Pillow/Wand required for others)

    Stretches the image to fit the specified size. Size must be a sequence of two integers:

    .. code-block:: python

        # Resize the image to 100x100 pixels
        resized_image = source_image.resize((100, 100))

.. method:: crop(region)

    (supported natively for SVG, Pillow/Wand required for others)

    Cuts out the specified region of the image. The region must be a sequence of
    four integers (left, top, right, bottom):

    .. code-block:: python

        # Cut out a square from the middle of the image
        cropped_image = source_image.resize((100, 100, 200, 200))

    If the crop rectangle overlaps the image boundaries, it will be reduced to fit within those
    boundaries, resulting in an output image smaller than specified. If the crop rectangle is
    entirely outside the image, or the coordinates are out of range in any other way (such as
    a left coordinate greater than the right coordinate), this throws a
    :class:`willow.image.BadImageOperationError` (a subclass of :class:`ValueError`).

.. method:: set_background_color_rgb(color)

    (Pillow/Wand only)

    If the image has an alpha channel, this will add a background color using
    the alpha channel as a mask. The alpha channel will be removed from the
    resulting image.

    The background color must be specified as a tuple of three integers with
    values between 0 - 255.

    This operation will convert the image to RGB format, but will not do
    anything if there is not an alpha channel.

    .. code-block:: python

        # Set the background color of the image to white
        image = source_image.set_background_color_rgb((255, 255, 255))

.. method:: transform_colorspace_to_srgb(rendering_intent=0)

    (Pillow only)

    Note: This operation has no effect if the image does not have an embedded ICC color profile.

    Transforms the colors of the image to fit inside sRGB color gamut using data
    from the embedded ICC profile. The resulting image will always be in RGB format
    (or RGBA for images with transparency) and will have a small generic sRGB
    ICC profile embedded.

    A large number of devices lack the capability to display images
    in color spaces other than sRGB and will automatically squash the colors
    to fit inside sRGB gamut. In order to do this accurately, the device uses
    the embedded ICC profile. You can use this operation to do the same thing
    upfront and save on image size by replacing the (large) embedded profile with a
    small generic sRGB profile. Keep in mind that this operation is lossy, devices
    that *do* support wider color gamuts, like DCI-P3 or Adobe RGB, will not be
    able to display the image in its original colors if the original colors were
    outside of sRGB gamut.

    The ``rendering_intent`` parameter specifies the rendering intent to use.
    It defaults to 0 (perceptual). This controls how out-of-gamut colors are handled.

    It can be one of the following values:

    * ``0`` - Perceptual (default)
    * ``1`` - Relative colorimetric
    * ``2`` - Saturation
    * ``3`` - Absolute colorimetric

    .. code-block:: python

        image = image.transform_colorspace_to_srgb()

    `Read more about rendering intents on Wikipedia
    <https://en.wikipedia.org/wiki/Rendering_intent>`_.

    `Read more about color spaces on the web in this WebKit blog post
    <https://webkit.org/blog/6682/improving-color-on-the-web/>`_.

.. method:: auto_orient()

    (Pillow/Wand only)

    Some JPEG files have orientation data in an EXIF tag that needs to be applied
    to the image. This method applies this orientation to the image (it is a no-op
    for other image formats).

    This should be run before performing any other image operations.

    .. code-block:: python

        image = image.auto_orient()

.. method:: detect_features()

    (OpenCV only)

    Uses OpenCV to find the most prominent corners in the image.
    Useful for detecting interesting features for cropping against.

    Returns a list of two integer tuples containing the coordinates of each
    point on the image

    .. code-block:: python

        points = image.detect_features()

.. method:: detect_faces(cascade_filename)

    (OpenCV only)

    Uses OpenCV's `cascade classification
    <https://docs.opencv.org/2.4/modules/objdetect/doc/cascade_classification.html>`_
    to detect faces in the image.

    By default the ``haarcascade_frontalface_alt2.xml`` (provided by OpenCV)
    cascade file is used. You can specify the filename to a different cascade
    file in the first parameter.

    Returns a list of four integer tuples containing the left, top, right, bottom
    locations of each face detected in the image.

    .. code-block:: python

        faces = image.detect_faces()

.. method:: save_as_jpeg(file, quality=85, optimize=False)

    (Pillow/Wand only)

    Saves the image to the specified file-like object in JPEG format.

    Note: If the image has an alpha channel, this operation may raise an
    exception or save a broken image (depending on the backend being used).
    To resolve this, use the :meth:`~Image.set_background_color_rgb` method to
    replace the alpha channel with a solid background color before saving as JPEG.

    Returns a ``JPEGImageFile`` wrapping the file.

    .. code-block:: python

        with open('out.jpg', 'wb') as f:
            image.save_as_jpeg(f)

.. method:: save_as_png(file, optimize=False)

    (Pillow/Wand only)

    Saves the image to the specified file-like object in PNG format.

    Returns a ``PNGImageFile`` wrapping the file.

    .. code-block:: python

        with open('out.png', 'wb') as f:
            image.save_as_png(f)

.. method:: save_as_gif(file)

    (Pillow/Wand only)

    Saves the image to the specified file-like object in GIF format.

    returns a ``GIFImageFile`` wrapping the file.

    .. code-block:: python

        with open('out.gif', 'wb') as f:
            image.save_as_gif(f)

.. method:: save_as_webp(file, quality=80, lossless=False)

    (Pillow/Wand only)

    Saves the image to the specified file-like object in WEBP format.

    returns a ``WebPImageFile`` wrapping the file.

    .. code-block:: python

        with open('out.webp', 'wb') as f:
            image.save_as_webp(f)


.. method:: save_as_heic(file, quality=80, lossless=False)

    (Pillow only; requires the `pillow-heif <https://pypi.org/project/pillow-heif/>`_ library)

    Saves the image to the specified file-like object in HEIF format.

    returns a ``HeicImageFile`` wrapping the file.

    .. code-block:: python

        with open('out.heic', 'wb') as f:
            image.save_as_heic(f)


.. method:: save_as_avif(file, quality=80, lossless=False)

    (requires the `pillow-heif <https://pypi.org/project/pillow-heif/>`_ library)

    Saves the image to the specified file-like object in AVIF format.
    When saving with `lossless=True`, no `chroma subsampling <https://en.wikipedia.org/wiki/Chroma_subsampling>` is used (4:4:4 instead of the default 4:2:0).

    returns a ``AvifImageFile`` wrapping the file.

    .. code-block:: python

        with open('out.avif', 'wb') as f:
            image.save_as_avif(f)


.. method:: save_as_svg(file)

    (SVG images only)

    Saves the image to the specified file-like object in SVG format.

    returns a ``SvgImageFile`` wrapping the file.

    .. code-block:: python

        with open('out.svg', 'w') as f:
            image.save_as_svg(f)


.. method:: save_as_ico(file)

    Saves the image to the specified file-like object in ICO format.

    returns a ``IcoImageFile`` wrapping the file.

    .. code-block:: python

        with open('out.ico', 'w') as f:
            image.save_as_ico(f)


.. method:: get_pillow_image()

    (Pillow only)

    Returns a ``PIL.Image`` object for the specified image. This may be useful
    for reusing existing code that requires a Pillow image.

    .. code-block:: python

        do_thing(image.get_pillow_image())

    You can convert a ``PIL.Image`` object back into a Willow :class:`Image`
    using the ``PillowImage`` class:

    .. code-block:: python

        import PIL.Image
        from willow.plugins.pillow import PillowImage

        pillow_image = PIL.Image.open('test.jpg')
        image = PillowImage(pillow_image)

        # Now you can use any Willow operation on that image
        faces = image.detect_faces()

.. method:: get_wand_image()

    (Wand only)

    Returns a ``Wand.Image`` object for the specified image. This may be useful
    for reusing existing code that requires a Wand image.

    .. code-block:: python

        do_thing(image.get_wand_image())

    You can convert a ``Wand.Image`` object back into a Willow :class:`Image`
    using the ``WandImage`` class:

    .. code-block:: python

        from wand.image import Image
        from willow.plugins.wand import WandImage

        # wand_image is an instance of Wand.Image
        wand_image = Image(filename='pikachu.png')
        image = WandImage(wand_image)

        # Now you can use any Willow operation on that image
        faces = image.detect_faces()