"Fossies" - the Fresh Open Source Software Archive

Member "scikit-image-0.19.3/skimage/io/_io.py" (12 Jun 2022, 6405 Bytes) of package /linux/misc/scikit-image-0.19.3.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. For more information about "_io.py" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 0.19.2_vs_0.19.3.

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