Debian Codegraph @

imageio/plugins/pillow.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # imageio is distributed under the terms of the (new) BSD License.
3
4 """Read/Write images using Pillow/PIL.
5
6 Backend Library: `Pillow <https://pillow.readthedocs.io/en/stable/>`_
7
8 Plugin that wraps the the Pillow library. Pillow is a friendly fork of PIL
9 (Python Image Library) and supports reading and writing of common formats (jpg,
10 png, gif, tiff, ...). For, the complete list of features and supported formats
11 please refer to pillows official docs (see the Backend Library link).
12
13 Parameters
14 ----------
15 request : Request
16 A request object representing the resource to be operated on.
17
18 Methods
19 -------
20
21 .. autosummary::
22 :toctree: _plugins/pillow
23
24 PillowPlugin.read
25 PillowPlugin.write
26 PillowPlugin.iter
27 PillowPlugin.get_meta
28
29 """
30
31 import sys
32 import warnings
33 from io import BytesIO
34 from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Union, cast
35
36 import numpy as np
37 from PIL import ExifTags, GifImagePlugin, Image, ImageSequence, UnidentifiedImageError
38 from PIL import __version__ as pil_version # type: ignore
39
40 from ..core.request import URI_BYTES, InitializationError, IOMode, Request
41 from ..core.v3_plugin_api import ImageProperties, PluginV3
42 from ..typing import ArrayLike
43
44
45 def pillow_version() -> Tuple[int]:
46 return tuple(int(x) for x in pil_version.split("."))
47
48
49 def _exif_orientation_transform(orientation: int, mode: str) -> Callable:
50 # get transformation that transforms an image from a
51 # given EXIF orientation into the standard orientation
52
53 # -1 if the mode has color channel, 0 otherwise
54 axis = -2 if Image.getmodebands(mode) > 1 else -1
55
56 EXIF_ORIENTATION = {
57 1: lambda x: x,
58 2: lambda x: np.flip(x, axis=axis),
59 3: lambda x: np.rot90(x, k=2),
60 4: lambda x: np.flip(x, axis=axis - 1),
61 5: lambda x: np.flip(np.rot90(x, k=3), axis=axis),
62 6: lambda x: np.rot90(x, k=3),
63 7: lambda x: np.flip(np.rot90(x, k=1), axis=axis),
64 8: lambda x: np.rot90(x, k=1),
65 }
66
67 # Some buggy/legacy software may not write the correct orientation (i.e. 0)
68 # No transformation if orientation is unknown or missing
69 return EXIF_ORIENTATION.get(orientation, lambda x: x)
70
71
72 class PillowPlugin(PluginV3):
73 def __init__(self, request: Request) -> None:
74 """Instantiate a new Pillow Plugin Object
75
76 Parameters
77 ----------
78 request : {Request}
79 A request object representing the resource to be operated on.
80
81 """
82
83 super().__init__(request)
84
85 # Register HEIF opener for Pillow
86 try:
87 from pillow_heif import register_heif_opener
88 except ImportError:
89 pass
90 else:
91 register_heif_opener()
92
93 # Register AVIF opener for Pillow
94 try:
95 from pillow_heif import register_avif_opener
96 except ImportError:
97 pass
98 else:
99 register_avif_opener()
100
101 self._image: Image = None
102 self.images_to_write = []
103
104 if request.mode.io_mode == IOMode.read:
105 try:
106 # Check if it is generally possible to read the image.
107 # This will not read any data and merely try to find a
108 # compatible pillow plugin (ref: the pillow docs).
109 image = Image.open(request.get_file())
110 except UnidentifiedImageError:
111 if request._uri_type == URI_BYTES:
112 raise InitializationError(
113 "Pillow can not read the provided bytes."
114 ) from None
115 else:
116 raise InitializationError(
117 f"Pillow can not read {request.raw_uri}."
118 ) from None
119
120 self._image = image
121 else:
122 self.save_args = {}
123
124 extension = self.request.extension or self.request.format_hint
125 if extension is None:
126 warnings.warn(
127 "Can't determine file format to write as. You _must_"
128 " set `format` during write or the call will fail. Use "
129 "`extension` to suppress this warning. ",
130 UserWarning,
131 )
132 return
133
134 tirage = [Image.preinit, Image.init]
135 for format_loader in tirage:
136 format_loader()
137 if extension in Image.registered_extensions().keys():
138 return
139
140 raise InitializationError(
141 f"Pillow can not write `{extension}` files."
142 ) from None
143
144 def close(self) -> None:
145 self._flush_writer()
146
147 if self._image:
148 self._image.close()
149
150 self._request.finish()
151
152 def read(
153 self,
154 *,
155 index: int = None,
156 mode: str = None,
157 rotate: bool = False,
158 apply_gamma: bool = False,
159 writeable_output: bool = True,
160 pilmode: str = None,
161 exifrotate: bool = None,
162 as_gray: bool = None,
163 ) -> np.ndarray:
164 """
165 Parses the given URI and creates a ndarray from it.
166
167 Parameters
168 ----------
169 index : int
170 If the ImageResource contains multiple ndimages, and index is an
171 integer, select the index-th ndimage from among them and return it.
172 If index is an ellipsis (...), read all ndimages in the file and
173 stack them along a new batch dimension and return them. If index is
174 None, this plugin reads the first image of the file (index=0) unless
175 the image is a GIF or APNG, in which case all images are read
176 (index=...).
177 mode : str
178 Convert the image to the given mode before returning it. If None,
179 the mode will be left unchanged. Possible modes can be found at:
180 https://pillow.readthedocs.io/en/stable/handbook/concepts.html#modes
181 rotate : bool
182 If True and the image contains an EXIF orientation tag,
183 apply the orientation before returning the ndimage.
184 apply_gamma : bool
185 If True and the image contains metadata about gamma, apply gamma
186 correction to the image.
187 writable_output : bool
188 If True, ensure that the image is writable before returning it to
189 the user. This incurs a full copy of the pixel data if the data
190 served by pillow is read-only. Consequently, setting this flag to
191 False improves performance for some images.
192 pilmode : str
193 Deprecated, use `mode` instead.
194 exifrotate : bool
195 Deprecated, use `rotate` instead.
196 as_gray : bool
197 Deprecated. Exists to raise a constructive error message.
198
199 Returns
200 -------
201 ndimage : ndarray
202 A numpy array containing the loaded image data
203
204 Notes
205 -----
206 If you read a paletted image (e.g. GIF) then the plugin will apply the
207 palette by default. Should you wish to read the palette indices of each
208 pixel use ``mode="P"``. The corresponding color palette can be found in
209 the image's metadata using the ``palette`` key when metadata is
210 extracted using the ``exclude_applied=False`` kwarg. The latter is
211 needed, as palettes are applied by default and hence excluded by default
212 to keep metadata and pixel data consistent.
213
214 """
215
216 if pilmode is not None:
217 warnings.warn(
218 "`pilmode` is deprecated. Use `mode` instead.", DeprecationWarning
219 )
220 mode = pilmode
221
222 if exifrotate is not None:
223 warnings.warn(
224 "`exifrotate` is deprecated. Use `rotate` instead.", DeprecationWarning
225 )
226 rotate = exifrotate
227
228 if as_gray is not None:
229 raise TypeError(
230 "The keyword `as_gray` is no longer supported."
231 "Use `mode='F'` for a backward-compatible result, or "
232 " `mode='L'` for an integer-valued result."
233 )
234
235 if self._image.format == "GIF":
236 # Converting GIF P frames to RGB
237 # https://github.com/python-pillow/Pillow/pull/6150
238 GifImagePlugin.LOADING_STRATEGY = (
239 GifImagePlugin.LoadingStrategy.RGB_AFTER_DIFFERENT_PALETTE_ONLY
240 )
241
242 if index is None:
243 if self._image.format == "GIF":
244 index = Ellipsis
245 elif self._image.custom_mimetype == "image/apng":
246 index = Ellipsis
247 else:
248 index = 0
249
250 if isinstance(index, int):
251 # will raise IO error if index >= number of frames in image
252 self._image.seek(index)
253 image = self._apply_transforms(
254 self._image, mode, rotate, apply_gamma, writeable_output
255 )
256 else:
257 iterator = self.iter(
258 mode=mode,
259 rotate=rotate,
260 apply_gamma=apply_gamma,
261 writeable_output=writeable_output,
262 )
263 image = np.stack([im for im in iterator], axis=0)
264
265 return image
266
267 def iter(
268 self,
269 *,
270 mode: str = None,
271 rotate: bool = False,
272 apply_gamma: bool = False,
273 writeable_output: bool = True,
274 ) -> Iterator[np.ndarray]:
275 """
276 Iterate over all ndimages/frames in the URI
277
278 Parameters
279 ----------
280 mode : {str, None}
281 Convert the image to the given mode before returning it. If None,
282 the mode will be left unchanged. Possible modes can be found at:
283 https://pillow.readthedocs.io/en/stable/handbook/concepts.html#modes
284 rotate : {bool}
285 If set to ``True`` and the image contains an EXIF orientation tag,
286 apply the orientation before returning the ndimage.
287 apply_gamma : {bool}
288 If ``True`` and the image contains metadata about gamma, apply gamma
289 correction to the image.
290 writable_output : bool
291 If True, ensure that the image is writable before returning it to
292 the user. This incurs a full copy of the pixel data if the data
293 served by pillow is read-only. Consequently, setting this flag to
294 False improves performance for some images.
295 """
296
297 for im in ImageSequence.Iterator(self._image):
298 yield self._apply_transforms(
299 im, mode, rotate, apply_gamma, writeable_output
300 )
301
302 def _apply_transforms(
303 self, image, mode, rotate, apply_gamma, writeable_output
304 ) -> np.ndarray:
305 if mode is not None:
306 image = image.convert(mode)
307 elif image.mode == "P":
308 # adjust for pillow9 changes
309 # see: https://github.com/python-pillow/Pillow/issues/5929
310 image = image.convert(image.palette.mode)
311 elif image.format == "PNG" and image.mode == "I":
312 major, minor, patch = pillow_version()
313
314 if sys.byteorder == "little":
315 desired_mode = "I;16"
316 else: # pragma: no cover
317 # can't test big-endian in GH-Actions
318 desired_mode = "I;16B"
319
320 if major < 10: # pragma: no cover
321 warnings.warn(
322 "Loading 16-bit (uint16) PNG as int32 due to limitations "
323 "in pillow's PNG decoder. This will be fixed in a future "
324 "version of pillow which will make this warning disappear.",
325 UserWarning,
326 )
327 elif minor < 1: # pragma: no cover
328 # pillow<10.1.0 can directly decode into 16-bit grayscale
329 image.mode = desired_mode
330 else:
331 # pillow >= 10.1.0
332 image = image.convert(desired_mode)
333
334 image = np.asarray(image)
335
336 meta = self.metadata(index=self._image.tell(), exclude_applied=False)
337 if rotate and "Orientation" in meta:
338 transformation = _exif_orientation_transform(
339 meta["Orientation"], self._image.mode
340 )
341 image = transformation(image)
342
343 if apply_gamma and "gamma" in meta:
344 gamma = float(meta["gamma"])
345 scale = float(65536 if image.dtype == np.uint16 else 255)
346 gain = 1.0
347 image = ((image / scale) ** gamma) * scale * gain + 0.4999
348 image = np.round(image).astype(np.uint8)
349
350 if writeable_output and not image.flags["WRITEABLE"]:
351 image = np.array(image)
352
353 return image
354
355 def write(
356 self,
357 ndimage: Union[ArrayLike, List[ArrayLike]],
358 *,
359 mode: str = None,
360 format: str = None,
361 is_batch: bool = None,
362 **kwargs,
363 ) -> Optional[bytes]:
364 """
365 Write an ndimage to the URI specified in path.
366
367 If the URI points to a file on the current host and the file does not
368 yet exist it will be created. If the file exists already, it will be
369 appended if possible; otherwise, it will be replaced.
370
371 If necessary, the image is broken down along the leading dimension to
372 fit into individual frames of the chosen format. If the format doesn't
373 support multiple frames, and IOError is raised.
374
375 Parameters
376 ----------
377 image : ndarray or list
378 The ndimage to write. If a list is given each element is expected to
379 be an ndimage.
380 mode : str
381 Specify the image's color format. If None (default), the mode is
382 inferred from the array's shape and dtype. Possible modes can be
383 found at:
384 https://pillow.readthedocs.io/en/stable/handbook/concepts.html#modes
385 format : str
386 Optional format override. If omitted, the format to use is
387 determined from the filename extension. If a file object was used
388 instead of a filename, this parameter must always be used.
389 is_batch : bool
390 Explicitly tell the writer that ``image`` is a batch of images
391 (True) or not (False). If None, the writer will guess this from the
392 provided ``mode`` or ``image.shape``. While the latter often works,
393 it may cause problems for small images due to aliasing of spatial
394 and color-channel axes.
395 kwargs : ...
396 Extra arguments to pass to pillow. If a writer doesn't recognise an
397 option, it is silently ignored. The available options are described
398 in pillow's `image format documentation
399 <https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html>`_
400 for each writer.
401
402 Notes
403 -----
404 When writing batches of very narrow (2-4 pixels wide) gray images set
405 the ``mode`` explicitly to avoid the batch being identified as a colored
406 image.
407
408 """
409 if "fps" in kwargs:
410 warnings.warn(
411 "The keyword `fps` is no longer supported. Use `duration`"
412 "(in ms) instead, e.g. `fps=50` == `duration=20` (1000 * 1/50).",
413 DeprecationWarning,
414 )
415 kwargs["duration"] = 1000 * 1 / kwargs.get("fps")
416
417 if isinstance(ndimage, list):
418 ndimage = np.stack(ndimage, axis=0)
419 is_batch = True
420 else:
421 ndimage = np.asarray(ndimage)
422
423 # check if ndimage is a batch of frames/pages (e.g. for writing GIF)
424 # if mode is given, use it; otherwise fall back to image.ndim only
425 if is_batch is not None:
426 pass
427 elif mode is not None:
428 is_batch = (
429 ndimage.ndim > 3 if Image.getmodebands(mode) > 1 else ndimage.ndim > 2
430 )
431 elif ndimage.ndim == 2:
432 is_batch = False
433 elif ndimage.ndim == 3 and ndimage.shape[-1] == 1:
434 raise ValueError("Can't write images with one color channel.")
435 elif ndimage.ndim == 3 and ndimage.shape[-1] in [2, 3, 4]:
436 # Note: this makes a channel-last assumption
437 is_batch = False
438 else:
439 is_batch = True
440
441 if not is_batch:
442 ndimage = ndimage[None, ...]
443
444 for frame in ndimage:
445 if mode is None:
446 pil_frame = Image.fromarray(frame)
447 else:
448 pil_frame = Image.fromarray(frame, mode=mode)
449 if "bits" in kwargs:
450 pil_frame = pil_frame.quantize(colors=2 ** kwargs["bits"])
451 self.images_to_write.append(pil_frame)
452
453 if (
454 format is not None
455 and "format" in self.save_args
456 and self.save_args["format"] != format
457 ):
458 old_format = self.save_args["format"]
459 warnings.warn(
460 "Changing the output format during incremental"
461 " writes is strongly discouraged."
462 f" Was `{old_format}`, is now `{format}`.",
463 UserWarning,
464 )
465
466 extension = self.request.extension or self.request.format_hint
467 self.save_args["format"] = format or Image.registered_extensions()[extension]
468 self.save_args.update(kwargs)
469
470 # when writing to `bytes` we flush instantly
471 result = None
472 if self._request._uri_type == URI_BYTES:
473 self._flush_writer()
474 file = cast(BytesIO, self._request.get_file())
475 result = file.getvalue()
476
477 return result
478
479 def _flush_writer(self):
480 if len(self.images_to_write) == 0:
481 return
482
483 primary_image = self.images_to_write.pop(0)
484
485 if len(self.images_to_write) > 0:
486 self.save_args["save_all"] = True
487 self.save_args["append_images"] = self.images_to_write
488
489 primary_image.save(self._request.get_file(), **self.save_args)
490 self.images_to_write.clear()
491 self.save_args.clear()
492
493 def get_meta(self, *, index=0) -> Dict[str, Any]:
494 return self.metadata(index=index, exclude_applied=False)
495
496 def metadata(
497 self, index: int = None, exclude_applied: bool = True
498 ) -> Dict[str, Any]:
499 """Read ndimage metadata.
500
501 Parameters
502 ----------
503 index : {integer, None}
504 If the ImageResource contains multiple ndimages, and index is an
505 integer, select the index-th ndimage from among them and return its
506 metadata. If index is an ellipsis (...), read and return global
507 metadata. If index is None, this plugin reads metadata from the
508 first image of the file (index=0) unless the image is a GIF or APNG,
509 in which case global metadata is read (index=...).
510 exclude_applied : bool
511 If True, exclude metadata fields that are applied to the image while
512 reading. For example, if the binary data contains a rotation flag,
513 the image is rotated by default and the rotation flag is excluded
514 from the metadata to avoid confusion.
515
516 Returns
517 -------
518 metadata : dict
519 A dictionary of format-specific metadata.
520
521 """
522
523 if index is None:
524 if self._image.format == "GIF":
525 index = Ellipsis
526 elif self._image.custom_mimetype == "image/apng":
527 index = Ellipsis
528 else:
529 index = 0
530
531 if isinstance(index, int) and self._image.tell() != index:
532 self._image.seek(index)
533
534 metadata = self._image.info.copy()
535 metadata["mode"] = self._image.mode
536 metadata["shape"] = self._image.size
537
538 if self._image.mode == "P" and not exclude_applied:
539 metadata["palette"] = np.asarray(tuple(self._image.palette.colors.keys()))
540
541 if self._image.getexif():
542 exif_data = {
543 ExifTags.TAGS.get(key, "unknown"): value
544 for key, value in dict(self._image.getexif()).items()
545 }
546 exif_data.pop("unknown", None)
547 metadata.update(exif_data)
548
549 if exclude_applied:
550 metadata.pop("Orientation", None)
551
552 return metadata
553
554 def properties(self, index: int = None) -> ImageProperties:
555 """Standardized ndimage metadata
556 Parameters
557 ----------
558 index : int
559 If the ImageResource contains multiple ndimages, and index is an
560 integer, select the index-th ndimage from among them and return its
561 properties. If index is an ellipsis (...), read and return the
562 properties of all ndimages in the file stacked along a new batch
563 dimension. If index is None, this plugin reads and returns the
564 properties of the first image (index=0) unless the image is a GIF or
565 APNG, in which case it reads and returns the properties all images
566 (index=...).
567
568 Returns
569 -------
570 properties : ImageProperties
571 A dataclass filled with standardized image metadata.
572
573 Notes
574 -----
575 This does not decode pixel data and is fast for large images.
576
577 """
578
579 if index is None:
580 if self._image.format == "GIF":
581 index = Ellipsis
582 elif self._image.custom_mimetype == "image/apng":
583 index = Ellipsis
584 else:
585 index = 0
586
587 if index is Ellipsis:
588 self._image.seek(0)
589 else:
590 self._image.seek(index)
591
592 if self._image.mode == "P":
593 # mode of palette images is determined by their palette
594 mode = self._image.palette.mode
595 else:
596 mode = self._image.mode
597
598 width: int = self._image.width
599 height: int = self._image.height
600 shape: Tuple[int, ...] = (height, width)
601
602 n_frames: Optional[int] = None
603 if index is ...:
604 n_frames = getattr(self._image, "n_frames", 1)
605 shape = (n_frames, *shape)
606
607 dummy = np.asarray(Image.new(mode, (1, 1)))
608 pil_shape: Tuple[int, ...] = dummy.shape
609 if len(pil_shape) > 2:
610 shape = (*shape, *pil_shape[2:])
611
612 return ImageProperties(
613 shape=shape,
614 dtype=dummy.dtype,
615 n_images=n_frames,
616 is_batch=index is Ellipsis,
617 )