Skip to content

Add sliceable interface class akin to PIMS - #564

Closed
lschr wants to merge 2 commits into
imageio:masterfrom
lschr:image_sequence
Closed

lschr wants to merge 2 commits into
imageio:masterfrom
lschr:image_sequence

Conversation

@lschr

@lschr lschr commented Nov 6, 2020

Copy link
Copy Markdown
Contributor

Some examples:

>>> seq = imageio.ImageSequence("some_file.tif").open()
>>> len(seq)
30
>>> seq[0]
Array([[203, 362, 223, ..., 225, 512, 432],
       [386, 234, 278, ..., 303, 354, 233],
       [211, 328, 722, ..., 194, 215, 478],
       ...,
       [203, 230, 261, ..., 155, 367, 177],
       [156, 290, 219, ..., 530, 179, 317],
       [432, 327, 355, ..., 500, 227, 182]], dtype=uint16)
>>> seq2 = seq[1::2]
>>> seq2
<imageio.core.sequence.ImageSequence object at 0x7fa706829d50>
>>> len(seq2)
15
>>> np.all(seq2[1] == seq[3])
True
>>> seq.close()

Key points:

  • Indexing with a slice or a sequence of ints or bools will create a new ImageSequence object
  • Indexing with an int will return the image data

This is work in progress. Documentation as well as tests are missing, but I would like some feedback before spending more time on it. Inspired by PIMS.

@lschr lschr mentioned this pull request Nov 6, 2020
@FirefoxMetzger

Copy link
Copy Markdown
Contributor

Well from #563 it is pretty obvious that I like the slicing idea.

I would choose not to give __getitem__(<int>) and __getitem__(<slice/tuple/list>) different meanings (and return types (!)). I would probably go for a separate seq.load(), seq.read(), seq.data(), or seq.to_numpy() or something like that.

Have you thought about __enter__ and __exit__ instead of or in addition to .open() and .close()? That way you could do

with imageio.ImageSequence("some_file.tif") as seq:
    # Fancy selection - proper cleanup even with exceptions/errors
    img = seq.read()
# file has now been cleaned-up

@lschr

lschr commented Nov 6, 2020

Copy link
Copy Markdown
Contributor Author

I would choose not to give __getitem__(<int>) and __getitem__(<slice/tuple/list>) different meanings (and return types (!)).

This is done throughout Python. When slicing a list (i.e., list.__getitem__(<slice>)), a new list is returned. When indexing with an integer (list.__getitem__(<int>)), you get the corresponding list entry. Same for tuples, numpy arrays, pandas structures, …

Have you thought about __enter__ and __exit__ instead of or in addition to .open() and .close()? That way you could do

with imageio.ImageSequence("some_file.tif") as seq:
    # Fancy selection - proper cleanup even with exceptions/errors
    img = seq.read()
# file has now been cleaned-up

This is already implemented. However, __enter__ and __exit__ are complementary to open and close. Sometimes it is the right thing to temporarily open a file, read contents, close it again (__enter__ and __exit__), while sometimes it is necessary to open the file (e.g., in some class's __init__) and close it in a different context (e.g., __del__). Hence both options exist.

@FirefoxMetzger

FirefoxMetzger commented Nov 7, 2020 •

Copy link
Copy Markdown
Contributor

This is already implemented. [...] Hence both options exist.

True, and I agree with this rationale. I missed the functions when I first read the code; my bad.

This is done throughout Python. When slicing a list (i.e., list.getitem()), a new list is returned. When indexing with an integer (list.getitem()), you get the corresponding list entry. Same for tuples, numpy arrays, pandas structures, …

You are absolutely right; slice returns a container of the same type but only holding a slice of the original, and int returns the element held by the container.

I think I have misunderstood the intent of the interface; do you aim for it to be applicable to sequences of 2D images only, or were you thinking about sequences of nd-images? For sequences of 2D images, this convention is indeed clear and actually pretty smart. For nd-images, I wonder how the user would request the third image in the fourth stack in a sequence of volume images. In such a case, would you return volumes only?

@almarklein

Copy link
Copy Markdown
Member

Thanks @lschr! It's really nice to see what this could look like.

That said, in the end I think I prefer an API based on functions without mimicking an array. I mentioned a few arguments in #563. Another came to mind as I read through the example code here: I fear that an API like this can trick people into moving the ImageSequence (or plugin object) deeper into their code, thus preventing the file from closing.

Reading data and processing data are different stages, and having a different API is fine. I understand how this indexing API can provide sort of a lazy loading mechanism, which can be really nice in some cases, but in most cases it's better to load the data and close the file asap. Preferably under a (short) context manager.

What this code here also shows, is that an index-based API can quite easily be built atop the existing imageio API, and surely this will hold for the new API as well :)

@lschr

lschr commented Nov 9, 2020

Copy link
Copy Markdown
Contributor Author

@FirefoxMetzger This is just thin wrapper around Reader.get_data. I don't have any 3D data to try, but I guess you'd use mode="v" or something and get a volume.

@lschr

lschr commented Nov 9, 2020

Copy link
Copy Markdown
Contributor Author

@almarklein I didn't intend this as a replacement of the function-based API, but as an extension of the “advanced” get_reader()-based API (and, of course, any prospective API).

I work in fluorescence mircoscopy, where it is common to record long sequences of images exciting alternatingly with different light sources. In this case being able to select the image type by slicing (e.g., red_seq = seq[::2]; green_seq = seq[1::2]) is extremely convenient. Those can be passed directly to analysis and manipulation functions that accept sequences of images. An example within imageio:

with ImageSequence("some_file.tif") as ims:
    mimwrite("every_other_frame.tif", ims[::2])

As the sequences are often several GB in size, it is not possible to load everything into RAM and then do the slicing.

I understand your concerns about misuse like not closing files, but these are already true when using get_reader(). I don't think having an indexable and sliceable, additional interface will add to the danger. I would assume that an advanced user (to whom the advanced APIs are geared) knows how to do the right thing.

Of course I could move this to a separate project (as you said, it is merely built on top of the existing API), but I do believe that it should be a part of imageio.

Clean up, add API documentation and tests.
@lschr

lschr commented Nov 17, 2020

Copy link
Copy Markdown
Contributor Author

I finished the implementation, including docs and tests.

The test fails for two reasons:

  1. tifffile has dropped support for Python 3.6 a while ago, thus using Python 3.6 implies using a quite outdated version of tifffile.
  2. The imageio plugin assumes that metadata is the same for all frames, which needs not be true. See tifffile plugin: Various fixes #567 for a possible fix.

@lschr
lschr marked this pull request as ready for review November 17, 2020 00:36
@almarklein

Copy link
Copy Markdown
Member

I don't think having an indexable and sliceable, additional interface will add to the danger. I would assume that an advanced user (to whom the advanced APIs are geared) knows how to do the right thing.

I disagree here. Yes, an advanced user knows what to do, but a novice will easily be confused. By looking at the code alone, it would be very easy to mistake the object for an array object.

I do believe that it should be a part of imageio.

Making this an alternative API based on the existing one can make sense, but I'm not sure whether it should be part of imageio. I'd prefer to keep imageio simple and provide just one API. If the use-cases for the proposed API are very common, than we could consider making it a utility of imageio, but I doubt that this is the case, to be honest.

I know you put effort into this, and I can see how it really helps your use-case. My suggestion would be to create a new library. I would be ok with refering to it from the imageio docs.

@lschr

lschr commented Nov 17, 2020 •

Copy link
Copy Markdown
Contributor Author

This will for now be part of my sdt-pyhon package. A link in the documentation would be nice so that people know that this exists. Should I make a pull request once a new version of sdt-python containing the ImageSequence class is released?

@FirefoxMetzger

FirefoxMetzger commented Nov 10, 2021 •

Copy link
Copy Markdown
Contributor

Closing this one since it has been superseded by #574 that is now merged.

I still like the idea of a sliceable interface to control which section of data will get loaded; however, knowing what I know now, I realize that this approach will be doomed as a general API for all plugins in ImageIO. For example, SPEv3 is a format that (from what I understand) stores sequences of ROIs which by default have unique shapes. Similarily, TIFF has a subIFD tag that allows creating a hierarchical layout inside a TIFF file. One of the use-cases for this is to attach thumbnails or downsampled versions of the image to the image itself. These, too, come in different shapes and a sliceable interface would be unintuitive.

However, there are definitely good examples for when such a sliceable interface is useful, e.g., with large volumetric data that you don't wish to load into memory in one swoop. For these cases, a sliceable interface can (maybe should) be added to the respective plugins that can benefit from it. This interface would then be available for that specific plugin inside a iio.imopen context:

with iio.imopen("...", plugin=...) as file:
    # the resource was opened with a specific plugin for which
    # a sliceable interface makes sense

    # the common API still works
    data = file.read(index=3)

    # but a plugin-specific sliceable API is available, too
    data = file[5:7, ...]

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants