Debian Codegraph @

imageio/plugins/pillow_legacy.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 (legacy).
5
6 Backend Library: `Pillow <https://pillow.readthedocs.io/en/stable/>`_
7
8 Pillow is a friendly fork of PIL (Python Image Library) and supports
9 reading and writing of common formats (jpg, png, gif, tiff, ...). While
10 these docs provide an overview of some of its features, pillow is
11 constantly improving. Hence, the complete list of features can be found
12 in pillows official docs (see the Backend Library link).
13
14 Parameters for Reading
15 ----------------------
16 pilmode : str
17 (Available for all formats except GIF-PIL)
18 From the Pillow documentation:
19
20 * 'L' (8-bit pixels, grayscale)
21 * 'P' (8-bit pixels, mapped to any other mode using a color palette)
22 * 'RGB' (3x8-bit pixels, true color)
23 * 'RGBA' (4x8-bit pixels, true color with transparency mask)
24 * 'CMYK' (4x8-bit pixels, color separation)
25 * 'YCbCr' (3x8-bit pixels, color video format)
26 * 'I' (32-bit signed integer pixels)
27 * 'F' (32-bit floating point pixels)
28
29 PIL also provides limited support for a few special modes, including
30 'LA' ('L' with alpha), 'RGBX' (true color with padding) and 'RGBa'
31 (true color with premultiplied alpha).
32
33 When translating a color image to grayscale (mode 'L', 'I' or 'F'),
34 the library uses the ITU-R 601-2 luma transform::
35
36 L = R * 299/1000 + G * 587/1000 + B * 114/1000
37 as_gray : bool
38 (Available for all formats except GIF-PIL)
39 If True, the image is converted using mode 'F'. When `mode` is
40 not None and `as_gray` is True, the image is first converted
41 according to `mode`, and the result is then "flattened" using
42 mode 'F'.
43 ignoregamma : bool
44 (Only available in PNG-PIL)
45 Avoid gamma correction. Default True.
46 exifrotate : bool
47 (Only available in JPEG-PIL)
48 Automatically rotate the image according to exif flag. Default True.
49
50
51 Parameters for saving
52 ---------------------
53 optimize : bool
54 (Only available in PNG-PIL)
55 If present and true, instructs the PNG writer to make the output file
56 as small as possible. This includes extra processing in order to find
57 optimal encoder settings.
58 transparency:
59 (Only available in PNG-PIL)
60 This option controls what color image to mark as transparent.
61 dpi: tuple of two scalars
62 (Only available in PNG-PIL)
63 The desired dpi in each direction.
64 pnginfo: PIL.PngImagePlugin.PngInfo
65 (Only available in PNG-PIL)
66 Object containing text tags.
67 compress_level: int
68 (Only available in PNG-PIL)
69 ZLIB compression level, a number between 0 and 9: 1 gives best speed,
70 9 gives best compression, 0 gives no compression at all. Default is 9.
71 When ``optimize`` option is True ``compress_level`` has no effect
72 (it is set to 9 regardless of a value passed).
73 compression: int
74 (Only available in PNG-PIL)
75 Compatibility with the freeimage PNG format. If given, it overrides
76 compress_level.
77 icc_profile:
78 (Only available in PNG-PIL)
79 The ICC Profile to include in the saved file.
80 bits (experimental): int
81 (Only available in PNG-PIL)
82 This option controls how many bits to store. If omitted,
83 the PNG writer uses 8 bits (256 colors).
84 quantize:
85 (Only available in PNG-PIL)
86 Compatibility with the freeimage PNG format. If given, it overrides
87 bits. In this case, given as a number between 1-256.
88 dictionary (experimental): dict
89 (Only available in PNG-PIL)
90 Set the ZLIB encoder dictionary.
91 prefer_uint8: bool
92 (Only available in PNG-PIL)
93 Let the PNG writer truncate uint16 image arrays to uint8 if their values fall
94 within the range [0, 255]. Defaults to true for legacy compatibility, however
95 it is recommended to set this to false to avoid unexpected behavior when
96 saving e.g. weakly saturated images.
97
98 quality : scalar
99 (Only available in JPEG-PIL)
100 The compression factor of the saved image (1..100), higher
101 numbers result in higher quality but larger file size. Default 75.
102 progressive : bool
103 (Only available in JPEG-PIL)
104 Save as a progressive JPEG file (e.g. for images on the web).
105 Default False.
106 optimize : bool
107 (Only available in JPEG-PIL)
108 On saving, compute optimal Huffman coding tables (can reduce a few
109 percent of file size). Default False.
110 dpi : tuple of int
111 (Only available in JPEG-PIL)
112 The pixel density, ``(x,y)``.
113 icc_profile : object
114 (Only available in JPEG-PIL)
115 If present and true, the image is stored with the provided ICC profile.
116 If this parameter is not provided, the image will be saved with no
117 profile attached.
118 exif : dict
119 (Only available in JPEG-PIL)
120 If present, the image will be stored with the provided raw EXIF data.
121 subsampling : str
122 (Only available in JPEG-PIL)
123 Sets the subsampling for the encoder. See Pillow docs for details.
124 qtables : object
125 (Only available in JPEG-PIL)
126 Set the qtables for the encoder. See Pillow docs for details.
127 quality_mode : str
128 (Only available in JPEG2000-PIL)
129 Either `"rates"` or `"dB"` depending on the units you want to use to
130 specify image quality.
131 quality : float
132 (Only available in JPEG2000-PIL)
133 Approximate size reduction (if quality mode is `rates`) or a signal to noise ratio
134 in decibels (if quality mode is `dB`).
135 loop : int
136 (Only available in GIF-PIL)
137 The number of iterations. Default 0 (meaning loop indefinitely).
138 duration : {float, list}
139 (Only available in GIF-PIL)
140 The duration (in milliseconds) of each frame. Either specify one value
141 that is used for all frames, or one value for each frame.
142 fps : float
143 (Only available in GIF-PIL)
144 The number of frames per second. If duration is not given, the
145 duration for each frame is set to 1/fps. Default 10.
146 palettesize : int
147 (Only available in GIF-PIL)
148 The number of colors to quantize the image to. Is rounded to
149 the nearest power of two. Default 256.
150 subrectangles : bool
151 (Only available in GIF-PIL)
152 If True, will try and optimize the GIF by storing only the
153 rectangular parts of each frame that change with respect to the
154 previous. Default False.
155
156 Notes
157 -----
158 To enable JPEG 2000 support, you need to build and install the OpenJPEG library,
159 version 2.0.0 or higher, before building the Python Imaging Library. Windows
160 users can install the OpenJPEG binaries available on the OpenJPEG website, but
161 must add them to their PATH in order to use PIL (if you fail to do this, you
162 will get errors about not being able to load the ``_imaging`` DLL).
163
164 GIF images read with this plugin are always RGBA. The alpha channel is ignored
165 when saving RGB images.
166 """
167
168 import logging
169 import threading
170
171 import numpy as np
172
173 from ..core import Format, image_as_uint
174 from ..core.request import URI_FILE, URI_BYTES
175
176 logger = logging.getLogger(__name__)
177
178
179 # todo: Pillow ImageGrab module supports grabbing the screen on Win and OSX.
180
181
182 GENERIC_DOCS = """
183 Parameters for reading
184 ----------------------
185
186 pilmode : str
187 From the Pillow documentation:
188
189 * 'L' (8-bit pixels, grayscale)
190 * 'P' (8-bit pixels, mapped to any other mode using a color palette)
191 * 'RGB' (3x8-bit pixels, true color)
192 * 'RGBA' (4x8-bit pixels, true color with transparency mask)
193 * 'CMYK' (4x8-bit pixels, color separation)
194 * 'YCbCr' (3x8-bit pixels, color video format)
195 * 'I' (32-bit signed integer pixels)
196 * 'F' (32-bit floating point pixels)
197
198 PIL also provides limited support for a few special modes, including
199 'LA' ('L' with alpha), 'RGBX' (true color with padding) and 'RGBa'
200 (true color with premultiplied alpha).
201
202 When translating a color image to grayscale (mode 'L', 'I' or 'F'),
203 the library uses the ITU-R 601-2 luma transform::
204
205 L = R * 299/1000 + G * 587/1000 + B * 114/1000
206 as_gray : bool
207 If True, the image is converted using mode 'F'. When `mode` is
208 not None and `as_gray` is True, the image is first converted
209 according to `mode`, and the result is then "flattened" using
210 mode 'F'.
211 """
212
213
214 class PillowFormat(Format):
215 """
216 Base format class for Pillow formats.
217 """
218
219 _pillow_imported = False
220 _Image = None
221 _modes = "i"
222 _description = ""
223
224 def __init__(self, *args, plugin_id: str = None, **kwargs):
225 super(PillowFormat, self).__init__(*args, **kwargs)
226 # Used to synchronize _init_pillow(), see #244
227 self._lock = threading.RLock()
228
229 self._plugin_id = plugin_id
230
231 @property
232 def plugin_id(self):
233 """The PIL plugin id."""
234 return self._plugin_id # Set when format is created
235
236 def _init_pillow(self):
237 with self._lock:
238 if not self._pillow_imported:
239 self._pillow_imported = True # more like tried to import
240 import PIL
241
242 if not hasattr(PIL, "__version__"): # pragma: no cover
243 raise ImportError(
244 "Imageio Pillow plugin requires " "Pillow, not PIL!"
245 )
246 from PIL import Image
247
248 self._Image = Image
249 elif self._Image is None: # pragma: no cover
250 raise RuntimeError("Imageio Pillow plugin requires " "Pillow lib.")
251 Image = self._Image
252
253 if self.plugin_id in ("PNG", "JPEG", "BMP", "GIF", "PPM"):
254 Image.preinit()
255 else:
256 Image.init()
257 return Image
258
259 def _can_read(self, request):
260 Image = self._init_pillow()
261 if self.plugin_id in Image.OPEN:
262 factory, accept = Image.OPEN[self.plugin_id]
263 if accept:
264 if request.firstbytes and accept(request.firstbytes):
265 return True
266
267 def _can_write(self, request):
268 Image = self._init_pillow()
269 if request.extension in self.extensions or request._uri_type in [
270 URI_FILE,
271 URI_BYTES,
272 ]:
273 if self.plugin_id in Image.SAVE:
274 return True
275
276 class Reader(Format.Reader):
277 def _open(self, pilmode=None, as_gray=False):
278 Image = self.format._init_pillow()
279 try:
280 factory, accept = Image.OPEN[self.format.plugin_id]
281 except KeyError:
282 raise RuntimeError("Format %s cannot read images." % self.format.name)
283 self._fp = self._get_file()
284 self._im = factory(self._fp, "")
285 if hasattr(Image, "_decompression_bomb_check"):
286 Image._decompression_bomb_check(self._im.size)
287 # Save the raw mode used by the palette for a BMP because it may not be the number of channels
288 # When the data is read, imageio hands the palette to PIL to handle and clears the rawmode argument
289 # However, there is a bug in PIL with handling animated GIFs with a different color palette on each frame.
290 # This issue is resolved by using the raw palette data but the rawmode information is now lost. So we
291 # store the raw mode for later use
292 if self._im.palette and self._im.palette.dirty:
293 self._im.palette.rawmode_saved = self._im.palette.rawmode
294 pil_try_read(self._im)
295 # Store args
296 self._kwargs = dict(
297 as_gray=as_gray, is_gray=_palette_is_grayscale(self._im)
298 )
299 # setting mode=None is not the same as just not providing it
300 if pilmode is not None:
301 self._kwargs["mode"] = pilmode
302 # Set length
303 self._length = 1
304 if hasattr(self._im, "n_frames"):
305 self._length = self._im.n_frames
306
307 def _get_file(self):
308 self._we_own_fp = False
309 return self.request.get_file()
310
311 def _close(self):
312 save_pillow_close(self._im)
313 if self._we_own_fp:
314 self._fp.close()
315 # else: request object handles closing the _fp
316
317 def _get_length(self):
318 return self._length
319
320 def _seek(self, index):
321 try:
322 self._im.seek(index)
323 except EOFError:
324 raise IndexError("Could not seek to index %i" % index)
325
326 def _get_data(self, index):
327 if index >= self._length:
328 raise IndexError("Image index %i > %i" % (index, self._length))
329 i = self._im.tell()
330 if i > index:
331 self._seek(index) # just try
332 else:
333 while i < index: # some formats need to be read in sequence
334 i += 1
335 self._seek(i)
336 if self._im.palette and self._im.palette.dirty:
337 self._im.palette.rawmode_saved = self._im.palette.rawmode
338 self._im.load()
339 im = pil_get_frame(self._im, **self._kwargs)
340 return im, self._im.info
341
342 def _get_meta_data(self, index):
343 if not (index is None or index == 0):
344 raise IndexError()
345 return self._im.info
346
347 class Writer(Format.Writer):
348 def _open(self):
349 Image = self.format._init_pillow()
350 try:
351 self._save_func = Image.SAVE[self.format.plugin_id]
352 except KeyError:
353 raise RuntimeError("Format %s cannot write images." % self.format.name)
354 self._fp = self.request.get_file()
355 self._meta = {}
356 self._written = False
357
358 def _close(self):
359 pass # request object handled closing _fp
360
361 def _append_data(self, im, meta):
362 if self._written:
363 raise RuntimeError(
364 "Format %s only supports single images." % self.format.name
365 )
366 # Pop unit dimension for grayscale images
367 if im.ndim == 3 and im.shape[-1] == 1:
368 im = im[:, :, 0]
369 self._written = True
370 self._meta.update(meta)
371 img = ndarray_to_pil(
372 im, self.format.plugin_id, self._meta.pop("prefer_uint8", True)
373 )
374 if "bits" in self._meta:
375 img = img.quantize() # Make it a P image, so bits arg is used
376 img.save(self._fp, format=self.format.plugin_id, **self._meta)
377 save_pillow_close(img)
378
379 def set_meta_data(self, meta):
380 self._meta.update(meta)
381
382
383 class PNGFormat(PillowFormat):
384 """See :mod:`imageio.plugins.pillow_legacy`"""
385
386 class Reader(PillowFormat.Reader):
387 def _open(self, pilmode=None, as_gray=False, ignoregamma=True):
388 return PillowFormat.Reader._open(self, pilmode=pilmode, as_gray=as_gray)
389
390 def _get_data(self, index):
391 im, info = PillowFormat.Reader._get_data(self, index)
392 if not self.request.kwargs.get("ignoregamma", True):
393 # The gamma value in the file represents the gamma factor for the
394 # hardware on the system where the file was created, and is meant
395 # to be able to match the colors with the system on which the
396 # image is shown. See also issue #366
397 try:
398 gamma = float(info["gamma"])
399 except (KeyError, ValueError):
400 pass
401 else:
402 scale = float(65536 if im.dtype == np.uint16 else 255)
403 gain = 1.0
404 im[:] = ((im / scale) ** gamma) * scale * gain + 0.4999
405 return im, info
406
407 # --
408
409 class Writer(PillowFormat.Writer):
410 def _open(self, compression=None, quantize=None, interlaced=False, **kwargs):
411 # Better default for compression
412 kwargs["compress_level"] = kwargs.get("compress_level", 9)
413
414 if compression is not None:
415 if compression < 0 or compression > 9:
416 raise ValueError("Invalid PNG compression level: %r" % compression)
417 kwargs["compress_level"] = compression
418 if quantize is not None:
419 for bits in range(1, 9):
420 if 2**bits == quantize:
421 break
422 else:
423 raise ValueError(
424 "PNG quantize must be power of two, " "not %r" % quantize
425 )
426 kwargs["bits"] = bits
427 if interlaced:
428 logger.warning("PIL PNG writer cannot produce interlaced images.")
429
430 ok_keys = (
431 "optimize",
432 "transparency",
433 "dpi",
434 "pnginfo",
435 "bits",
436 "compress_level",
437 "icc_profile",
438 "dictionary",
439 "prefer_uint8",
440 )
441 for key in kwargs:
442 if key not in ok_keys:
443 raise TypeError("Invalid arg for PNG writer: %r" % key)
444
445 PillowFormat.Writer._open(self)
446 self._meta.update(kwargs)
447
448 def _append_data(self, im, meta):
449 if str(im.dtype) == "uint16" and (im.ndim == 2 or im.shape[-1] == 1):
450 im = image_as_uint(im, bitdepth=16)
451 else:
452 im = image_as_uint(im, bitdepth=8)
453 PillowFormat.Writer._append_data(self, im, meta)
454
455
456 class JPEGFormat(PillowFormat):
457 """See :mod:`imageio.plugins.pillow_legacy`"""
458
459 class Reader(PillowFormat.Reader):
460 def _open(self, pilmode=None, as_gray=False, exifrotate=True):
461 return PillowFormat.Reader._open(self, pilmode=pilmode, as_gray=as_gray)
462
463 def _get_file(self):
464 # Pillow uses seek for JPG, so we cannot directly stream from web
465 if self.request.filename.startswith(
466 ("http://", "https://")
467 ) or ".zip/" in self.request.filename.replace("\\", "/"):
468 self._we_own_fp = True
469 return open(self.request.get_local_filename(), "rb")
470 else:
471 self._we_own_fp = False
472 return self.request.get_file()
473
474 def _get_data(self, index):
475 im, info = PillowFormat.Reader._get_data(self, index)
476
477 # Handle exif
478 if "exif" in info:
479 from PIL.ExifTags import TAGS
480
481 info["EXIF_MAIN"] = {}
482 for tag, value in self._im._getexif().items():
483 decoded = TAGS.get(tag, tag)
484 info["EXIF_MAIN"][decoded] = value
485
486 im = self._rotate(im, info)
487 return im, info
488
489 def _rotate(self, im, meta):
490 """Use Orientation information from EXIF meta data to
491 orient the image correctly. Similar code as in FreeImage plugin.
492 """
493 if self.request.kwargs.get("exifrotate", True):
494 try:
495 ori = meta["EXIF_MAIN"]["Orientation"]
496 except KeyError: # pragma: no cover
497 pass # Orientation not available
498 else: # pragma: no cover - we cannot touch all cases
499 # www.impulseadventure.com/photo/exif-orientation.html
500 if ori in [1, 2]:
501 pass
502 if ori in [3, 4]:
503 im = np.rot90(im, 2)
504 if ori in [5, 6]:
505 im = np.rot90(im, 3)
506 if ori in [7, 8]:
507 im = np.rot90(im)
508 if ori in [2, 4, 5, 7]: # Flipped cases (rare)
509 im = np.fliplr(im)
510 return im
511
512 # --
513
514 class Writer(PillowFormat.Writer):
515 def _open(self, quality=75, progressive=False, optimize=False, **kwargs):
516 # The JPEG quality can be between 0 (worst) and 100 (best)
517 quality = int(quality)
518 if quality < 0 or quality > 100:
519 raise ValueError("JPEG quality should be between 0 and 100.")
520
521 kwargs["quality"] = quality
522 kwargs["progressive"] = bool(progressive)
523 kwargs["optimize"] = bool(progressive)
524
525 PillowFormat.Writer._open(self)
526 self._meta.update(kwargs)
527
528 def _append_data(self, im, meta):
529 if im.ndim == 3 and im.shape[-1] == 4:
530 raise IOError("JPEG does not support alpha channel.")
531 im = image_as_uint(im, bitdepth=8)
532 PillowFormat.Writer._append_data(self, im, meta)
533 return
534
535
536 class JPEG2000Format(PillowFormat):
537 """See :mod:`imageio.plugins.pillow_legacy`"""
538
539 class Reader(PillowFormat.Reader):
540 def _open(self, pilmode=None, as_gray=False):
541 return PillowFormat.Reader._open(self, pilmode=pilmode, as_gray=as_gray)
542
543 def _get_file(self):
544 # Pillow uses seek for JPG, so we cannot directly stream from web
545 if self.request.filename.startswith(
546 ("http://", "https://")
547 ) or ".zip/" in self.request.filename.replace("\\", "/"):
548 self._we_own_fp = True
549 return open(self.request.get_local_filename(), "rb")
550 else:
551 self._we_own_fp = False
552 return self.request.get_file()
553
554 def _get_data(self, index):
555 im, info = PillowFormat.Reader._get_data(self, index)
556
557 # Handle exif
558 if "exif" in info:
559 from PIL.ExifTags import TAGS
560
561 info["EXIF_MAIN"] = {}
562 for tag, value in self._im._getexif().items():
563 decoded = TAGS.get(tag, tag)
564 info["EXIF_MAIN"][decoded] = value
565
566 im = self._rotate(im, info)
567 return im, info
568
569 def _rotate(self, im, meta):
570 """Use Orientation information from EXIF meta data to
571 orient the image correctly. Similar code as in FreeImage plugin.
572 """
573 if self.request.kwargs.get("exifrotate", True):
574 try:
575 ori = meta["EXIF_MAIN"]["Orientation"]
576 except KeyError: # pragma: no cover
577 pass # Orientation not available
578 else: # pragma: no cover - we cannot touch all cases
579 # www.impulseadventure.com/photo/exif-orientation.html
580 if ori in [1, 2]:
581 pass
582 if ori in [3, 4]:
583 im = np.rot90(im, 2)
584 if ori in [5, 6]:
585 im = np.rot90(im, 3)
586 if ori in [7, 8]:
587 im = np.rot90(im)
588 if ori in [2, 4, 5, 7]: # Flipped cases (rare)
589 im = np.fliplr(im)
590 return im
591
592 # --
593
594 class Writer(PillowFormat.Writer):
595 def _open(self, quality_mode="rates", quality=5, **kwargs):
596 # Check quality - in Pillow it should be no higher than 95
597 if quality_mode not in {"rates", "dB"}:
598 raise ValueError("Quality mode should be either 'rates' or 'dB'")
599
600 quality = float(quality)
601
602 if quality_mode == "rates" and (quality < 1 or quality > 1000):
603 raise ValueError(
604 "The quality value {} seems to be an invalid rate!".format(quality)
605 )
606 elif quality_mode == "dB" and (quality < 15 or quality > 100):
607 raise ValueError(
608 "The quality value {} seems to be an invalid PSNR!".format(quality)
609 )
610
611 kwargs["quality_mode"] = quality_mode
612 kwargs["quality_layers"] = [quality]
613
614 PillowFormat.Writer._open(self)
615 self._meta.update(kwargs)
616
617 def _append_data(self, im, meta):
618 if im.ndim == 3 and im.shape[-1] == 4:
619 raise IOError(
620 "The current implementation of JPEG 2000 does not support alpha channel."
621 )
622 im = image_as_uint(im, bitdepth=8)
623 PillowFormat.Writer._append_data(self, im, meta)
624 return
625
626
627 def save_pillow_close(im):
628 # see issue #216 and #300
629 if hasattr(im, "close"):
630 if hasattr(getattr(im, "fp", None), "close"):
631 im.close()
632
633
634 # Func from skimage
635
636 # This cells contains code from scikit-image, in particular from
637 # http://github.com/scikit-image/scikit-image/blob/master/
638 # skimage/io/_plugins/pil_plugin.py
639 # The scikit-image license applies.
640
641
642 def pil_try_read(im):
643 try:
644 # this will raise an IOError if the file is not readable
645 im.load()
646 except IOError as e:
647 site = "http://pillow.readthedocs.io/en/latest/installation.html"
648 site += "#external-libraries"
649 pillow_error_message = str(e)
650 error_message = (
651 'Could not load "%s" \n'
652 'Reason: "%s"\n'
653 "Please see documentation at: %s"
654 % (im.filename, pillow_error_message, site)
655 )
656 raise ValueError(error_message)
657
658
659 def _palette_is_grayscale(pil_image):
660 if pil_image.mode != "P":
661 return False
662 elif pil_image.info.get("transparency", None): # see issue #475
663 return False
664 # get palette as an array with R, G, B columns
665 # Note: starting in pillow 9.1 palettes may have less than 256 entries
666 palette = np.asarray(pil_image.getpalette()).reshape((-1, 3))
667 # Not all palette colors are used; unused colors have junk values.
668 start, stop = pil_image.getextrema()
669 valid_palette = palette[start : stop + 1]
670 # Image is grayscale if channel differences (R - G and G - B)
671 # are all zero.
672 return np.allclose(np.diff(valid_palette), 0)
673
674
675 def pil_get_frame(im, is_gray=None, as_gray=None, mode=None, dtype=None):
676 """
677 is_gray: Whether the image *is* gray (by inspecting its palette).
678 as_gray: Whether the resulting image must be converted to gaey.
679 mode: The mode to convert to.
680 """
681
682 if is_gray is None:
683 is_gray = _palette_is_grayscale(im)
684
685 frame = im
686
687 # Convert ...
688 if mode is not None:
689 # Mode is explicitly given ...
690 if mode != im.mode:
691 frame = im.convert(mode)
692 elif as_gray:
693 pass # don't do any auto-conversions (but do the explicit one above)
694 elif im.mode == "P" and is_gray:
695 # Paletted images that are already gray by their palette
696 # are converted so that the resulting numpy array is 2D.
697 frame = im.convert("L")
698 elif im.mode == "P":
699 # Paletted images are converted to RGB/RGBA. We jump some loops to make
700 # this work well.
701 if im.info.get("transparency", None) is not None:
702 # Let Pillow apply the transparency, see issue #210 and #246
703 frame = im.convert("RGBA")
704 elif im.palette.mode in ("RGB", "RGBA"):
705 # We can do this ourselves. Pillow seems to sometimes screw
706 # this up if a multi-gif has a palette for each frame ...
707 # Create palette array
708 if hasattr(im.palette, "tobytes"):
709 palette_bytes = im.palette.tobytes()
710 else: # pragma: no cover
711 palette_bytes = im.palette.getdata()[1]
712 p = np.frombuffer(palette_bytes, np.uint8)
713 # Restore the raw mode that was saved to be used to parse the palette
714 if hasattr(im.palette, "rawmode_saved"):
715 im.palette.rawmode = im.palette.rawmode_saved
716 mode = im.palette.rawmode if im.palette.rawmode else im.palette.mode
717 nchannels = len(mode)
718 # Shape it.
719 p = p.reshape(-1, nchannels)
720 if p.shape[1] == 3 or (p.shape[1] == 4 and mode[-1] == "X"):
721 p = np.column_stack((p[:, :3], 255 * np.ones(p.shape[0], p.dtype)))
722 # Swap the axes if the mode is in BGR and not RGB
723 if mode.startswith("BGR"):
724 p = p[:, [2, 1, 0]] if p.shape[1] == 3 else p[:, [2, 1, 0, 3]]
725 # Apply palette
726 frame_paletted = np.array(im, np.uint8)
727 try:
728 frame = p[frame_paletted]
729 except Exception:
730 # Ok, let PIL do it. The introduction of the branch that
731 # tests `im.info['transparency']` should make this happen
732 # much less often, but let's keep it, to be safe.
733 frame = im.convert("RGBA")
734 else:
735 # Let Pillow do it. Unlinke skimage, we always convert
736 # to RGBA; palettes can be RGBA.
737 if True: # im.format == 'PNG' and 'transparency' in im.info:
738 frame = im.convert("RGBA")
739 else:
740 frame = im.convert("RGB")
741 elif "A" in im.mode:
742 frame = im.convert("RGBA")
743 elif im.mode == "CMYK":
744 frame = im.convert("RGB")
745 elif im.format == "GIF" and im.mode == "RGB":
746 # pillow9 returns RGBA images for subsequent frames so that it can deal
747 # with multi-frame GIF that use frame-level palettes and don't dispose
748 # all areas.
749
750 # For backwards compatibility, we promote everything to RGBA.
751 frame = im.convert("RGBA")
752
753 # Apply a post-convert if necessary
754 if as_gray:
755 frame = frame.convert("F") # Scipy compat
756 elif not isinstance(frame, np.ndarray) and frame.mode == "1":
757 # Workaround for crash in PIL. When im is 1-bit, the call array(im)
758 # can cause a segfault, or generate garbage. See
759 # https://github.com/scipy/scipy/issues/2138 and
760 # https://github.com/python-pillow/Pillow/issues/350.
761 #
762 # This converts im from a 1-bit image to an 8-bit image.
763 frame = frame.convert("L")
764
765 # Convert to numpy array
766 if im.mode.startswith("I;16"):
767 # e.g. in16 PNG's
768 shape = im.size
769 dtype = ">u2" if im.mode.endswith("B") else "<u2"
770 if "S" in im.mode:
771 dtype = dtype.replace("u", "i")
772 frame = np.frombuffer(frame.tobytes(), dtype).copy()
773 frame = frame.reshape(shape[::-1])
774 else:
775 # Use uint16 for PNG's in mode I
776 if im.format == "PNG" and im.mode == "I" and dtype is None:
777 dtype = "uint16"
778 frame = np.array(frame, dtype=dtype)
779
780 return frame
781
782
783 def ndarray_to_pil(arr, format_str=None, prefer_uint8=True):
784 from PIL import Image
785
786 if arr.ndim == 3:
787 arr = image_as_uint(arr, bitdepth=8)
788 mode = {3: "RGB", 4: "RGBA"}[arr.shape[2]]
789
790 elif format_str in ["png", "PNG"]:
791 mode = "I;16"
792 mode_base = "I"
793
794 if arr.dtype.kind == "f":
795 arr = image_as_uint(arr)
796
797 elif prefer_uint8 and arr.max() < 256 and arr.min() >= 0:
798 arr = arr.astype(np.uint8)
799 mode = mode_base = "L"
800
801 else:
802 arr = image_as_uint(arr, bitdepth=16)
803
804 else:
805 arr = image_as_uint(arr, bitdepth=8)
806 mode = "L"
807 mode_base = "L"
808
809 if mode == "I;16" and int(getattr(Image, "__version__", "0").split(".")[0]) < 6:
810 # Pillow < v6.0.0 has limited support for the "I;16" mode,
811 # requiring us to fall back to this expensive workaround.
812 # tobytes actually creates a copy of the image, which is costly.
813 array_buffer = arr.tobytes()
814 if arr.ndim == 2:
815 im = Image.new(mode_base, arr.T.shape)
816 im.frombytes(array_buffer, "raw", mode)
817 else:
818 image_shape = (arr.shape[1], arr.shape[0])
819 im = Image.frombytes(mode, image_shape, array_buffer)
820 return im
821 else:
822 return Image.fromarray(arr, mode)
823
824
825 # imported for backwards compatibility
826 from .pillowmulti import GIFFormat, TIFFFormat # noqa: E402, F401