pillow_legacy.py 31 KB

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