_io.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. import pathlib
  2. import warnings
  3. import numpy as np
  4. from .._shared.utils import warn, deprecate_func, deprecate_parameter, DEPRECATED
  5. from .._shared.version_requirements import require
  6. from ..exposure import is_low_contrast
  7. from ..color.colorconv import rgb2gray, rgba2rgb
  8. from ..io.manage_plugins import call_plugin, _hide_plugin_deprecation_warnings
  9. from .util import file_or_url_context
  10. __all__ = [
  11. 'imread',
  12. 'imsave',
  13. 'imshow',
  14. 'show',
  15. 'imread_collection',
  16. 'imshow_collection',
  17. ]
  18. _remove_plugin_param_template = (
  19. "The plugin infrastructure in `skimage.io` and the parameter "
  20. "`{deprecated_name}` are deprecated since version {deprecated_version} and "
  21. "will be removed in {changed_version} (or later). To avoid this warning, "
  22. "please do not use the parameter `{deprecated_name}`. Instead, use `imageio` "
  23. "or other I/O packages directly. See also `{func_name}`."
  24. )
  25. @deprecate_parameter(
  26. "plugin",
  27. start_version="0.25",
  28. stop_version="0.27",
  29. template=_remove_plugin_param_template,
  30. )
  31. def imread(fname, as_gray=False, plugin=DEPRECATED, **plugin_args):
  32. """Load an image from file.
  33. Parameters
  34. ----------
  35. fname : str or pathlib.Path
  36. Image file name, e.g. ``test.jpg`` or URL.
  37. as_gray : bool, optional
  38. If True, convert color images to gray-scale (64-bit floats).
  39. Images that are already in gray-scale format are not converted.
  40. Other Parameters
  41. ----------------
  42. plugin_args : DEPRECATED
  43. The plugin infrastructure is deprecated.
  44. Returns
  45. -------
  46. img_array : ndarray
  47. The different color bands/channels are stored in the
  48. third dimension, such that a gray-image is MxN, an
  49. RGB-image MxNx3 and an RGBA-image MxNx4.
  50. """
  51. if plugin is DEPRECATED:
  52. plugin = None
  53. if plugin_args:
  54. msg = (
  55. "The plugin infrastructure in `skimage.io` is deprecated since "
  56. "version 0.25 and will be removed in 0.27 (or later). To avoid "
  57. "this warning, please do not pass additional keyword arguments "
  58. "for plugins (`**plugin_args`). Instead, use `imageio` or other "
  59. "I/O packages directly. See also `skimage.io.imread`."
  60. )
  61. warnings.warn(msg, category=FutureWarning, stacklevel=3)
  62. if isinstance(fname, pathlib.Path):
  63. fname = str(fname.resolve())
  64. if plugin is None and hasattr(fname, 'lower'):
  65. if fname.lower().endswith(('.tiff', '.tif')):
  66. plugin = 'tifffile'
  67. with file_or_url_context(fname) as fname, _hide_plugin_deprecation_warnings():
  68. img = call_plugin('imread', fname, plugin=plugin, **plugin_args)
  69. if not hasattr(img, 'ndim'):
  70. return img
  71. if img.ndim > 2:
  72. if img.shape[-1] not in (3, 4) and img.shape[-3] in (3, 4):
  73. img = np.swapaxes(img, -1, -3)
  74. img = np.swapaxes(img, -2, -3)
  75. if as_gray:
  76. if img.shape[2] == 4:
  77. img = rgba2rgb(img)
  78. img = rgb2gray(img)
  79. return img
  80. @deprecate_parameter(
  81. "plugin",
  82. start_version="0.25",
  83. stop_version="0.27",
  84. template=_remove_plugin_param_template,
  85. )
  86. def imread_collection(
  87. load_pattern, conserve_memory=True, plugin=DEPRECATED, **plugin_args
  88. ):
  89. """
  90. Load a collection of images.
  91. Parameters
  92. ----------
  93. load_pattern : str or list
  94. List of objects to load. These are usually filenames, but may
  95. vary depending on the currently active plugin. See :class:`ImageCollection`
  96. for the default behaviour of this parameter.
  97. conserve_memory : bool, optional
  98. If True, never keep more than one in memory at a specific
  99. time. Otherwise, images will be cached once they are loaded.
  100. Returns
  101. -------
  102. ic : :class:`ImageCollection`
  103. Collection of images.
  104. Other Parameters
  105. ----------------
  106. plugin_args : DEPRECATED
  107. The plugin infrastructure is deprecated.
  108. """
  109. if plugin is DEPRECATED:
  110. plugin = None
  111. if plugin_args:
  112. msg = (
  113. "The plugin infrastructure in `skimage.io` is deprecated since "
  114. "version 0.25 and will be removed in 0.27 (or later). To avoid "
  115. "this warning, please do not pass additional keyword arguments "
  116. "for plugins (`**plugin_args`). Instead, use `imageio` or other "
  117. "I/O packages directly. See also `skimage.io.imread_collection`."
  118. )
  119. warnings.warn(msg, category=FutureWarning, stacklevel=3)
  120. with _hide_plugin_deprecation_warnings():
  121. return call_plugin(
  122. 'imread_collection',
  123. load_pattern,
  124. conserve_memory,
  125. plugin=plugin,
  126. **plugin_args,
  127. )
  128. @deprecate_parameter(
  129. "plugin",
  130. start_version="0.25",
  131. stop_version="0.27",
  132. template=_remove_plugin_param_template,
  133. )
  134. def imsave(fname, arr, plugin=DEPRECATED, *, check_contrast=True, **plugin_args):
  135. """Save an image to file.
  136. Parameters
  137. ----------
  138. fname : str or pathlib.Path
  139. Target filename.
  140. arr : ndarray of shape (M,N) or (M,N,3) or (M,N,4)
  141. Image data.
  142. check_contrast : bool, optional
  143. Check for low contrast and print warning (default: True).
  144. Other Parameters
  145. ----------------
  146. plugin_args : DEPRECATED
  147. The plugin infrastructure is deprecated.
  148. """
  149. if plugin is DEPRECATED:
  150. plugin = None
  151. if plugin_args:
  152. msg = (
  153. "The plugin infrastructure in `skimage.io` is deprecated since "
  154. "version 0.25 and will be removed in 0.27 (or later). To avoid "
  155. "this warning, please do not pass additional keyword arguments "
  156. "for plugins (`**plugin_args`). Instead, use `imageio` or other "
  157. "I/O packages directly. See also `skimage.io.imsave`."
  158. )
  159. warnings.warn(msg, category=FutureWarning, stacklevel=3)
  160. if isinstance(fname, pathlib.Path):
  161. fname = str(fname.resolve())
  162. if plugin is None and hasattr(fname, 'lower'):
  163. if fname.lower().endswith(('.tiff', '.tif')):
  164. plugin = 'tifffile'
  165. if arr.dtype == bool:
  166. warn(
  167. f'{fname} is a boolean image: setting True to 255 and False to 0. '
  168. 'To silence this warning, please convert the image using '
  169. 'img_as_ubyte.',
  170. stacklevel=3,
  171. )
  172. arr = arr.astype('uint8') * 255
  173. if check_contrast and is_low_contrast(arr):
  174. warn(f'{fname} is a low contrast image')
  175. with _hide_plugin_deprecation_warnings():
  176. return call_plugin('imsave', fname, arr, plugin=plugin, **plugin_args)
  177. @deprecate_func(
  178. deprecated_version="0.25",
  179. removed_version="0.27",
  180. hint="Please use `matplotlib`, `napari`, etc. to visualize images.",
  181. )
  182. def imshow(arr, plugin=None, **plugin_args):
  183. """Display an image.
  184. Parameters
  185. ----------
  186. arr : ndarray or str
  187. Image data or name of image file.
  188. plugin : str
  189. Name of plugin to use. By default, the different plugins are
  190. tried (starting with imageio) until a suitable candidate is found.
  191. Other Parameters
  192. ----------------
  193. plugin_args : keywords
  194. Passed to the given plugin.
  195. """
  196. if isinstance(arr, str):
  197. arr = call_plugin('imread', arr, plugin=plugin)
  198. with _hide_plugin_deprecation_warnings():
  199. return call_plugin('imshow', arr, plugin=plugin, **plugin_args)
  200. @deprecate_func(
  201. deprecated_version="0.25",
  202. removed_version="0.27",
  203. hint="Please use `matplotlib`, `napari`, etc. to visualize images.",
  204. )
  205. def imshow_collection(ic, plugin=None, **plugin_args):
  206. """Display a collection of images.
  207. Parameters
  208. ----------
  209. ic : :class:`ImageCollection`
  210. Collection to display.
  211. Other Parameters
  212. ----------------
  213. plugin_args : keywords
  214. Passed to the given plugin.
  215. """
  216. with _hide_plugin_deprecation_warnings():
  217. return call_plugin('imshow_collection', ic, plugin=plugin, **plugin_args)
  218. @require("matplotlib", ">=3.3")
  219. @deprecate_func(
  220. deprecated_version="0.25",
  221. removed_version="0.27",
  222. hint="Please use `matplotlib`, `napari`, etc. to visualize images.",
  223. )
  224. def show():
  225. """Display pending images.
  226. Launch the event loop of the current GUI plugin, and display all
  227. pending images, queued via `imshow`. This is required when using
  228. `imshow` from non-interactive scripts.
  229. A call to `show` will block execution of code until all windows
  230. have been closed.
  231. Examples
  232. --------
  233. >>> import skimage.io as io
  234. >>> rng = np.random.default_rng()
  235. >>> for i in range(4):
  236. ... ax_im = io.imshow(rng.random((50, 50))) # doctest: +SKIP
  237. >>> io.show() # doctest: +SKIP
  238. """
  239. with _hide_plugin_deprecation_warnings():
  240. return call_plugin('_app_show')