Skip to content

Consistent API endpoint for orientation/rotation tag #455

Open

Description

@xkortex

See #362 for the meta-data overview issue.

This relates to #362, #382 and #371 . I would like to see an endpoint in the API which provides any orientation information which was used to transform the image on loading.

Here is my use case. I have a dataset of ~30k images of just about every data format under the sun, but mostly jpg. 75% have the exif Orientation tag, and a third of those have a non-upright rotation. I have a corresponding set of png images which are binary masks of regions of interest. All of the masks have the same orientation of the raw image array, i.e. ignoring the orientiation tag. But, I also need the images oriented upright, so that they can be fed into various detectors which are rotationally variant.

I cannot map over imageio.imread(uri, exifrotate=False) easily, because I get this error on non-jpg images, see #454, otherwise I could load everything with consistently no rotation, and rotate myself. Right now, I am using this function to pull the orientation value in a manner similar to the JPEGFormat(PillowFormat) reader.

def get_orientation(metary):
    # hastily assigning integer tags to invalid/unread orientation
    meta = getattr(metary, 'meta', {})
    exif = meta.get("EXIF_MAIN", {})
    if not exif:
        return -1
    ori = exif.get("Orientation", -2)
    return ori

which works, but I do not have any guarantees about the stability of those keys. Image orientation seems to be a thorn in many sides, so I think it would help further imageio's goal of being a one-stop-shop python frontend for image I/O if the ability to manipulate orientation gracefully were a part of the public API, or at least a consistent key in the metadata.

One way I would suggest accomplishing this would be to, whenever a function like Reader._rotate is called, set img.meta['orientation'] = ori. Therefore the presence of that key indicates the image was rotated on load. If you wanted to save as jpg without orientation, you would del img.meta['orientation']. Saving to a non-jpg format would save the array as displayed. One could even throw a warning that it is saving with an orientation tag present, to a format that lacks orientation support.

Another option would be a helper function get_orientation provided with the library, which would update if the EXIF_MAIN were to ever change.

Possibly, it might make sense to have an origin property, which is expected to be a transformation matrix. This would be generally useful in the ITK sphere, for DICOM slices, etc. JPG exif would be mapped to one of eight 3x3 affine matrixes corresponding to the Orientation tags on load. This approach might be bringing a bazooka to a knife fight though. :)

Activity

  1. xkortex commented on Feb 19, 2020

    @xkortex
    Author

    Here's a convenience function I've been using. I have some other stuff that I might wanna PR, but I have to check with my employer first.

    def get_orientation(im):
        # type: (Image) -> Optional[int]
        """
        Get the orientation tag parsed by imageio
        Args:
            im: imagio Image object with .meta property
    
        Returns:
            exif orientation value
    
        >>> import imageio
        >>> n = 6
        >>> img = imageio.imread('https://raw.githubusercontent.com/recurser/exif-orientation-examples/master/Landscape_{}.jpg'.format(n),
                        exifrotate=1)
        >>> ori = get_orientation(img)
        >>> assert n == ori
        >>> assert img.shape == (1200, 1800, 3)
        """
        meta = getattr(im, "meta", {})
        exif = meta.get("EXIF_MAIN", {})
        if not exif:
            return None
        ori = exif.get("Orientation", None)
        return ori
  2. hmaarrfk commented on Sep 24, 2020

    @hmaarrfk
    Contributor

    Have you figured out how to write the exif orientation using imageio?

  3. FirefoxMetzger commented on Jun 22, 2021

    @FirefoxMetzger
    Contributor

    @hmaarrfk We have a unit test for pillow that tests the exif orientation tag written by ImageIO

    def test_exif_orientation(image_files: Path):
    from PIL.Image import Exif
    im = np.load(image_files / "chelsea.npy")
    # original image is has landscape format
    assert im.shape[0] < im.shape[1]
    im_flipped = np.rot90(im, -1)
    exif_tag = Exif()
    exif_tag[274] = 6 # Set Orientation to 6
    iio.v3.imwrite(
    image_files / "chelsea_tagged.png", im_flipped, plugin="pillow", exif=exif_tag
    )
    with iio.imopen(
    image_files / "chelsea_tagged.png",
    "r",
    plugin="pillow",
    ) as f:
    im_reloaded = f.read()
    im_meta = f.get_meta()
    # ensure raw image is now portrait
    assert im_reloaded.shape[0] > im_reloaded.shape[1]
    # ensure that the Exif tag is set in the file
    assert "Orientation" in im_meta and im_meta["Orientation"] == 6
    im_reloaded = iio.v3.imread(
    image_files / "chelsea_tagged.png", plugin="pillow", rotate=True
    )
    assert np.array_equal(im, im_reloaded)

    It uses pillows EXIF class until there is some more concrete idea on how metadata can be handled consistently. Because of this, you might consider it more of a hack than a solution depending on what you were looking for.

  4. FirefoxMetzger commented on Jan 26, 2022

    @FirefoxMetzger
    Contributor

    I'm going through metadata issues at the moment, to see which ones are still relevant.

    @almarklein I think the main problem here is that the pillow plugin doesn't auto-rotate. However, most other image-related projects I am aware of do. Do you think it makes sense to change this default in ImageIO v3 to closer match users' expectations?

    I have a corresponding set of png images which are binary masks of regions of interest. All of the masks have the same orientation of the raw image array, i.e. ignoring the orientiation tag. But, I also need the images oriented upright, so that they can be fed into various detectors which are rotationally variant.

    @xkortex Not sure if you still remember the situation you had (or if this is still relevant). If you do, could you comment whether auto-rotating all images (if such a tag is present) would solve your problem?

    Regarding a standardized name for any rotation that may exist, we could start discussing it as a candidate for ImageProperties (see #739 and also the big metadata discussion in #362 ). My main problem is that it becomes a bit confusing which value to set: Assume a plugin auto-rotates. Should it now set the orientation field to the value that is stored in the file or to the value that represents the orientation after the data was loaded? What about loading with auto-rotation disabled? Both make sense, but neither seems more "natural" than the other.

  5. almarklein commented on Jan 28, 2022

    @almarklein
    Member

    Do you think it makes sense to change this default in ImageIO v3 to closer match users' expectations?

    +1

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