Skip to content

Decorators around annotate functions, convert PIL images to np.ndarray - #875

Merged
onuralpszr merged 10 commits into
roboflow:developfrom
LinasKo:feature/annotators-accept-PIL-images
Feb 28, 2024
Merged

onuralpszr merged 10 commits into
roboflow:developfrom
LinasKo:feature/annotators-accept-PIL-images

Conversation

@LinasKo

@LinasKo LinasKo commented Feb 10, 2024 •

Copy link
Copy Markdown
Contributor

Description

PR for #859: Annotators will now accept both np.ndarray and PIL.Image.Image.

  1. Added a type that encapsulates both np.ndarray and PIL.Image.Image
  2. Added a decorator that checks for the type, and if it's not np.ndarray, converts to it, the does annotation, and converts the image back.
  3. Annotated every annotate implementation I could find, including the deprecated BoxAnnotator.
  4. Changed the docs and types of annotate functions to use the new ImgType
  5. Added a docstring ImgType, but the static checker did not allow it below the declaration, so it does not appear in my VSCode when hovering over the type. More on this later.

No new dependencies, but internally, a new image type is now created in supervision/annotators/base.py

  • New feature (non-breaking change which adds functionality)

How has this change been tested, please provide a testcase or example of how you tested the change?

For all annotator types, visualised the before and after results, both when np.ndarray image, and PIL.Image.Image are passed in. Ran the same on latest develop branch to check for regressions (with PIL images commented out as that's not supported)

Colab: https://colab.research.google.com/drive/14dtq8SrY1FanCPMT0GGZ2R-7jrbvfQw4?usp=sharing

Test assets:
Image: https://github.com/roboflow/supervision/assets/6500785/ec6ca6cb-0215-413b-96c6-f6802c34ece8
Video: https://github.com/roboflow/supervision/assets/6500785/4994d0bc-e79b-4f63-ac03-c83ddf472756

Any specific deployment considerations

None that I'm aware of.

Docs

Would we need to explain what ImageType is in more detail somewhere?

Tradeoffs

There was a surprising amount of tradeoffs to consider for this one. A simple change, but without knowing your philosophy around documentation, the "right" solution might be different:

Union vs TypeVar

The issue with Union is that it does not guarantee the type passed in to annotate will be the same as the one returned. If anyone's using mypy, it will produce red error squiggles. Every. Single. Time.
I know you're not aiming for mypy consistency yet, but users who do would need a typing.cast call or isinstance whenever annotators are used, or learn to ignore error markers.
On a positive side, Union[img_t1, img_t2] is self-documenting and very clear as to what it is.

TypeVar is an alternative that binds the values, very similar to how C++ templates would treat type T. E.g. If you pass np.ndarray, the static checkers will know it's np.ndarray when it's returned.
The downside - it's not self-documenting. When you mouse over ImgType, you get (variable) ImgType: type[ImgType] and need to go to the source to see what it is, so it's harder to know what arguments to pass in.
But, mouse over the result of annotate, and you'll get a nice clean np.ndarray or PIL.Image.Image, depending on what you passed in.

In my opinion, it's annoying when you copy-paste the simplest examples of a library and it already produces error markers. The static type safety is worth it, and TypeVar is the way to go, with docs that could be added to explain usage.

In light of that, I added a docstring, but it needs to be below the declaration to appear in VSCode, and that's prevented by the pre-commit hook. I moved it above TypeVar for now.

Simple functions vs Decorator vs Wrapper

  1. Easiest implementation is two functions - one for encoding, one for decoding, added to the start and end of each annotator function. But that's not very DRY.
  2. Second option is to keep annotate as is, taking an nd.array, and make a decorator that takes ImgType and converts. It's what we want to happen, but the issue is docs - the user will see np.ndarray as required argument, but actually it's the more broader ImgType
  3. (One I implemented) Have the same decorator, but also change types of annotate to accept ImgType (that we always know will be np.ndarray. Docs are now correct from user's perspective, but not if someone was somehow calling the function directly / forgets to add the decorator.
  4. From the dev's perspective, the best solution would be to split annotate into 2: public annotate taking ImgType and private _annotate taking np.ndarray. The user sees the general one that does the conversion, and each annotator implments _annotate. The downside? Docs, again. We'd lose the ability to have different ones for each annotator.

@CLAassistant

CLAassistant commented Feb 10, 2024 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@LinasKo

LinasKo commented Feb 10, 2024

Copy link
Copy Markdown
Contributor Author

Seems that checker doesn't like variable docstrings at all - not them being below the declarations.

* Bad decision, but makes the pre-commit hook happy
@LinasKo

LinasKo commented Feb 10, 2024

Copy link
Copy Markdown
Contributor Author

Ready for review. Second commit removes the docstring I think is important, but makes the pre-commit hook pass.

@SkalskiP

SkalskiP commented Feb 13, 2024 •

Copy link
Copy Markdown
Collaborator

Hi @LinasKo 👋🏻 Thanks for your interest in supervision and time working on this PR.

Thank you also for the in-depth description that helped me understand your thinking. From the description of the PR, I conclude that this is a kind of invitation to discussion, and potential changes are still possible.

Here is my hierarchy of priorities: documentation, mypy happiness, being DRY. This is a library. I have no problem with repetition (within reason, of course) as long as users have total comfort.

Seems that checker doesn't like variable docstrings at all - not them being below the declarations.

Could you elaborate a little on this thought? I'm not quite sure I know what you mean :)

Comment thread pyproject.toml Outdated
opencv-python-headless = ">=4.5.5.64"
requests = { version = ">=2.26.0,<=2.31.0", optional = true }
tqdm = { version = ">=4.62.3,<=4.66.1", optional = true }
types-pillow = "^10.2.0.20240206"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@onuralpszr I'm curious about your opinion here.

@LinasKo LinasKo Feb 13, 2024 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added this and poetry.lock by mistake. This commit should only have touched annotators/base.py.

Shall I revert that?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @LinasKo, my main question is how will you run annotated = Image.fromarray(annotated) without Pillow?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@LinasKo I'm also updating my previous comment about docs. Please give me few minutes.

@LinasKo LinasKo Feb 13, 2024 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, that's right, you don't have Pillow as a dependency at all? That's curious.

Seems like me having it installed when running the tests was preventing any dependency errors from popping up.

Yes, it needs to be added.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Feel free to add it. ;)

@onuralpszr onuralpszr Feb 13, 2024 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@LinasKo @SkalskiP let's remove that and If we REALLY needed it. we can add into dev package but for main package %100 no let's remove from there

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@SkalskiP types-pillow or type-opencv etc. for mypy and type checks not a dep for actual package

@LinasKo

LinasKo commented Feb 13, 2024 •

Copy link
Copy Markdown
Contributor Author

this is a kind of invitation to discussion, and potential changes are still possible

Yup - happy to support this PR to the end (deployment or the decision not to), hoping to learn about the repo along the way :)

Here is my hierarchy of priorities: documentation, mypy happiness, being DRY. This is a library.

Perfect - I needed that. Is it the case that user-facing aspects come first, and code clarity after that (within reason)? I think that'd be a valid approach.

Could you elaborate a little on this thought? I'm not quite sure I know what you mean :)

Suppose I want to add documentation for the variable ImgType like so:

ImgType = TypeVar("ImgType", np.ndarray, Image.Image)
"""
An image of type `np.ndarray` or `PIL.Image.Image`.

Unlike a `Union`, ensures the type remains consistent. If a function
takes an `ImgType` argument and returns an `ImgType`, when you pass
an `np.ndarray`, you will always get an `np.ndarray` back.
"""

If put like this, it appears in VS Code:
image

However, running pre-commit run --all-files then causes:
image

At first I thought it'd be fixed if I moved the docstring above the type declaration, but no - as long as I have a dosctring outside a function / class, the hook shows a failure.

@SkalskiP

SkalskiP commented Feb 13, 2024 •

Copy link
Copy Markdown
Collaborator

@LinasKo

Yup - happy to support this PR [...] hoping to learn about the repo along the way :)

Awesome! I am very happy that people like you want to join the community.

Is it the case that user-facing aspects come first, and code clarity after that (within reason)?

I try to make the quality of the code as high as possible, but I believe that specific appeals change when you build an open-source library that you want others to contribute to. I try to build the code so that outsiders can come in and make changes without being thoroughly familiar with the entire library. I can expand on this thought if you want.

However, running pre-commit run --all-files then causes:

@onuralpszr, can we add some ruff exceptions to the rule here?

Also:

  • Please let's change the name from ImgType to ImageType.
  • I would also update annotators' docstrings and specify that the scene is ImageType and can be np.ndarray or PIL.Image. This way, people will see that documentation as well.

@onuralpszr

onuralpszr commented Feb 13, 2024 •

Copy link
Copy Markdown
Contributor

@SkalskiP

pre-commit/pre-commit-hooks#159

This is a known issue so I am probably going to remove that pre-commit rule from our list and going to add docs rules for python to enforce us to type properly. For short solution either let's remove or exclude file but I would prefer to remove rule and adding rule in separate PR. I suggest @LinasKo remove "- id: check-docstring-first" rule and I will come up something better but I don't wanna add more commit into this PR.

@LinasKo

LinasKo commented Feb 14, 2024 •

Copy link
Copy Markdown
Contributor Author

@SkalskiP
Got a question about the process; but likely ready for review.

At the time of writing the only conflicts are the hash in poetry.lock and:

pyproject.toml

<<<<<<< feature/annotators-accept-PIL-images
tqdm = { version = ">=4.62.3,<=4.66.1", optional = true }
pillow = "^10.2.0"
=======
tqdm = { version = ">=4.62.3,<=4.66.2", optional = true }
>>>>>>> develop

(<=4.66.1 vs <=4.66.2)

The workflow I'm used to is running a rebase onto the latest develop before merging, which should help solve the tqdm diff; however I don't know what'd happen to the PR on GitHub - as far as I know, the commit hashes for my changes are regenerated and that could, in theory, detach or wipe the conversation.

There's also #889 waiting to be merged. The tidiest way is to merge that in, squish commits in this PR, rebase on top.

What's your usual process? Do you prefer an extra commit to resolve conflicts before merging, or do you rebase? In the latter case, does it affect GitHub PR history? Do I just hand it off to one of you at this point?

@LinasKo
LinasKo requested a review from SkalskiP February 14, 2024 12:29
@SkalskiP SkalskiP mentioned this pull request Feb 21, 2024
1 task done
@onuralpszr

Copy link
Copy Markdown
Contributor

@LinasKo can you do resolve the conflict or I can do it too ?

@onuralpszr

Copy link
Copy Markdown
Contributor

@LinasKo accept our develop side then add pillow via poetry and make sure you effect lock file as well. If you cant I can handle it too

@LinasKo

LinasKo commented Feb 26, 2024

Copy link
Copy Markdown
Contributor Author

@onuralpszr, "Accept our develop side" - do you mean a merge request from develop? That'll spam this PR with commits as far as I can tell.

On my machine, it's ready to be pushed, so let me know and I'll do it.

@LinasKo

LinasKo commented Feb 26, 2024

Copy link
Copy Markdown
Contributor Author

I figured out what you meant. Resolve here, accept develop changes, then pull, and add Pillow. 1 sec.

@onuralpszr

onuralpszr commented Feb 26, 2024 •

Copy link
Copy Markdown
Contributor

@LinasKo you need add pillow as well I thought you gonna add while merging but please re add it :)

@LinasKo

LinasKo commented Feb 26, 2024 •

Copy link
Copy Markdown
Contributor Author

@onuralpszr, That was a merge-via-UI, which would not have helped generate the hash.

Should be ready now. Dependency resolution took ages.

Thanks!

@onuralpszr

Copy link
Copy Markdown
Contributor

That was a merge-via-UI, which would not have helped generate the hash.

Should be ready now. Dependency resolution took ages.

If you struggle I can clean up too no problem. :)

@LinasKo

LinasKo commented Feb 26, 2024

Copy link
Copy Markdown
Contributor Author

That was a merge-via-UI, which would not have helped generate the hash.
Should be ready now. Dependency resolution took ages.

If you struggle I can clean up too no problem. :)

It's a trivial fix - various steps just took ages :)

@onuralpszr

Copy link
Copy Markdown
Contributor

@LinasKo thank you for your contribution, merging in !!

@onuralpszr
onuralpszr merged commit 96225cd into roboflow:develop Feb 28, 2024
@SkalskiP

Copy link
Copy Markdown
Collaborator

Hi @LinasKo and @onuralpszr ! 👋🏻 Thanks for pushing this PR to the finish line without me! I really like how this change has been implemented. Very clean with minimal code changes. 🔥

@LinasKo
LinasKo deleted the feature/annotators-accept-PIL-images branch April 11, 2024 09:37
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.

4 participants