Skip to content

Design for a new public API #563

Closed
Closed

Description

@almarklein

Following up on a discussion started in scikit-image/scikit-image#5036,
I'd like to consider an alternative API for imageio. How to apply this is another discussion; let's first dream up an ideal API :)

TLDR

# Get object that can be used to read/write image and meta data.
# The mode arg can be used to specify read/write mode, as well as the expected dimensionality.
# Default is "greedy"
r = imopen(filename, mode='read/write greedy/image/volume') 

# The short way to read an image
# im = imopen(...).read() -> actually this is bad, as it may keep files open on pypy
with imopen(...) as r:
    im = r.read()
# maybe a shorthand
im = imread(...)

# Read image and meta data
with imopen(...) as r:
    meta = r.get_meta()
    im = r.read(index=None)

# Read a volume or fail
vol = imopen(..., mode='rv').read()

# Iterate over 2D images
for im, meta in imopen(... mode='ri').iter(): 
  pass

Use-cases

Let's start by explaining some use-cases of data that a user might encounter.

A single image:

 ____________
|______1_____|

A stack of images. E.g. a Tiff, a small gif, or Dicom (3D medical data):

 ____________
|______1_____|
|______2_____|
|______3_____|

A BIG stack of images. E.g. an mp4. The precise number of elements is likely not known, and it may we streaming data (e.g. from a webcam). The total data may be too big to fit in RAM, and the preferred way to load it would be to stream it (with an iterator) or to specify a frame with an index. A plugin may want to prevent the user from reading the data all at once.

 ____________
|______1_____|
|______2_____|
|______...___|
|______n_____|

Multiple stacks of images. This can happen with e.g. Tiff and Dicom. Let's assume / hope that this is about the most complex kind of data we can get. The stacks may have different shapes.

 ____________
|______1_____|
|______2_____|
|______3_____|
 __________
|_____1____|
|_____2____|
|_____3____|
|_____4____|

What Imageio currently does

  • imread: get (only) the first 2D image.
  • mimread: get a list of all 2D images in the dataset.
  • volread: get the first 3D image.
  • mvolread: get all 3D images.
  • get_reader(): an object that allows streaming the data: get_data(index), get_next_data(), iter_data(). These return 2D or 3D images depending on a mode argument when creating the reader object.

In short, the user specifies what kind of data is expected, and this is expressed to the underlying plugin using a mode (or hint).

What (I think) we need

In scikit-image/scikit-image#5036 the need was expressed to be able to just imread(), and get a 3D or 2D image, whatever is in the dataset. This is useful in data exploration and e.g. when using Napari, which will be fine with whatever you give it :)

However, I also think we should allow the user to express an expectation. E.g. when reading video, you probably don't want to stack all images in a single array.

Further, there is an increasing need to be able to read (standardized) metadata from the images. At the same time, most users probably don't need it, so an API that always returns metadata may be too verbose.

Proposed API

I propose a function imopen() that returns an object (as described in #562) that can be used to read or write data. This function has a mode arument, that can be specified to r(ead) or w(rite), but also to specify the expected dimensionality: g(reedy) is the default, i(mage), v(olume). The returned reader object has a simple API with ~4 functions.

  • r = imopen(... mode='read/write greedy/image/volume') -> returns a format object.
  • r.get_meta(index=None) -> get metadata of whole file or of specified frame.
  • r.read(index=None) -> Return im, for the given index, or the next image if index=None.
  • r.write(im, meta) -> for writing.
  • r.iter() -> returns a generator that produces (im, meta) tuples.

So ...

  • imopen(...).read() gives whatever is in the dataset (mode='greedy' by default).
  • imopen(... mode='image').read() gives the first image.
  • imopen(... mode='volume').read() gives a volume or fails.
  • [im for im, meta in imopen(...mode='image').iter()] gives a list of images.

Questions

Is imopen(...).read() too verbose? We can off-course wrap this in a convenience function, and I think this is exactly what skimage.io.imread() would call.

When you are interested in meta-data, would you rather:

im, meta = imopen(...).read()

which may be nice, but verbose when you don't want metadata, or:

with imopen(...) as r:
    meta = r.get_meta()
    im = r.read()

Is there a better term for "greedy"?

Activity

  1. FirefoxMetzger commented on Nov 2, 2020

    @FirefoxMetzger
    Contributor

    Three thoughts:

    (1) Is there a particular reason why you propose imopen(...) instead of leaning on python's open(...) and then pass the file object into a functional API? (Not familiar with this codebase) I could imagine something like

    with open(..., 'rb') as image_file:
        array_like = iio.load(image_file, mode="greedy")
        image_file.seek(0)
        metadata = iio.metadata(image_file)
    

    (2) Might be implied and I failed to read between the lines: I wouldn't use g/i/v, but the longer greedy, volume, image for clarity.

    (3) If we introduce a new class like imopen, the class could represent the image as a list of lists (lazy-loaded) and define the slice operator that loads a (possibly n-dimensional) ROI of the image as an array-like. Slices would also apply along the stack dimension, the time dimension, or any other dimension people might use. If there are missing values for any pixel (for example because the images in a .tiff have different dimensions), imopen can raise an exception (default) or fill those with a given value, e.g. fill=np.nan.

    slice(a, None, b) would interpret the None for stop as len(sublist) where sublist is given by start of the previous slices. Something like img = iio.imopen(filename)[5, 350:, 62::2] would be interpreted as

    file_list_of_lists # loaded from disk
    
    # handle first dimension, integer index
    sublist_one = file_list_of_lists[5] 
    
    # handle second dimension, slice(350, None, None)
    sublist_two = sublist_one[slice(350, len(sublist_one), 1)] 
    
    # handle third dimension, slice(62, None, 2)
    sublist_three = [row[slice(62, len(sublist_two), 2)] for row in sublist_two]

    We could then use this slicing mechanic to legacy support current imageio functions and skimage.imread:

    img = imopen(filename)[0, ...] # iio.imread()
    
    img_list = [imopen(filename)[idx, ...] for idx in len(imopen(filename))] # iio.mimread
    
    # prior knowledge: `num_images` in the first stack
    img = imopen(filename)[:num_images, ...] # iio.volread
    
    # prior knowledge: `img_per_stack` number of images per stack
    steps = np.cumsum([0] + img_per_stack)
    img_list = [imopen(filename)[start:stop, ...] for start, stop in zip(steps[:-1], steps[1:])] # iio.mvolread
    
    # skimage assumes that the dimensionality "just works" (afaik)
    img = imopen(filename)[...] # skimage.imread
    

    To allow the prior knowledge for volread and mvolread to be discovered, imopen might expose imopen(...).len(dim) (horrible API, please improve). It takes a dim-tuple and returns the length of the sublist at that location.

    There might be even better python trickery available if imopen(...).__getitem__ returns a new imopen object and defers loading until np.asarray(imopen(...)) is called, which then loads the required ROI (or fails). I didn't really think about how the handle ownership of the IO object, but that appears solvable at first glance.

  2. almarklein commented on Nov 4, 2020

    @almarklein
    MemberAuthor

    Thanks for the feedback!

    (1) Is there a particular reason why you propose imopen(...) instead of leaning on python's open(...)

    Yes. I did not explain this above, but what imopen would do is select the right format/plugin (however you call it), given the filename/uri. It then returns the format object which will handle the actual reading/writing. I chose the name imopen, so that one could do from imageio import imopen.

    (2) Might be implied and I failed to read between the lines: I wouldn't use g/i/v, but the longer greedy, volume, image for clarity.

    Good point, I agree. I will update the examples.

    (3) If we introduce a new class like imopen, the class could represent the image as a list of lists (lazy-loaded) and define the slice operator that loads a (possibly n-dimensional) ROI of the image as an array-like.

    Interesting idea! I don't fully follow it yet :) and I have some remarks. I think it would be valuable to see what the examples at the top post would look like with this approach.

    You seem to suggest that the index is 3 dimensional: r[z/slice, y, x], but for data containing multiple volumes (or multiple stacks of images) you'd need 4, I think: r[stack, z/slice, y, x]. That would make reading an image r[0, 0,...].

    What would be the API to obtain meta data?

    Note that for some formats the number of images is not known (e.g. getting the exact number of frames in a video file is either a guess, or very slow). That's why I am aiming for an iterator to iterate over images/volumes. I'm not sure how this would fit in?

  3. almarklein commented on Nov 4, 2020

    @almarklein
    MemberAuthor

    A bit of background: the core of imageio is responsible for basically two things:

    • Selecting the right plugin, given a read or write request.
    • Providing the plugin with an easy interface to get the data (either using a file object or a local filename), while enabling users to read from a wide variety of sources (filenames, file objects, http, ftp, zipfiles, etc).
  4. FirefoxMetzger commented on Nov 4, 2020

    @FirefoxMetzger
    Contributor

    I gave it a bit more thought, and I think imopen.__getitem__ is indeed a fun idea, but it should return a new imopen object. The concept would be analogous to numpy views. To get actual numpy data a to_numpy() function ala pandas would make a lot of sense.

    # Get object that can be used to read/write image and metadata.
    # The mode arg can be used to specify read/write mode, as well as the expected dimensionality.
    # Default is "greedy"
    r = imopen(filename, fill=None) # fill=None (default) fails when trying to index/access a pixel that doesn't exist
    
    # The short way to read an image
    # -----------------------------------
    
    im = imopen(...).to_numpy() # file contains a single image
    im = imopen(...)[42:1337, 50:500].to_numpy() # read ROI only
    
    # file contains multiple single images
    im = imopen(...)[n].to_numpy() # read the n-th image
    im = imopen(...)[n, 42:1337, 50:500].to_numpy() # read ROI from n-th image
    
    # Read image and metadata
    # -----------------------------------
    imagefile = imopen(...) # lingering IO is not so nice
    img = imagefile.to_numpy()
    metadata = imgfile.metadata()
    
    # Read a volume or fail
    # -----------------------------------
    # The exact syntax (number of dimension in slice) will depend on the file format
    
    vol = imopen(...).to_numpy() # single volume file
    vol = imopen(...)[3].to_numpy() # file has multiple volumes stacked along the leading dimension
    
    # volume from a stack of images
    vol = imopen(...)[:50].to_numpy()
    
    # if `imopen(...)[:50]` contains images/volumes with different shapes
    # find the shape of `imopen(...)[:50][0]` (first image/volume in the stack)
    # and then cut all proceeding images that are bigger to fit that shape
    # for the images that are smaller fill the missing pixels with `fill`
    # Question: Can we have different color models within the same file?
    
    # Iterate over 2D images
    # -----------------------------------
    for filepart in imopen(...): 
      img = filepart.to_numpy()
    
    # or even more pythonic
    for img in map(lambda x: x.to_numpy(), imopen(...)):
        pass # do cool stuff with img

    The user-facing API could be quite simple:

    class imopen:
        def __init__(self, filename, fill=None):
            raise NotImplementedError()
        def __getitem__(self, key):
            # key supports int, tuple, and slice
            raise NotImplementedError()
        def metadata(self):
            raise NotImplementedError()
        def to_numpy(self):
            raise NotImplementedError()
        def __len__(self):
            # length of the leading dimension
            raise NotImplementedError()

    You seem to suggest that the index is 3 dimensional: r[z/slice, y, x], but for data containing multiple volumes (or multiple stacks of images) you'd need 4, I think: r[stack, z/slice, y, x]. That would make reading an image r[0, 0,...].

    I don't know if I understand the problem. If the stack and volume dimension run along separate axes, then indexing becomes even easier. Could you elaborate your concern a bit more?

    What would be the API to obtain meta data?

    imopen(...).metadata() This has the advantage that many formats store some metadata in the front or back of the image, and seek + read can be much faster if we only want metadata.

    Note that for some formats the number of images is not known (e.g. getting the exact number of frames in a video file is either a guess, or very slow). That's why I am aiming for an iterator to iterate over images/volumes. I'm not sure how this would fit in?

    You could explicitly implement the __iter__ method that could return a generator if the size isn't known.

  5. almarklein commented on Nov 4, 2020

    @almarklein
    MemberAuthor

    Let's take a small step back :) The main thing to achieve here, is an API that provides both 1) a way to read the data in the file in the highest possible dimensionality, and 2) read data in an expected dimensionality, regardless of how it's organized in the file.

    For the index-API to work, the first index should not simply refer to the first dimension of the data, because:

    # This could return a volume, or image, or a row from an image
    x= imopen(...)[3].to_numpy() 
    # Similarly:
    for filepart in imopen(...): 
      x = filepart.to_numpy()  # image or volume?

    The alternative, I think, is to predefine the indices, so the first refers to the outermost dimension that we assume (the list of volumes), and the second refers to the image in that stack/volume:

    # Read the 4th volume
    vol = imopen(...)[3].to_numpy() 
    # Read the 4th image
    im = imopen(...)[0, 3].to_numpy() 

    But if I'm honest, I am not sold on this :) The idea to use an array-like API for reading image data is interesting, but image io is different from slicing/processing the image data, and they don't need the same API. Also because I don't think there is much advantage for being able to read a subrectangle within an image, since in most formats the data is compressed per-image anyway, so I don't expect a performance benefit.

  6. almarklein commented on Nov 4, 2020

    @almarklein
    MemberAuthor

    Perhaps there are ideas that we can take away from the index-API. As an alternative to using the mode arguments to specify the expected dimensionality, we could do something like this:

    # Read whatever the source data is
    im = imopen(...).read()
    
    # Read a volume or fail
    vol = imopen(...).volume.read()
    
    # Read the 4th image
    im = imopen(...).image.read(3)
    
    # Iterate over 2D images
    for im, meta in imopen(...).image.iter(): 
      pass
  7. FirefoxMetzger commented on Nov 5, 2020

    @FirefoxMetzger
    Contributor
    1. read data in an expected dimensionality, regardless of how it's organized in the file.

    This one somehow strikes me as odd. What I understand here, is that the aim is to create an abstraction over file types. Regardless of how the image is stored. After the image is loaded by imageio, the dimensions will be in a predefined order with an expected meaning to each axis. I'm not sure how we would guarantee that. Will we reorganize dimensions if necessary? Are we constraining ourselves to a limited set of output formats? If so, which ones?

    I can see how this has merit for formats that are popular now (.jpg, .png or .tiff), but what about more esoteric ones? You mentioned reading video as image stacks earlier; how will this fit into the read/volume/iter API? What would be the expected dimensionality for an RGBD video stream or stereo video? I feel enforcing an expected dimensionality across file formats is us being opinionated where we don't have to be.

    I think it's much cleaner (and easier) to return the data in the dimensionality and order given by the file and let the user do the standardization/reshaping. They have the domain knowledge on how they want to consume the image, so let's not try and guess.

    #This could return a volume, or image, or a row from an image

    Yes! I think this is exactly the strength of this approach; you seem to think of it as a weakness. Could you explain why?

    If images are stacked along the last dimension (interleaved image stacks!?), one would do imopen(...)[..., 3].to_numpy(). Arguably inefficient to load, but the solution here is to have the user change the image format if performance is a concern :)

    For me, the reason I like this approach is that it keeps the simple use cases simple. "I want to load a .jpg" -> imopen(...jpg).to_numpy(), "I want to read a volume from a .tiff containing a single volume" -> imopen(...tiff).to_numpy(), "I want to load all images in a .gif" -> imopen(...gif).to_numpy(). Reading your first aim for the API, I think we are likely to agree on this part.

    What is missing is how to let users select the first image from stacks, sequences, etc. (to support the previous imread and volread). If they should not be phased out, is it possible to generalize them? Maybe we can allow users to select an arbitrary image/volume from a stack or sequence? Maybe we can allow users to do both at the same time and select a specific image from a specific volume directly? How about adding a time dimension? Maybe it is easier at this point to think of nd-images. Could we allow users to select elements along dimensions of an nd-image? What about multiple elements along dimensions? At this point, slice becomes an obvious choice. I assume that you have a different view on this though; would be interesting to learn where we differ.

    As an alternative to using the mode arguments to specify the expected dimensionality, we could do something like this:

    I would actually prefer the mode= API in comparison. What will imopen(...).volume.read() do for a .png image? Presumably, it will throw an exception, but why does a class have a method that is only valid in some cases, but not others? To me, this sounds like a candidate for inheritance and OOP. At this point, it sounds a bit like relabeling imread, volread, mimread, ... and adding a generic read (highest dimension) to it.

    Tangent: How would imopen(...).read() handle the case of stacked differently sized volumes?

    Edit: Oh, almost forgot:

    I don't think there is much advantage for being able to read a subrectangle within an image, since in most formats the data is compressed per-image anyway, so I don't expect a performance benefit

    I agree, for many formats, there will be no large speed gain. You will likely have to read most of the image and IO will be the performance bottleneck. When reading ROI, you will get speed advantages from fewer transitions between the C and python layer though. Instead of doing two rounds, one to load the full image and a second to slice it, you can do both in a single pass down to C. For some formats, however, there will be a performance advantage in not having to read the entire file, and if reading a small area of many files fast (e.g. checking a watermark) is your use case then the proposed API can accommodate you almost naturally and without change.

    What you will get in all cases is memory benefits. The read call knows the shape it has to load and can simply discard all the data it doesn't need to fulfill the request and only keep the relevant pixels. This can be useful for CV on embedded devices, mobile phones, robots, etc.

  8. lschr commented on Nov 6, 2020

    @lschr
    Contributor

    I just created #564, which I intended as an alternative interface to imageio. This may be relevant for this discussion as well.

  9. almarklein commented on Nov 7, 2020

    @almarklein
    MemberAuthor

    About expressing the expected dimensionality.

    It took me a while to reply because I had to contemplate this. The thing is that it is currently a part of imageio, and it plays a role in different parts, and I found that I cannot yet oversee whether/how it would work without it. I'll try to list the problems that I foresee:

    1 - file formats are (sometimes) messy

    I think it's much cleaner (and easier) to return the data in the dimensionality and order given by the file and let the user do the standardization/reshaping. They have the domain knowledge on how they want to consume the image, so let's not try and guess.

    I'm not sure if I agree ... file formats are messy ... and if a plugin knows the intention of the user, it could be more capable of returning something sensible. Anyway, that has been one of the arguments at the time. Maybe it's not so much needed as I thought at the time? I don't know. We can try.

    2 - you don't know what you'll get

    #This could return a volume, or image, or a row from an image

    Yes! I think this is exactly the strength of this approach; you seem to think of it as a weakness. Could you explain why?

    Well, it's arguably confusing. You read one tiff and get a 2D array, you read another and get a 3D array. Plus it makes the code less readable.

    3 - protect users when reading large files

    The current imageio.mimread() protects users from reading a large number of images from e.g. a movie, bringing your machine to its knees by forcing it to use the swap file.

    I think it would make sense that plugins may disallow reading the whole file at once, forcing to use .read(index) or the iter API. That should at least make the potential problem more obvious to the user. So I suppose this could work.

    4 - plugin selection

    The mode is used during the plugin selection process. E.g. the Pillow plugin can read .gif, but not animated .gif - there is another plugin for that.

    Without a mode, plugins are thus more strictly bound to the extension. This might mean they'd need to be more aware of each other and delegate to other plugins as needed. Maybe this is for the better, but I can't be sure.

    In summary, I'm starting to see how things could look like without mode, but I am not fully convinced that we can pull it off. Maybe we should try, and add the mode argument if we find out we kinda need it?

    Imread returning partial data is a problem

    I can see how imread() returning a fraction of the data (a 2d image, if the data in the file is actually 3D) is confusing. So in any case, that's something we should probably fix.

    One possibility (for the API proposed at the first post) could be:

     # read image, if the image contains multiple images, raise an error
    with imopen(..., mode='image') as r:
        r.read() 

    Tangent: How would imopen(...).read() handle the case of stacked differently sized volumes?

    I think it should fail, forcing the user to specify an index, or use the iterator approach.

    Indexing API

    I have thought about it, but I believe a function-based (file-like) API is more appropriate. I think that mimicking an array API is potentially confusing to users, and adds complexity for plugins. Further, a plugin can give it's read() method more arguments to allow more fine-grained control, which you cannot do with indexing.

    When reading ROI, you will get speed advantages from fewer transitions between the C and python layer though. Instead of doing two rounds, one to load the full image and a second to slice it

    I do not follow. All current plugins are written in pure Python, so any slicing would be done with numpy anyway. In any case, I believe that any performance benefit is marginal, while it adds complexity - all plugins would need to support it! So I feel quite strongly against this ROI thing.

    Note that what imopen returns is a plugin object. We specify what it must be able to do, but special formats can add more API for certain things. This applies to reading ROI's, stereo video, and other esoteric stuff :)

  10. FirefoxMetzger commented on Nov 8, 2020

    @FirefoxMetzger
    Contributor

    Hmm ... many things to think about. A few questions (in no particular order):

    1. Formats are indeed messy; especially esoteric ones. Regarding your concern that the response from some formats will not be meaningful: Is it a general concern, or do you already have specific formats in mind?
    2. Whenever you talk about returning something sensible, it sounds a bit like you have a quite specific subset of return types in mind. It seems like imageio is not just expected to return an image but an image in a quite specific/restricted format. Was this an explicit design choice or did it grow like that? Is there some documentation on what the API should and should not return?
    3. Regarding the unexpected/unknown return dimensions: Do you think it will happen often that a user doesn't know the dimensionality of the file he/she is trying to open? In my mind, it is much more common that the user knows what file he/she is working with, and he/she is mainly looking for a way to get it into python. Am I missing something?
    4. I think that a good API should be largely transparent with a low barrier of entry and a large amount of optional specificity. I can see how your (@almarklein ) approach solves the large specificity aspect. What are your thoughts on the low barrier of entry side? Like, if I have never used the library will it be easy for me to understand that I need to use a specific mode=<something> for my specific image, and will it be easy to see which mode I should use? Can good documentation alone (how to make it easily accessible?) solve this?
    5. Not sure how I feel about the idea of protecting users from themself on opening too large files. I think that this is a mistake a user will do exactly once and then learn from it very quickly. Besides, isn't validating user input something that user-facing applications should do? I could be wrong, but I see imageio mainly as a low-level library and not so much as a user-facing app; I would aim for "fail spectacularly and noisily on misuse". That said, an option could be a maxsize='4GB' argument? What do you think?
    6. How does the current plugin structure look like and how does this deligation work? I think I may have missed reading up on some documentation; could you give me a link to it?
    7. On the one side we are discussing not loading large files, on the other, we are discussing not loading ROIs. If I load a single image from a volume isn't this a special case of a ROI along the stack dimension?
    8. I keep getting the impression that we are implicitly discussing multiple use-cases for the API and are seamlessly switching between them. At least to me, this is a little confusing at times. Could we come up with a clear, numbered list of individual use-cases that represents the minimum number of scenarios we would like the API to support?
  11. almarklein commented on Nov 9, 2020

    @almarklein
    MemberAuthor
    1. [...] Regarding your concern that the response from some formats will not be meaningful: Is it a general concern, or do you already have specific formats in mind?

    It's more of a gut feeling. The plugins now do have this information, and I am not sure what it'd look like without it. Thinking of Dicom and Tiff in particular. It could be fine though!

    1. [...] Whenever you talk about returning something sensible, it sounds a bit like you have a quite specific subset of return types in mind.

    With sensible I meant "something that makes sense to the user". If the user is able to express their expectation it's easier to match that than when the plugin code must make a guess. I suppose in most cases this comes down to returning the data in the highest possible dimension, but as mentioned for performance, a plugin could decide to limit that in some cases.

    It seems like imageio is not just expected to return an image but an image in a quite specific/restricted format.

    Not really. For images a Numpy array shaped NxM or NxMxC (with C 1, 2 ,3, or 4). (There is an open issue whether we expect RGB (as opposed to e.g. HSV), but that's a different topic: :D )

    1. [...] Do you think it will happen often that a user doesn't know the dimensionality of the file he/she is trying to open? In my mind, it is much more common that the user knows what file he/she is working with [...]

    That would depend on the field. In such cases one would probably do some data-exploration when receiving new data anyway. So reading "greedy" might even be better, I suppose. My remaining point is readabilty:

    # This would be an image, or a volume, probably
    im = someapi.read("xx.tiff")
    # I'm pretty sure that this is a volume
    im = someapi.volread("xx.tiff")
    1. [...] I have never used the library will it be easy for me to understand that I need to use a specific mode= for my specific image, and will it be easy to see which mode I should use? Can good documentation alone (how to make it easily accessible?) solve this?

    (edited the below, I refered to "imshow", but meant "imread")

    That is a really good question. In the current API, the mode is expressed with toplevel functions (imread, volread etc), making things very explicit, because a user is forced to use one of these functions. If imread) would have raised an exception instead of "dropping data", this would already have made a huge difference, I think.

    The risk with a mode parameter is that it's much less visible, making it's use less obvious. Maybe this is fine, if the default way to load an image works for most. But maybe we can change how it is expressed. This needs thought.

    1. Not sure how I feel about the idea of protecting users from themself on opening too large files. [...] an option could be a maxsize='4GB' argument? What do you think?

    I suppose the fact of having mimread() makes the need higher. Note that only mimread() and mvolread() have this option. If users are forced to do something like ims = [x[0] for x in iter], the potential problem is much more obvious. Plus the plugin cannot know whether process (and then drop) each frame, or keep everything in memory. So I think I'd prefer not to have a maxsize argument in this case.

    1. How does the current plugin structure look like and how does this deligation work? I think I may have missed reading up on some documentation; could you give me a link to it?

    See e.g. https://imageio.readthedocs.io/en/stable/plugins.html and https://github.com/imageio/imageio/blob/master/imageio/core/format.py#L666

    1. On the one side we are discussing not loading large files, on the other, we are discussing not loading ROIs. If I load a single image from a volume isn't this a special case of a ROI along the stack dimension?

    Yes, I meant ROIs for x and y specifically. With respect to being able to select individual frames we're on the same page :)

    1. I keep getting the impression that we are implicitly discussing multiple use-cases for the API and are seamlessly switching between them. At least to me, this is a little confusing at times. Could we come up with a clear, numbered list of individual use-cases that represents the minimum number of scenarios we would like the API to support?

    I think the data layouts at the top are a good start. I'll add some variations for files being large in a particular dimension.

  12. FirefoxMetzger commented on Nov 12, 2020

    @FirefoxMetzger
    Contributor

    @almarklein Thank you for such a detailed response.

    I read up on the plugin documentation and took a stroll through some of the implementations. The plugins I checked seem to all load the entire image, with exception of tifffile, which allows a key=N argument to select a slice of width 1 along the first dimension of the array (which strongly looks like the C-API leaking into python). This would mean that most APIs load the full image/volume/etc. and then discard some of the data before returning the desired type of image to the user. Perhaps I missed the ones that excel with the reading modes (volread, imread, iter) introduced by the imageio API?

    The current documentation also seems to suggest this, by only specifying to implement plugin._get_data(index) without specifying explicitly what index is supposed to mean. I suppose it means to read the index-th image in the file if present or index-th volume if it contains multiple volumes? What if the format supports both? What if the format only supports a single image, doesn't index=0 become redundant and index!=0 non-sensical? Which also makes me wonder, how does imageio fulfill a volread call?

    It appears that imread/volread/iter is a split specifically introduced by imageio. For the most part, plugin libraries that I checked seem to do: read() # reads the entire image. There is the odd case (like tifffile) which adds some partial indexing to address memory constraints on some systems, but this seems much less common. Their approach (blindly read everything) seems to be working quite well. Why are we introducing specialization here, and why is this specialization the default (and only) way to interact with an image file? There must be something I am missing because the more I look at it, the less I understand it.


    I read your updated top-level post again. For the last use-case (multiple volumes) I thought that this comes from the ability of TIFF to store multiple images of different sizes. When I checked the tifffile.py documentation it seemed as if they always load the entire image into a single nd-array. Do you know how this works with multiple volumes? My initial thought was that it seems impossible to create your use-case with that, but maybe it has to do with the magic key= property? Which other formats can produce this use-case?


    Reading your answers again, I was thinking that the main thing you object to in my suggestion isn't so much the slicing, but the fact that the returned shape of the image/volume is unknown until the object is returned. Is this consistency the reason why you have such a strong view on splitting imread and volread? Could you explain why trading convenience for consistency, in this case, is worth doing?

  13. almarklein commented on Nov 16, 2020

    @almarklein
    MemberAuthor

    which allows a key=N argument to select a slice of width 1 along the first dimension of the array (which strongly looks like the C-API leaking into python).

    I think you were looking at the vendored code for tifffile.py. The imageio tifffile plugin's read method is here, and you can see it uses the mode parameter to determine what the index means.

    Perhaps I missed the ones that excel with the reading modes (volread, imread, iter) introduced by the imageio API?

    I think Tifffile and Dicom are the only plugins that currently use the mode parameter. Naturally by far the most formats are 2D.

    The current documentation also seems to suggest this, by only specifying to implement plugin._get_data(index) without specifying explicitly what index is supposed to mean. I suppose it means to read the index-th image in the file if present or index-th volume if it contains multiple volumes? What if the format supports both?

    Then it uses the mode to see whether volread or imread was used.

    What if the format only supports a single image, doesn't index=0 become redundant and index!=0 non-sensical?

    Yes.

    Which also makes me wonder, how does imageio fulfill a volread call?

    It will first try to select an appropriate plugin. In this process, plugins that do not support volumes are skipped. If no plugin was found, an error is raised.

    Why are we introducing specialization here, and why is this specialization the default (and only) way to interact with an image file?

    The goal of imageio includes support for video and streaming data. To support that goal an (some form of) iter api is needed. It might be that the imread() / volread() split is not actually needed. I'm open to trying it without it :)

    When I checked the tifffile.py documentation it seemed as if they always load the entire image into a single nd-array. Do you know how this works with multiple volumes

    You can access each page (i.e. image) individually and call asarrary on that. Also see the link to the tiffule plugin above.

    Reading your answers again, I was thinking that the main thing you object to in my suggestion isn't so much the slicing, but the fact that the returned shape of the image/volume is unknown until the object is returned. Is this consistency the reason why you have such a strong view on splitting imread and volread? Could you explain why trading convenience for consistency, in this case, is worth doing?

    Actually, I object to the slicing API. As for the imread/volread separation - or the use of a mode parameter - I'm less certain by now.


    What about going with the API proposed at the top, but dropping the mode parameter (except for r/w), and see how this holds up?

  14. FirefoxMetzger commented on Nov 16, 2020

    @FirefoxMetzger
    Contributor

    Thanks again for the answers! Sorry, if my last comment was too harsh. I tend to get a bit critical and inquisitive when I am confused; I'm meaning no offense. I think I have a better sense of how things work under the hood now, so our discussion has definitely helped me.


    Ok, then the slicing API is off the table.

    I like the direction of the API in your top comment. If we try to challenge it a bit more: Do we really need an imopen object? The current (imread/volread) API is functional and this would introduce an object-oriented element to the API, mixing both styles (like an imread convenience for imopen(...).read()). Could something like this be cleaner?

    meta = metadata(...)  # read the image metadata
    
    img = imread(...)  # load the entire file as single nd-image
    
    for img in imiter(...):  # stream nd-images from the given URI
        pass  # do stuff with the image
    
    imwrite(...)  # write the image to disk

    Edit: If a plugin doesn't support a certain mode (like imiter for .jpg, or imwrite) they could raise IOError. Though, I guess this is already taken care of by plugin selection itself.

  15. almarklein commented on Nov 17, 2020

    @almarklein
    MemberAuthor

    No offense taken! I must admit that I was a bit frustrated at times - this started as an effort to bring skimage and imageio closer, which should (eventually) make maintaining imageio easier. But here we are discussion a brand new API, and some quite fundamental properties of the current implementation of imageio :) Sorry if this made my come across as blunt sometimes.

    The mode thing has been part of imageo for so long that it's hard for me to see it without, even though it's too long ago to remember all the arguments for it at the time. If we can indeed pull this off without de mode parameter, that would simply things quite a bit! Anyway, it's good that we had this discussion, so thanks for that!


    Could something like this be cleaner?

    Yesterday I was thinking of an API nearly the same as what you outline above :)

    The thing that bothers me with the proposal in the top post, is that for this to work safely, we should really promote the use of a with statement. I initially thought we could promote imopen(...).read() for simple cases, but we cannot, because on pypy this notation does not guarantee (at all) that the imopen object is closed, which may mean that the physical file stays open. However, the use of a with statement arguably makes the API more complex (and take twice as many lines in most cases).

    The API you propose above feels nice and simple, but it has shortcomings:

    • A nice feature of the imopen object is that you get exactly the plugin object, which could offer additional functionality (API calls), giving more freedom for special formats.
    • If you want to read the metadata and image data, the file is opened and closed twice, which seems like such a waste. Similarly, reading 4 images from a large image sequence using imread(index=i).

    I may overestimate the usefulness of the former - I don't think any of the current plugins actually do this. Also they could support additional kwargs for imread. Maybe there may be solutions for the latter?

    Maybe we should start a new issue outlining these two proposals and ask for input from others too.

  16. FirefoxMetzger commented on Nov 17, 2020

    @FirefoxMetzger
    Contributor

    I may not fully understand what additional functionality you have in mind. I'm sure you already thought about basic plumbing like:

    # default for plugin is `None` which calls the plugin selector to find a fitting plugin
    imread(filename, *args, plugin="tifffile", **kwargs) ->tifffile(filename, *args, **kwargs)

    If you mean custom methods on imopen, have you thought about allowing plugins to use a custom namespace like;

    import imageio as iio
    
    iio.read(filename, plugin="dicom")
    iio.dicom.custom_function(filename, ...)  # do something only dicom can do
    

    Opening the file twice for metadata and image data is an explicit choice because I think the case of not caring about metadata is much more common than needing metadata. If a user only wants metadata, e.g., for warehousing, then it can be much faster to not have to read the entire image on a lot of files; though I don't think many plugins support this currently (but they might!). For cases where a user wants both, metadata and image data, this API choice is indeed suboptimal, especially for a lot of files. We could think of

    metadata(filename, ...) #  still exists
    imread(filename, *args, plugin=None, metadata=False, **kwargs) # returns a single nd-array
    imread(filename, *args, plugin=None, metadata=True, **kwargs) # returns a (metadata, nd-array)-tuple
    imiter(filename, *args, plugin=None, metadata=False, **kwargs)
    

    Not sure if this makes things a little redundant though. In the case of imiter it might be wasteful to return the same metadata each time.

    Reading 4 specific images from a file is not a primary use-case listed in the top post :P If we want to do that, we are steering close to the slicing API. The current API returns/yields nd-images ... you would only need a single call

    imread(filename)[[i, j ,k l], ...] # reads the entire file and then slices the numpy array
    
    # if memory is a concern
    images = [img for idx, img in enumerate(imiter(filename)) if idx in [i, j, k, l]]    
    
  17. almarklein commented on Nov 18, 2020

    @almarklein
    MemberAuthor

    If you mean custom methods on imopen [...]

    Yeah, that's what I meant. But I don't think it's a strong argument, because we can have kwargs in imread, like you mentioned.

    I realized an important shortcoming: wrapper API's like @lschr's array-like interface would not be possible ...


    I'm starting to think that we cannot have a single API. We can discern at least 3 API's:

    • The imopen API to provide access to a plugin object. This seems to be an API offering complete functionality, and is still quite concise, but requires a with-statement in most cases.
    • The imread/metaread/imiter API (a thin layer over imopen), is more friendly and covers the need of 80-90% of users.
    • The array-like API (a thin layer over imopen). Convenient for lazy loading, but probably more for advanced users.

    Each of these have their strengths. I think we need imopen as a basis, but also imread because forcing the with-statement on all users is not the way to go.

    What do you think? If this sounds good, let's start a new discussion on where each API should live ... and how to deal with backwards compatibility.

  18. lschr commented on Nov 18, 2020

    @lschr
    Contributor

    I think it is best (as suggested and as it is now) to have a low-level API offering maximum flexibility (possibly at the cost of unease (?) of use) plus, on top of that, high-level API(s) covering most use cases. The current documentation also makes it very clear which one is which 👍.

    That being said, @almarklein 's suggestions should be easy to implement (unless I am missing something):

    • imopen(…, mode="r") would be basically the same as get_reader is now
    • imopen(…, mode="w") <-> get_writer
    • imread(…, mode="ri") <-> imread
    • imread(…, mode="rI") <-> mimread
    • …

    To keep backward compatibility for some time, one could (for instance) implement the old API as a wrapper around the new API and emit a DeprecationWarning. The deprecated package provides a convenient way of doing this (I think; never have used it since I prefer not to pull in another package just for this).

  19. FirefoxMetzger commented on Nov 18, 2020

    @FirefoxMetzger
    Contributor

    I realized an important shortcoming: wrapper API's like @lschr's array-like interface would not be possible ...

    Not sure I follow. Do you mean the ability to subclass the "API object" and specialize it?

    Either way, it is a nice idea to have multiple APIs depending on the use-case. I am a bit worried that this proliferation could lead to a long-term maintenance headache, especially if we need/want to change imopen in the future. This is not something we have to worry about now though. Let's go with this idea and discuss where things should live. Do we do this here or in a new issue?

    Random proposal: Have imopen and the array API live in imageio.advanced and the easy API live in the main namespace imageio.

  20. almarklein commented on Nov 19, 2020

    @almarklein
    MemberAuthor

    I realized an important shortcoming: wrapper API's like @lschr's array-like interface would not be possible ...

    Not sure I follow. Do you mean the ability to subclass the "API object" and specialize it?

    I meant that there is no longer an open reader object to wrap, so lazy loading is not possible (or very inefficient).

    Let's go with this idea and discuss where things should live. Do we do this here or in a new issue?

    I was just composing a new issue, but as I wrote it, I felt an unease, because I was basically listing 4 API's: the imopen, the new imread, the array-like, and the current imageio API (for backwards compatibility). This is a bit ... overwhelming.

    This leads me to the following:

    • I'd like to propose the imopen plus the imread convenience functions as a single API.
    • The array-like API is external (useful, but out of scope for imageio).
    • We need a fresh start, a separate namespace, maybe even a new package. I think refactoring the current API on top of the new imopen would be hard.
  21. almarklein commented on Nov 19, 2020

    @almarklein
    MemberAuthor

    Let's continue in #569

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions