Skip to content

META ISSUE: Revisit how imageio provides and handles meta data #362

Closed

Description

@almarklein

This is a meta issue about meta data - in this top post I try to keep track of the current status. If you want to comment, see if there already is an issue related to your question/comment, open a new issue, or comment below.

Related issues

Goals

  • Provide the user with a small subset of meta data with standardized fields and values.
  • Provide the user with the full original raw metadata (differs per format).
  • Make it possible for the user to read both of the above without actually reading the image data (where the format allows it).
  • Make it possible to provide both standardized and format-specific metadata when writing images.

Questions

Current status of imageio

  • The read functions return an imageio.Image object (subclass of ndarray) which has a .meta dict attached.
  • We have Reader.get_meta_data() but it does not have standard elements, so is usually not very helpful (Inspecting shape, dtype, etc. #263).
  • The (generic) Writer class allows giving meta data explicitly, and also checks for the .meta attribute.
  • The high level public API (e.g. imwrite()) does not have a way to provide meta data explicitly.

The plan / tasks

Activity

  1. lschr commented on Aug 6, 2018

    @lschr
    Contributor

    One could also use an approach similar to https://github.com/soft-matter/slicerator:

    • Add an attribute to Image that contains a list of attributes that should be copied after image processing, e.g.
    class Image:
        _propagate_attrs = ["meta"]
        ...
    • Provide a function decorator that can be used on processing functions to copy all attributes listed in _propagate_attrs to the result array.
    def copy_attrs(func):
        def wrapped(input, *args, **kwargs):
            res = func(input, *args, **kwargs)
            for a in getattr(input, "_propagate_attrs", []):
                setattr(res, a, getattr(input, a, None))
            return res
        return wrapped
    
    @copy_attrs
    def do_something(arr):
        return numpy.zeros_like(arr)

    (not sure if above code actually works, but I think you get the idea). This is a very general approach; one could also limit it to checking whether a meta attribute exists and if so, copy it.

  2. almarklein commented on Aug 7, 2018

    @almarklein
    MemberAuthor

    I can see how such an approach would make it easier to work with a custom Image class. The thing is that imageio does not have any processing functions itself, and skimage got rid of using a custom class some years ago.

    The purpose of this issue is to find a way to make meta data more (generically) useful (e.g. by standardizing certain info), let it work well with whatever skimage will decide on in scikit-image/scikit-image#2605, and along the way, if possible, drop the Image class too.

  3. jakirkham commented on Aug 9, 2018

    @jakirkham

    What sort of metadata can the builtin plugins currently provide (including stuff that might not be nicely exposed currently)?

  4. almarklein commented on Aug 10, 2018

    @almarklein
    MemberAuthor

    @jakirkham That's a good question. I think that it should be possible to inspect shape, dtype and nchannels for most plugins, though many plugins will need work to do this before the loading of the data. There may also be plugins for which it is not possible to read metadata before reading the image data. What other kinds of generic metadata could we think of?

  5. lschr commented on Aug 10, 2018

    @lschr
    Contributor

    I think most formats support some kind of description or comment tag, which would be very helpful to have access to. Also date and time are very common.

  6. lschr commented on Aug 13, 2018

    @lschr
    Contributor

    Additionally, colorspace (what each channel represents; RGB or CMYK …) information may be useful.

  7. jni commented on Aug 21, 2018

    @jni
    Contributor

    I totally missed this! Hi @almarklein! =) (And hi @jakirkham! =) (@lschr we haven't met but now it feels rude not to say hi. =P 👋 )

    Regarding what metadata you could include, for microscopy an absolutely essential one is the pixel spacing. Some microscopes also do tiling and include e.g. stage positioning information, which then aids in mosaicing/registration to get the full image. Sometimes the units of the image data are also useful, e.g. "photons".

    Regarding what to do with it, it goes far beyond copying and every function does something different. For example, downsampling requires one to increase the pixel spacing by a corresponding factor. Scaling the image requires adjusting the units. Colorspace conversion requires changing the colorspace. etc.

    I think I just talked myself out of handling all this in scikit-image. =P

    As to what imageio does with the Image class, from scikit-image's perspective I am agnostic. You can unpack into (array, dict) using return_meta, or you can keep returning Image and we can unpack it on our end easily enough.

    I do like the idea of standard metadata fields and having imageio provide them (rather than doing the conversion on skimage's end). I can do a bit of work here both in discussing standard field names, and in providing an appropriate conversion for some formats (notably FEI, for which I wrote the reader).

    One question is how to deal with the existing metadata tags that may or may not map to our standard ones. I think we would want to keep them, while still doing the conversion. For example, the FEI format has two layers of annotations, and pixel spacing is under ['Scan']['PixelHeight'] and ['Scan']['PixelWidth']. (And these are in meters, which is simultaneously sensible and silly. =P) How do we prevent namespace clashes in the metadata hierarchy? I see two options:

    • return two metadata dictionaries, one "raw" and one standardised
    • use a special key, e.g. ['imageio'], and if that key exists, check whether it's there from saving a previous imageio standard set, in which case we just keep it, or whether it's someone else's 'imageio' tag, in which case...? This gets messy quickly.

    Anyway, they're my thoughts for now. Happy to have some friends in this adventure. =D

  8. lschr commented on Aug 31, 2018

    @lschr
    Contributor

    Hey @jni ;-)

    After all, I gather it seems best to have an extra dict for metadata. I was thinking, that instead of having something like return_meta=True and changing the return signature accordingly, simply introducing a meta parameter may also be an option. This can either be None, in which case nothing happens or a user-supplied dictionary to be updated, like

    md = {}
    img = imread(..., meta=md)

    Not sure if this has any advantage; just an idea.

  9. jni commented on Sep 1, 2018

    @jni
    Contributor

    @lschr Being a functional programming proponent, I'm quite opposed to modifying input arguments, especially in public-facing functions. =)

  10. almarklein commented on Sep 3, 2018

    @almarklein
    MemberAuthor

    Things I am starting to converge on (will update the post top accordingly):

    Since we have to keep backward compatibility, I feel that any attempt to try and get rid of the Image class will add complexity. Also, as @jni points out, skimage can easily strip&convert. Therefore, I think it's best to keep it, but rename to ArrayWithMetaArray, which (I hope) sounds more like a ndarray subclass than a wrapper. Image is kept as an alias. And we should add docs (in the class's docstring and in the higher level docs) on how to convert.

    We should add an imageio.metaread() function that will (where possible) return the meta data without reading the image data. We should also add a meta argument to the write() functions.

    Things that need more thoughs and discussion:

    It seems evident that we should standardize the meta information. This means that every image comes with its "raw" meta data, as well as a "standardized" meta data. Some information may be duplicate and upon writing, it should be merged to raw meta data again. I think it makes sense to have any standardized fields overwrite the raw fields here. An alternative is to consider the standardized information as read-only and ignore it in the writers (ppl that actively write meta data probably know how to use the raw data).

    Its not trivial how to provide these two forms of meta data. As @jni mentioned:

    • They could be two dictionaries (e.g. the standardized dict could be an info attribute on the ArrayWithMeta class). Probably easiest for imageio but awkward in skimage.
    • The standardized dict could be a subdict, but under what key?
    • The standardized dict could also have a subdict for the raw data. Seems nice and clean, so maybe good for skimage? But harder to do in imageio because of backward compatibility.
  11. jni commented on Sep 3, 2018

    @jni
    Contributor

    @almarklein

    have a subdict for the raw data.

    Like, as a monkey-patched attribute? That doesn't seem like something I would describe as "nice and clean"???

  12. jni commented on Sep 3, 2018

    @jni
    Contributor

    (Overall though, I'm glad we are converging on vaguely the same space, I think!)

  13. almarklein commented on Sep 3, 2018

    @almarklein
    MemberAuthor

    @jni, haha no, as having a dict with the standardized data, which has one field called raw that contains the raw meta data. As in the other way around as what you proposed.

  14. 22 remaining items

  15. almarklein commented on Nov 17, 2021

    @almarklein
    MemberAuthor

    I think people working with time series data might disagree that spacing in time doesn't matter???

    Good point. I assumed that the unit of the values in spacing would be homogeneous. It did not occur to me that some could be spatial units (e.g. mm) and others could be temporal, or even something else. On that note, the channels could also have a relation that can be expressed with some spacing value!

  16. almarklein commented on Nov 17, 2021

    @almarklein
    MemberAuthor

    Thinking about this more ... I wonder whether we should distinguish here. If I call a skimage function that takes spacing into account, then it will very likely assume that this spacing is spatial. Should we somehow take precautions for this situation? Or is it up to the user to provide a slice that only includes spatial dimensions?

    This brings me to another point:

    a_function_that_uses_spacing(im[1,...], descriptor???)

    Looks like this brings us full circle to the custom Image class, so we can do this:

    >> im = iio.imread(...)
    >> im.shape
    (10, 512, 512)
    >> im.descriptor.spacing
    (1, 0.5, 0.5)
    >> im2 = im[0, ...]
    >> im2.shape
    (512, 512)
    >> im2.descriptor.spacing
    (0.5, 0.5)
  17. FirefoxMetzger commented on Nov 17, 2021

    @FirefoxMetzger
    Contributor

    Yes, what I'm saying is something like:
    [...]
    Then we add all of the array protocol methods and attributes.

    @jni Ah, so you are proposing a different idea from what we have been discussing so far? This looks like Image aims to lazy-load pixels using Dask (ImageIO using Dask for performance improvement), whereas I am saying that Dask can use ImageIO for performance improvement. I might misunderstand your intention though.

    Dask needs cheap access to shape+dtype information (what we currently call ImageDescriptor). Workers then load the actual pixel data eg. via iio.imread. From what I understand, however, this loading of pixel data currently happens twice. Once in the main thread to be immediately discarded after having extracted shape+dtype, and once again on the worker thread/node/... The first pixel-data read can often be avoided, and that is what I was trying to achieve with ImageDescriptor.

    Ok, something like:
    [...]
    ?

    I am even more convinced that we aren't currently not talking about the same thing 😅. My idea of iio.imread(..., out=my_object) is to take my_object, place the image data into it ("modify it in-place"), and to then return my_object instead of ndarray. Your suggestion looks like we would get my_object's buffer, modify it (in-place) and return an Image that shares the buffer with my_object.

    Essentially, what I want to be able to do with out is something like:

    # pinning memory is expensive
    batch = torch.empty((10, 512, 512, 3), pin_memory=True)
    
    for idx, img_path in enumerate(images.iterdir()):
        img = iio.imread(img_path, out=batch[idx, ...])
        # img is a torch.Tensor
    
    # batch is populated and ready to be picked up by the GPU

    Lucky guess? 😂 Remote sensing / satellite folks also like physical spacing info about their pixels.

    The community around skimage is surprisingly homogeneous 😛 and people doing hardware and/or real-time critical work usually think of python as too slow to even try (old habits die hard 🤷). This limits the number of viable guesses considerably 😆

    Do you prefer evening or morning? With a 10h difference we'll have to be a bit creative, but it can be done. 😊

    How morning is morning? I am in the gym between 6-8 am (CET) on weekdays. Depending on how long you think we need I can offer 5 am (CET), but I think @almarklein will not be too happy about that.

    Otherwise, I think the evening (again CET) will be easier.

    If I call a skimage function that takes spacing into account, then it will very likely assume that this spacing is spatial. Should we somehow take precautions for this situation? Or is it up to the user to provide a slice that only includes spatial dimensions?

    Looks like this brings us full circle to the custom Image class, so we can do this:

    I would be careful with functions that self-configure based on image metadata; it sounds a bit like this walks a line bordering magic. Being explicit about where additional metadata is being used will make the code easier to understand (albeit more verbose). It also makes things scalable, because functions don't have to rely on getting an Image as input, but can accept any ArrayLike combined with something that looks like a valid metadata struct.

  18. jni commented on Nov 17, 2021

    @jni
    Contributor

    Should we somehow take precautions for this situation? Or is it up to the user to provide a slice that only includes spatial dimensions?

    Buyer beware, imho. 😂

    a_function_that_uses_spacing(im[1,...], descriptor???)

    Yes, scikit-image will almost certainly continue to work with external parameters rather than an Image object. Here we would say eg spacing=im[1, ...].spacing as the second argument...?

    and to then return my_object instead of ndarray

    This seems pointless? You already have my_object. Just do whatever you want to do with it once you've read into it? If you're worried that my __init__ doesn't actually fill the buffer, that's fine, you can do Image(filename, out=my_object).read()?

    Your suggestion looks like we would get my_object's buffer, modify it (in-place) and return an Image that shares the buffer with my_object.

    No, it doesn't share a buffer, it uses my_object directly as the _data. As long as my_object satisfies the Array API, that's ok.

    At any rate, I'm pretty sure we can satisfy both your and my API requirements in a single API. Let's discuss more live. It'll be nice to meet you! 😃

    5am sounds painful even for me on the other end! 😂 I think two reasonable options are 8am Europe/6pm Australia (Or 8:30, dunno how much buffer you want after the gym @FirefoxMetzger!) or 10pm Europe/8am Australia. @almarklein?

  19. almarklein commented on Nov 17, 2021

    @almarklein
    MemberAuthor

    8am-8:30 is getting-kids-breakfast-and-to-school time here. 10pm would work for me. Is that doable @FirefoxMetzger ?

  20. almarklein commented on Nov 17, 2021

    @almarklein
    MemberAuthor

    I would be careful with functions that self-configure based on image metadata; it sounds a bit like this walks a line bordering magic.

    I have always been under the impression that one of the goals of this whole metadata exercise was that skimage functions can consume the standardized metadata that comes with an image.

  21. FirefoxMetzger commented on Nov 17, 2021

    @FirefoxMetzger
    Contributor

    @almarklein @jni 10pm CET / 8am ACT it is. Now for the more challenging part. Finding a date :D

    I have always been under the impression that one of the goals of this whole metadata exercise was that skimage functions can consume the standardized metadata that comes with an image.

    Yep, I think on that part we are on the same page (though maybe I'd draw the circle broader than just around skimage). However, it is a different question on whether the metadata and the pixel data should be served together (struct/object) or individually. @jni seems to prefer the Image object route, whereas I think that it will be cleaner to split metadata and pixel data into separate functions.

  22. almarklein commented on Nov 19, 2021

    @almarklein
    MemberAuthor

    though maybe I'd draw the circle broader than just around skimage

    Definitely!

    However, it is a different question on whether the metadata and the pixel data should be served together (struct/object) or individually.

    Right. I think it makes sense for functions to automatically use the standardized fields, so subsequently it makes sense for these to be attached to the image object (so that they travel along with the image). But for the plugin-specific metadata this would get muddy, and a function using that info might result in surprising (magical in a bad way) behaviour. I think this is a valid argument against putting the specific metadata on the Image.

  23. jni commented on Nov 19, 2021

    @jni
    Contributor

    @FirefoxMetzger @almarklein can you discuss dates amongst yourselves? I generally don't start my day before 9am so all of my 8ams are currently free except Dec 16. 😃 As long as it's a weekday!

    Regarding the one vs two objects, the issue is that two objects is clunky when the two things belong together and a single object is strictly more general, because I can always do result = filters.gaussian(np.asarray(image), sigma=5 / image.spacing).

    As a general rule I am indeed anti custom-objects, and my preference here would actually be that NumPy/Dask provided a "metadata" dict/namespace for custom attributes, and we would just use that. But they don't, so we have to do something else. And, the other thing I've learned in my years of campaigning against objects, is that sometimes, if you're repeatedly writing x1, y1, z1 = func(x0, y0, z0), then maybe you should bundle x, y, and z in an object.

    As to whether skimage will take these custom objects as input... I guess it depends on how custom they are vs whether we can make them standard enough. Maybe we should think about xarray? But what I'd prefer is an "annotated array" library that meets our needs and maybe a few extra — e.g. one of the things I've always wanted from skimage is the ability to annotate whether an array is an image, some coordinates, or a segmentation, among others.

  24. FirefoxMetzger commented on Nov 20, 2021

    @FirefoxMetzger
    Contributor

    @jni @almarklein Awesome. I looked up both of your emails and sent a suggestion; seemed like the easier/faster thing to do.

    Regarding the one vs two objects, the issue is that two objects is clunky when the two things belong together and a single object is strictly more general

    Doesn't that go both ways though? It's pretty easy to tear a single object into multiple bits, but it is just as possible to stack parts into one object downstream if downstream decides that it wants to consume images in this way:

    @dataclass
    class Image:
        pixel_data: np.ndarray
        descriptor: ImageDescriptor
        metadata: Dict[str, Any]
    
    with iio.imopen("some_file.png") as file:
        img = Image(file.read(), file.props(), file.metadata)
    
    # how to elegantly set sigma=5*img.spacing?
    # "sigma_multiplier" doesn't seem too intuitive
    result = filters.gaussian(image, sigma_multiplier=5)

    This touches upon another topic, which I think makes sense to talk about during the meeting: We have iio.imopen and the plugin interface which takes care of lazy for performance junkies. Maybe we can tweak that to serve your use-case @jni.

    A plugin instance is actually fairly close to a lazy-loaded Image object, and no matter our solution. It is missing numpy slicing (explicit choice in the new API #563 (comment)) and it doesn't support np.asarray(plugin_instance) (files may hold multiple images). You do get plugin_instance.read() -> ndarray and plugin_instance.descriptor.spacing though, so it has all the information you want/need in a single object.

    if you're repeatedly writing x1, y1, z1 = func(x0, y0, z0), then maybe you should bundle x, y, and z in an object.

    I agree. My angle here is that the metadata issue hasn't been resolved for years because it likely isn't as important to most users as is access to raw pixel data. So if the main use-case is x1, _, _ = func(x0, y0, z0) (aka. np.asarray(iio.imread(...))) then perhaps it is better to keep metadata separate (but easily accessible) for those who need it.

    At the same time, if you are just interested in metadata, pixel-data shouldn't slow you down. There are definite use-cases for that, e.g. to pre-configure a pipeline to then pump large quantities of them through efficiently (dask use-case). Something like a iio.improps("my.tiff") would fit that bill perfectly.

    Then there is the situation where you need both (standardized) metadata and pixel data. I think this is the one we are trying to solve now, right? The preferred solution is to get an Image object that contains both pixel data and metadata so that they stay connected and can be accessed easily. Returning an image object would have an impact on the two scenarios above, so my question here is if this happens often enough (compared to the other two scenarios) to motivate solving it like this.

    The "skimage auto-config" feature falls into the last category, and I can see how this is desirable. At the same time, I agree with the Zen of python that "explicit is better than implicit", so if we do auto-config, I would like to explicitly pass in a config object so that (a) I know exactly which functions do auto-config, and (b) I get some means of introspecting and debugging what the auto-config does if I need that.

    e.g. one of the things I've always wanted from skimage is the ability to annotate whether an array is an image, some coordinates, or a segmentation, among others.

    From an I/O perspective that would depend on the underlying format used. If the format supports exif tags or a comment field, we could easily write a comment into the metadata for those annotations. If not then those annotations would be lost once the image is saved, which is a bit sad and kind of defeats the point I guess.

  25. FirefoxMetzger commented on Dec 2, 2021

    @FirefoxMetzger
    Contributor

    It looks like we can soon bring this to a close. To summarize the meeting we had, we agreed on the following points:

    • Plugins will get two new methods: properties(self, index=None) -> ImageDescriptor and metadata(self, *, remove_applied=True) -> Dict[str, Any]. Details are in META ISSUE: Revisit how imageio provides and handles meta data #362 (comment)
    • The ImageDescriptor contains standardized metadata and will grow incrementally as we figure out what can be standardized. It will have the following fields to start with: shape, dtype, spacing
    • The functional API will get two new convenience wrappers: iio.improps and iio.imdetails
    • There will be a new object API that allows the creation of an Image object. This object is essentially a plugin, except that it allows slicing which triggers lazy-loading of pixel data.

    @almarklein @jni Anything I missed?

  26. almarklein commented on Dec 3, 2021

    @almarklein
    MemberAuthor

    We also discussed an ImageSequence object next to the Image object, right?

    Names ...

    Let's consistently call metadata "meta". So iio.immeta I guess?

    I like "props" for the descriptor. Let's also make it an ImageProps object ;)

  27. FirefoxMetzger commented on Dec 3, 2021

    @FirefoxMetzger
    Contributor

    We also discussed an ImageSequence object next to the Image object, right?

    Yes. We should see how we can add this one. It can't have a direct slicing API, due to the multi-image formats that allow different shapes (and are non-stackable as a consequence). Maybe it can be a plugin that returns Image instead of ndarray? Then again, that could be handled by doing plugin.read(like=iio.Image).

    Let's consistently call metadata "meta". So iio.immeta I guess?

    That was my first thought but I think iio.immeta is quite prone to typos due to the mm. Not sure if we worry about that. The alternative could be to consistently call everything details: iio.imdetails, plugin.details

    I like "props" for the descriptor. Let's also make it an ImageProps object ;)

    Yes, I was thinking the same actually. Didn't want to edit the previous post though, because of consistency. Lets go with properties, improps, and ImageProperties.

  28. unpinned this issue on Feb 10, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions