Compare commits

..
188 Commits
Author SHA1 Message Date
Piotr Skalski f7f40f09ba Merge pull request #1127 from roboflow/develop
`supervision-0.20.0` release
2024-04-24 19:34:57 +02:00
Piotr Skalski c5f92a544b Merge pull request #1132 from roboflow/docs/supervision-0.20.0-changelog
docs/supervision 0.20.0 change log
2024-04-24 19:32:32 +02:00
SkalskiP d6a59cb851 Merge remote-tracking branch 'origin/docs/supervision-0.20.0-changelog' into docs/supervision-0.20.0-changelog 2024-04-24 19:25:54 +02:00
SkalskiP 5c4ed2650e drop accidentally committed from_inference 2024-04-24 19:25:45 +02:00
pre-commit-ci[bot] 6ae99444b5 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-24 17:24:18 +00:00
SkalskiP 7a90eefd5b changelog updated version bump from 0.20.0rc2 to 0.20.0 2024-04-24 19:22:59 +02:00
SkalskiP 65ddf9d67d Merge remote-tracking branch 'origin/develop' into develop 2024-04-24 16:57:44 +02:00
Piotr Skalski b0840911fc Merge pull request #1131 from roboflow/docs/refactor_before_0.20.0_release
docs/refactor before supervision 0.20.0 release
2024-04-24 16:47:06 +02:00
pre-commit-ci[bot] f4fca3339d fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-24 14:45:20 +00:00
SkalskiP d7da00c55b make pre-commit happy 2024-04-24 16:43:40 +02:00
pre-commit-ci[bot] 383c1a1d8d fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-24 14:39:03 +00:00
SkalskiP e5d1ac7238 Merge remote-tracking branch 'origin/docs/refactor_before_0.20.0_release' into docs/refactor_before_0.20.0_release 2024-04-24 16:38:47 +02:00
SkalskiP 895562d444 make pre-commit happy 2024-04-24 16:37:41 +02:00
pre-commit-ci[bot] 263420758e fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-24 14:36:17 +00:00
SkalskiP 1c42838ca1 improved docs linking 2024-04-24 16:35:34 +02:00
SkalskiP 908f3d14c6 improved docs linking 2024-04-24 16:28:48 +02:00
SkalskiP 389453777e vertex and edge annotators visualizations added 2024-04-24 16:18:21 +02:00
SkalskiP 77793571b0 major docs refactor 2024-04-24 15:39:08 +02:00
Linas Kondrackis 48809c1332 Add a basic from_supervision function to KeyPoints 2024-04-24 16:37:41 +03:00
Piotr Skalski 2c90a1ef1e Merge pull request #1129 from roboflow/fix/keypoints-no-detections
Fix keypoint crash with no detections
2024-04-24 14:07:49 +02:00
Linas Kondrackis 4b89bece4f Fix keypoint crash with no detections 2024-04-24 14:59:57 +03:00
Piotr Skalski 80e5413402 Merge pull request #1128 from roboflow/feat/dev/keypoints-annotated
initial key point support and annotators
2024-04-24 12:25:58 +02:00
Linas Kondrackis 741309fd09 Remove Skeleton from __init__, small renames, consts 2024-04-24 13:13:10 +03:00
pre-commit-ci[bot] 08d7a6b4cd fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-24 09:53:36 +00:00
Linas Kondrackis d1c103ee16 Best skeleton cache ever, obviously 2024-04-24 12:50:19 +03:00
pre-commit-ci[bot] 0f6ad236eb fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-24 09:45:47 +00:00
Linas Kondrackis 1c27bf7fea EdgeAnnotator, warn and not crash when None 2024-04-24 12:44:29 +03:00
pre-commit-ci[bot] 0749efed8f fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-24 06:52:19 +00:00
Linas Kondrackis d8681b8b4f remove xy_all, turn to for xy in keypoints.xy 2024-04-24 09:51:40 +03:00
pre-commit-ci[bot] 9ad35bcfb9 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-23 22:44:02 +00:00
SkalskiP 102c5adc38 test simplified skeleton API 2024-04-24 00:43:46 +02:00
SkalskiP a2dbbcce63 Merge remote-tracking branch 'origin/feat/dev/keypoints-annotated' into feat/dev/keypoints-annotated 2024-04-24 00:24:29 +02:00
SkalskiP 397b2249a7 fix typo 2024-04-24 00:24:21 +02:00
pre-commit-ci[bot] e2865ecda7 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-23 22:21:49 +00:00
SkalskiP 0ff1cfac07 Merge remote-tracking branch 'origin/feat/dev/keypoints-annotated' into feat/dev/keypoints-annotated 2024-04-24 00:21:30 +02:00
SkalskiP 2745c70ae0 docs plugged into mkdocs.yml 2024-04-24 00:21:19 +02:00
pre-commit-ci[bot] e2fabc1cfe fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-23 21:57:30 +00:00
SkalskiP a8d5e05885 Merge remote-tracking branch 'origin/feat/dev/keypoints-annotated' into feat/dev/keypoints-annotated 2024-04-23 23:57:16 +02:00
SkalskiP 9789ff4043 solve CI tests 2024-04-23 23:57:08 +02:00
SkalskiP 0274c45dbc solve CI tests 2024-04-23 23:12:54 +02:00
SkalskiP 6a541845ba Merge branch 'develop' into feat/dev/keypoints-annotated 2024-04-23 23:07:37 +02:00
pre-commit-ci[bot] 409dcbd9da fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-23 20:49:06 +00:00
Linas Kondrackis 07482a347c Keypoints: Multi-person annotators 2024-04-23 20:43:14 +03:00
Linas Kondrackis 7f0ecbbd0a Keypoints: Smart skellies 2024-04-23 20:19:28 +03:00
Linas Kondrackis a00604bfb2 Keypoints: Expose KeyPoints, annotators in __init__ 2024-04-23 19:28:34 +03:00
Linas Kondrackis d079ce92df Keypoints: Separate-out skeleton annotator 2024-04-23 19:26:12 +03:00
Linas Kondrackis a6b563cf4d Add keypoints skeleton, 2x annotators 2024-04-23 17:18:34 +03:00
Onuralp SEZER 7c2aad194a Merge pull request #1124 from roboflow/pre-commit-ci-update-config
chore(pre_commit): ⬆ pre_commit autoupdate
2024-04-23 00:47:00 +03:00
pre-commit-ci[bot] feae6d3f78 chore(pre_commit): ⬆ pre_commit autoupdate
updates:
- [github.com/astral-sh/ruff-pre-commit: v0.3.7 → v0.4.1](https://github.com/astral-sh/ruff-pre-commit/compare/v0.3.7...v0.4.1)
2024-04-22 17:43:51 +00:00
Onuralp SEZER 4ebace283c Merge pull request #1123 from roboflow/dependabot/pip/ruff-0.4.1
⬆️ Bump ruff from 0.4.0 to 0.4.1
2024-04-22 04:03:29 +03:00
dependabot[bot] 98493c2ae1 ⬆️ Bump ruff from 0.4.0 to 0.4.1
Bumps [ruff](https://github.com/astral-sh/ruff) from 0.4.0 to 0.4.1.
- [Release notes](https://github.com/astral-sh/ruff/releases)
- [Changelog](https://github.com/astral-sh/ruff/blob/main/CHANGELOG.md)
- [Commits](https://github.com/astral-sh/ruff/compare/v0.4.0...v0.4.1)

---
updated-dependencies:
- dependency-name: ruff
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-22 00:45:54 +00:00
Onuralp SEZER 8b32815648 Merge pull request #1122 from roboflow/dependabot/pip/ruff-0.4.0
⬆️ Bump ruff from 0.3.7 to 0.4.0
2024-04-19 13:36:40 +03:00
dependabot[bot] a1a66e7078 ⬆️ Bump ruff from 0.3.7 to 0.4.0
Bumps [ruff](https://github.com/astral-sh/ruff) from 0.3.7 to 0.4.0.
- [Release notes](https://github.com/astral-sh/ruff/releases)
- [Changelog](https://github.com/astral-sh/ruff/blob/main/CHANGELOG.md)
- [Commits](https://github.com/astral-sh/ruff/compare/v0.3.7...v0.4.0)

---
updated-dependencies:
- dependency-name: ruff
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-19 00:17:17 +00:00
Onuralp SEZER fd4ef9960a Merge pull request #1119 from roboflow/dependabot/pip/mkdocs-material-9.5.18
⬆️ Bump mkdocs-material from 9.5.17 to 9.5.18
2024-04-18 08:39:53 +03:00
Onuralp SEZER 6c54da2afa Merge pull request #1121 from roboflow/dependabot/pip/notebook-7.1.3
⬆️ Bump notebook from 7.1.2 to 7.1.3
2024-04-18 08:39:31 +03:00
dependabot[bot] 53eb76922d ⬆️ Bump notebook from 7.1.2 to 7.1.3
Bumps [notebook](https://github.com/jupyter/notebook) from 7.1.2 to 7.1.3.
- [Release notes](https://github.com/jupyter/notebook/releases)
- [Changelog](https://github.com/jupyter/notebook/blob/@jupyter-notebook/tree@7.1.3/CHANGELOG.md)
- [Commits](https://github.com/jupyter/notebook/compare/@jupyter-notebook/tree@7.1.2...@jupyter-notebook/tree@7.1.3)

---
updated-dependencies:
- dependency-name: notebook
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-18 00:42:40 +00:00
dependabot[bot] b3f022b15a ⬆️ Bump mkdocs-material from 9.5.17 to 9.5.18
Bumps [mkdocs-material](https://github.com/squidfunk/mkdocs-material) from 9.5.17 to 9.5.18.
- [Release notes](https://github.com/squidfunk/mkdocs-material/releases)
- [Changelog](https://github.com/squidfunk/mkdocs-material/blob/master/CHANGELOG)
- [Commits](https://github.com/squidfunk/mkdocs-material/compare/9.5.17...9.5.18)

---
updated-dependencies:
- dependency-name: mkdocs-material
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-17 00:29:27 +00:00
Onuralp SEZER 91e03ce903 Merge pull request #1118 from roboflow/pre-commit-ci-update-config
chore(pre_commit): ⬆ pre_commit autoupdate
2024-04-15 23:25:35 +03:00
pre-commit-ci[bot] 2af86e56f0 chore(pre_commit): ⬆ pre_commit autoupdate
updates:
- [github.com/astral-sh/ruff-pre-commit: v0.3.5 → v0.3.7](https://github.com/astral-sh/ruff-pre-commit/compare/v0.3.5...v0.3.7)
2024-04-15 17:52:01 +00:00
Onuralp SEZER af0ece26d7 Merge pull request #1117 from roboflow/dependabot/pip/ruff-0.3.7
⬆️ Bump ruff from 0.3.6 to 0.3.7
2024-04-15 14:15:29 +03:00
dependabot[bot] 77d3276ad6 ⬆️ Bump ruff from 0.3.6 to 0.3.7
Bumps [ruff](https://github.com/astral-sh/ruff) from 0.3.6 to 0.3.7.
- [Release notes](https://github.com/astral-sh/ruff/releases)
- [Changelog](https://github.com/astral-sh/ruff/blob/main/CHANGELOG.md)
- [Commits](https://github.com/astral-sh/ruff/compare/v0.3.6...v0.3.7)

---
updated-dependencies:
- dependency-name: ruff
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-15 01:13:38 +00:00
Piotr Skalski c8d2a54ed8 Merge pull request #1078 from roboflow/docs/ci/release-docs
ci: 👷 supervision documentation 📚 release CI added
2024-04-12 17:49:26 +02:00
Onuralp SEZER 9d9acd7e58 Merge pull request #1112 from roboflow/dependabot/pip/idna-3.7
⬆️ Bump idna from 3.6 to 3.7
2024-04-12 17:26:41 +03:00
Piotr Skalski f9ed80f91b Merge pull request #1109 from jeslinpjames/polygonzone-update
Dropped frame_resolution_wh from [PolygonZone]
2024-04-12 16:23:56 +02:00
SkalskiP dfd9fc8e6d fix too long string 2024-04-12 16:17:29 +02:00
SkalskiP 2c62f0b26d drop frame_resolution_wh from docs 2024-04-12 16:15:10 +02:00
SkalskiP 0ad3796571 bug fix 2024-04-12 16:13:09 +02:00
Onuralp SEZER da236aa565 Merge pull request #1110 from roboflow/dependabot/pip/ruff-0.3.6
⬆️ Bump ruff from 0.3.5 to 0.3.6
2024-04-12 16:19:30 +03:00
Jeslin P James 0800b0569f Merge branch 'polygonzone-update' of github.com:jeslinpjames/supervision into polygonzone-update 2024-04-12 16:46:02 +05:30
Jeslin P James 510df54572 Updated order of parameters in PolygonZone __init__() 2024-04-12 16:16:48 +05:30
dependabot[bot] 89d84d1f74 ⬆️ Bump idna from 3.6 to 3.7
Bumps [idna](https://github.com/kjd/idna) from 3.6 to 3.7.
- [Release notes](https://github.com/kjd/idna/releases)
- [Changelog](https://github.com/kjd/idna/blob/master/HISTORY.rst)
- [Commits](https://github.com/kjd/idna/compare/v3.6...v3.7)

---
updated-dependencies:
- dependency-name: idna
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-12 04:14:49 +00:00
dependabot[bot] 7126adc74a ⬆️ Bump ruff from 0.3.5 to 0.3.6
Bumps [ruff](https://github.com/astral-sh/ruff) from 0.3.5 to 0.3.6.
- [Release notes](https://github.com/astral-sh/ruff/releases)
- [Changelog](https://github.com/astral-sh/ruff/blob/main/CHANGELOG.md)
- [Commits](https://github.com/astral-sh/ruff/compare/v0.3.5...v0.3.6)

---
updated-dependencies:
- dependency-name: ruff
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-12 00:13:05 +00:00
pre-commit-ci[bot] 743e42080b fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-11 13:57:50 +00:00
Jeslin P James b64c61c388 formated code 2024-04-11 19:04:06 +05:30
Jeslin P James 28baf18cb6 updated PolygonZone Attributes docs 2024-04-11 18:59:48 +05:30
Jeslin P James b7607c6f15 Updated PolyZone class to compute frame_resolution_wh based on polygon coordinates 2024-04-11 18:57:30 +05:30
Piotr Skalski d3dbe7c597 Update README.md 2024-04-11 14:54:22 +02:00
Piotr Skalski 9284bfdcd9 Update README.md 2024-04-11 14:44:50 +02:00
Piotr Skalski 263421d145 Update README.md 2024-04-11 14:40:43 +02:00
Piotr Skalski ed225187b2 Update README.md 2024-04-11 14:09:02 +02:00
Onuralp SEZER 855f9191c5 Merge pull request #1107 from LinasKo/feature/new-video-beach
Add beach drone footage asset
2024-04-10 09:46:25 +03:00
Linas Kondrackis 98b64f5e7d Add beach drone footage asset 2024-04-10 09:34:44 +03:00
Onuralp SEZER 048d1a8b98 Merge pull request #1106 from roboflow/dependabot/pip/mkdocs-jupyter-0.24.7
⬆️ Bump mkdocs-jupyter from 0.24.3 to 0.24.7
2024-04-10 03:35:14 +03:00
dependabot[bot] 2fd5452181 ⬆️ Bump mkdocs-jupyter from 0.24.3 to 0.24.7
Bumps [mkdocs-jupyter](https://github.com/danielfrg/mkdocs-jupyter) from 0.24.3 to 0.24.7.
- [Changelog](https://github.com/danielfrg/mkdocs-jupyter/blob/main/CHANGELOG.md)
- [Commits](https://github.com/danielfrg/mkdocs-jupyter/compare/0.24.3...0.24.7)

---
updated-dependencies:
- dependency-name: mkdocs-jupyter
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-10 00:14:47 +00:00
Piotr Skalski 10843c9989 Merge pull request #1104 from roboflow/letterbox_pr_docs_improvements
docs improvements related to #1028 PR
2024-04-09 23:19:44 +02:00
SkalskiP eb1c7716ef make ruff happy 2024-04-09 23:18:02 +02:00
pre-commit-ci[bot] c27d9eaf22 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-09 21:16:21 +00:00
SkalskiP 5eb43a25c9 Merge remote-tracking branch 'origin/letterbox_pr_docs_improvements' into letterbox_pr_docs_improvements 2024-04-09 23:15:57 +02:00
SkalskiP e0d5f00ae3 initial version of How to Save Detections guide done 2024-04-09 23:15:49 +02:00
pre-commit-ci[bot] 99fbd4b601 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-09 20:45:09 +00:00
SkalskiP d155592f45 Merge remote-tracking branch 'origin/letterbox_pr_docs_improvements' into letterbox_pr_docs_improvements 2024-04-09 22:44:54 +02:00
SkalskiP d929d6f58b How to Save Detections guide update 2024-04-09 22:44:10 +02:00
pre-commit-ci[bot] 6248fa7d17 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-09 20:08:13 +00:00
SkalskiP 7ad50cc7c2 Merge remote-tracking branch 'origin/letterbox_pr_docs_improvements' into letterbox_pr_docs_improvements 2024-04-09 22:07:58 +02:00
SkalskiP c30e377eb5 more docs improvements 2024-04-09 22:07:12 +02:00
pre-commit-ci[bot] f872fddaff fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-09 19:24:04 +00:00
SkalskiP 079e62fb0c rename place_image to overlay image 2024-04-09 21:23:23 +02:00
SkalskiP 774ac2ed4f update letterbox_image docs 2024-04-09 17:59:19 +02:00
pre-commit-ci[bot] a7dccfcc0d fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-09 15:48:33 +00:00
Onuralp SEZER 15a4555b6a Merge pull request #1102 from roboflow/pre-commit-ci-update-config
chore(pre_commit): ⬆ pre_commit autoupdate
2024-04-09 18:48:21 +03:00
SkalskiP 233d25d4c5 fix resize_image tests after rename 2024-04-09 17:48:13 +02:00
pre-commit-ci[bot] ad94689362 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-09 14:46:48 +00:00
SkalskiP 94e06ab0d6 scale_image, resize_image changes 2024-04-09 16:46:05 +02:00
Onuralp SEZER b63379749e fix(keypoint): 🚀 getitem and setitem funcs added
Signed-off-by: Onuralp SEZER <thunderbirdtr@gmail.com>
2024-04-09 17:43:40 +03:00
Onuralp SEZER 5d43e1380d feat(test): 🚀 mock keypoints added
Signed-off-by: Onuralp SEZER <thunderbirdtr@gmail.com>
2024-04-09 17:42:31 +03:00
Onuralp SEZER 7d0cf8a723 feat: 🚀 initial sv.Keypoints features added
Signed-off-by: Onuralp SEZER <thunderbirdtr@gmail.com>
2024-04-09 15:51:16 +03:00
pre-commit-ci[bot] f2e6d882fb fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-09 12:50:50 +00:00
SkalskiP 2115c9a152 crop_image improvements 2024-04-09 14:50:32 +02:00
pre-commit-ci[bot] 5b1ee8f870 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-09 12:31:32 +00:00
SkalskiP 574c61b6b0 initial commit 2024-04-09 14:28:40 +02:00
pre-commit-ci[bot] 6b682f00ae chore(pre_commit): ⬆ pre_commit autoupdate
updates:
- [github.com/pre-commit/pre-commit-hooks: v4.5.0 → v4.6.0](https://github.com/pre-commit/pre-commit-hooks/compare/v4.5.0...v4.6.0)
- [github.com/astral-sh/ruff-pre-commit: v0.3.4 → v0.3.5](https://github.com/astral-sh/ruff-pre-commit/compare/v0.3.4...v0.3.5)
2024-04-08 17:55:20 +00:00
Onuralp SEZER 4729e20a94 Merge pull request #1099 from roboflow/dependabot/pip/mkdocstrings-0.24.3
⬆️ Bump mkdocstrings from 0.24.2 to 0.24.3
2024-04-08 04:16:40 +03:00
dependabot[bot] b5ccc99537 ⬆️ Bump mkdocstrings from 0.24.2 to 0.24.3
Bumps [mkdocstrings](https://github.com/mkdocstrings/mkdocstrings) from 0.24.2 to 0.24.3.
- [Release notes](https://github.com/mkdocstrings/mkdocstrings/releases)
- [Changelog](https://github.com/mkdocstrings/mkdocstrings/blob/main/CHANGELOG.md)
- [Commits](https://github.com/mkdocstrings/mkdocstrings/compare/0.24.2...0.24.3)

---
updated-dependencies:
- dependency-name: mkdocstrings
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-08 01:11:06 +00:00
Onuralp SEZER 922ebb237a Merge pull request #1097 from pirnerjonas/fix/formatting-in-docs
fix: formatting in notebook.md
2024-04-07 09:54:33 +03:00
Jonas Pirner 0ae2c1206f fix: formatting in notebook.md 2024-04-06 21:40:19 +02:00
Piotr Skalski 372e703a7a Merge pull request #1028 from roboflow/feature/add_tiles_generator
Add util to create image tiles
2024-04-05 18:37:19 +02:00
pre-commit-ci[bot] 0a919db9fd fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-05 16:02:57 +00:00
SkalskiP 473f140133 create_batches and fill docs added 2024-04-05 18:01:17 +02:00
pre-commit-ci[bot] e93224570f fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-05 15:51:35 +00:00
SkalskiP 5e9c3fdfa5 refactor tests to use @pytest.mark.parametrize 2024-04-05 17:51:08 +02:00
Paweł Pęczek b76f864f70 Rename decorators to convert images to acceptable format 2024-04-05 17:45:49 +02:00
SkalskiP c9095881ae docs updates 2024-04-05 17:33:52 +02:00
Piotr Skalski 299c933c4c Merge pull request #1093 from macc-n/ultralytics-results
Fixed obb key check in ultralytics_results
2024-04-05 13:38:06 +02:00
Piotr Skalski 9ae69c71d9 Merge pull request #1084 from sharingan000/geometry-utils-update-polygon-center-getter
Geometry utils update polygon center getter
2024-04-05 13:07:44 +02:00
Piotr Skalski a60884d94f Merge pull request #1046 from jeslinpjames/feature/transformers-support
Enhanced from_transformers to support class name extraction
2024-04-05 12:12:30 +02:00
SkalskiP e2f1d5812e docs improvements 2024-04-05 12:10:10 +02:00
pre-commit-ci[bot] dd7fddb4f5 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-05 09:50:00 +00:00
SkalskiP ee38ba36c4 docs improvements 2024-04-05 11:49:43 +02:00
macc-n 79da48fc49 If conditions merged 2024-04-04 18:45:42 +02:00
pre-commit-ci[bot] 7e21aaaa1a fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-04 16:16:35 +00:00
sharingan000 57335ef986 just comments 2024-04-05 02:14:44 +10:00
sharingan000 c605687f82 Ehe fix :) 2024-04-05 02:06:03 +10:00
sharingan000 6001e4033e Merge remote-tracking branch 'origin/geometry-utils-update-polygon-center-getter' into geometry-utils-update-polygon-center-getter 2024-04-05 02:04:03 +10:00
sharingan000 761fb89241 Fixed test/geometry/test_utils 2024-04-05 02:03:53 +10:00
pre-commit-ci[bot] 5f0082048c fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-04 16:01:22 +00:00
sharingan000 0b86478417 Only solid algorithm geometry/utils 2024-04-05 02:00:54 +10:00
macc-n c8ea42af6d Fixed obb key check in ultralytics_results 2024-04-04 17:32:41 +02:00
sharingan000 40200ddd8d Merge remote-tracking branch 'origin/develop' into geometry-utils-update-polygon-center-getter 2024-04-04 15:01:49 +10:00
pre-commit-ci[bot] 8de73738c7 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-04 04:59:31 +00:00
sharingan000 0cf31d7e55 Merge remote-tracking branch 'origin/geometry-utils-update-polygon-center-getter' into geometry-utils-update-polygon-center-getter
# Conflicts:
#	supervision/geometry/utils.py
2024-04-04 14:58:36 +10:00
sharingan000 eb3317694e Include all three algorithms 2024-04-04 14:57:57 +10:00
pre-commit-ci[bot] 960e2529b1 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-03 10:44:27 +00:00
sharingan000 b7d18681b1 Merge remote-tracking branch 'origin/geometry-utils-update-polygon-center-getter' into geometry-utils-update-polygon-center-getter 2024-04-03 20:42:48 +10:00
sharingan000 cd81c1cef4 Updated algorithm 2024-04-03 20:40:54 +10:00
Onuralp SEZER fe1e0d9bec Merge pull request #1088 from roboflow/dependabot/pip/mkdocs-material-9.5.17
⬆️ Bump mkdocs-material from 9.5.16 to 9.5.17
2024-04-03 03:44:53 +03:00
Onuralp SEZER 275c7c6cc3 Merge pull request #1087 from roboflow/dependabot/pip/mkdocstrings-0.24.2
⬆️ Bump mkdocstrings from 0.24.1 to 0.24.2
2024-04-03 03:44:39 +03:00
dependabot[bot] 79c731b431 ⬆️ Bump mkdocs-material from 9.5.16 to 9.5.17
Bumps [mkdocs-material](https://github.com/squidfunk/mkdocs-material) from 9.5.16 to 9.5.17.
- [Release notes](https://github.com/squidfunk/mkdocs-material/releases)
- [Changelog](https://github.com/squidfunk/mkdocs-material/blob/master/CHANGELOG)
- [Commits](https://github.com/squidfunk/mkdocs-material/compare/9.5.16...9.5.17)

---
updated-dependencies:
- dependency-name: mkdocs-material
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-03 00:35:04 +00:00
dependabot[bot] f15a6224ff ⬆️ Bump mkdocstrings from 0.24.1 to 0.24.2
Bumps [mkdocstrings](https://github.com/mkdocstrings/mkdocstrings) from 0.24.1 to 0.24.2.
- [Release notes](https://github.com/mkdocstrings/mkdocstrings/releases)
- [Changelog](https://github.com/mkdocstrings/mkdocstrings/blob/main/CHANGELOG.md)
- [Commits](https://github.com/mkdocstrings/mkdocstrings/compare/0.24.1...0.24.2)

---
updated-dependencies:
- dependency-name: mkdocstrings
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-03 00:30:06 +00:00
jeslinpjames b6b72eddce add defensive checks to from_transformers 2024-04-02 18:53:42 +05:30
jeslinpjames b02e8664a1 mark id2label as Optional in from_transformers docs 2024-04-02 18:39:24 +05:30
jeslinpjames c7a0f62dea Merge branch 'develop' of github.com:jeslinpjames/supervision into feature/transformers-support 2024-04-02 18:20:53 +05:30
pre-commit-ci[bot] dcad812c5c fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-02 07:15:15 +00:00
sharingan000 7ded0bd493 Change the method of finding polygon center and create test for new function 2024-04-02 16:55:03 +10:00
sharingan000 a38ae3f840 Change the method of finding polygon center and create test for new function 2024-04-02 16:54:34 +10:00
Onuralp SEZER 175dd7d0f5 Merge pull request #1082 from roboflow/dependabot/pip/ruff-0.3.5
⬆️ Bump ruff from 0.3.4 to 0.3.5
2024-04-02 04:06:40 +03:00
Onuralp SEZER 173a5d63a2 Merge pull request #1083 from roboflow/dependabot/pip/pillow-10.3.0
⬆️ Bump pillow from 10.2.0 to 10.3.0
2024-04-02 04:06:06 +03:00
dependabot[bot] f21597446b ⬆️ Bump pillow from 10.2.0 to 10.3.0
Bumps [pillow](https://github.com/python-pillow/Pillow) from 10.2.0 to 10.3.0.
- [Release notes](https://github.com/python-pillow/Pillow/releases)
- [Changelog](https://github.com/python-pillow/Pillow/blob/main/CHANGES.rst)
- [Commits](https://github.com/python-pillow/Pillow/compare/10.2.0...10.3.0)

---
updated-dependencies:
- dependency-name: pillow
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-02 00:47:42 +00:00
dependabot[bot] da5dfef2ed ⬆️ Bump ruff from 0.3.4 to 0.3.5
Bumps [ruff](https://github.com/astral-sh/ruff) from 0.3.4 to 0.3.5.
- [Release notes](https://github.com/astral-sh/ruff/releases)
- [Changelog](https://github.com/astral-sh/ruff/blob/main/CHANGELOG.md)
- [Commits](https://github.com/astral-sh/ruff/compare/v0.3.4...v0.3.5)

---
updated-dependencies:
- dependency-name: ruff
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-02 00:45:56 +00:00
Onuralp SEZER 03803a7d7e Merge pull request #1079 from roboflow/dependabot/pip/mkdocs-material-9.5.16
⬆️ Bump mkdocs-material from 9.5.15 to 9.5.16
2024-04-01 04:13:13 +03:00
dependabot[bot] cbc5aa49f5 ⬆️ Bump mkdocs-material from 9.5.15 to 9.5.16
Bumps [mkdocs-material](https://github.com/squidfunk/mkdocs-material) from 9.5.15 to 9.5.16.
- [Release notes](https://github.com/squidfunk/mkdocs-material/releases)
- [Changelog](https://github.com/squidfunk/mkdocs-material/blob/master/CHANGELOG)
- [Commits](https://github.com/squidfunk/mkdocs-material/compare/9.5.15...9.5.16)

---
updated-dependencies:
- dependency-name: mkdocs-material
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-01 00:50:45 +00:00
Onuralp SEZER 8fc5413394 ci: 👷 supervision documentation 📚 release CI added
Signed-off-by: Onuralp SEZER <thunderbirdtr@gmail.com>
2024-04-01 02:37:57 +03:00
Onuralp SEZER b5250105e0 Merge pull request #1071 from roboflow/dependabot/pip/build-1.2.1
⬆️ Bump build from 1.2.0 to 1.2.1
2024-03-29 16:34:00 +03:00
dependabot[bot] 90ad1c2c9a ⬆️ Bump build from 1.2.0 to 1.2.1
Bumps [build](https://github.com/pypa/build) from 1.2.0 to 1.2.1.
- [Release notes](https://github.com/pypa/build/releases)
- [Changelog](https://github.com/pypa/build/blob/main/CHANGELOG.rst)
- [Commits](https://github.com/pypa/build/compare/1.2.0...1.2.1)

---
updated-dependencies:
- dependency-name: build
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-29 00:38:59 +00:00
jeslinpjames 7dedc452b7 Added missing data field 2024-03-29 01:44:37 +05:30
jeslinpjames 767f9a7148 formatted code 2024-03-29 01:14:10 +05:30
jeslinpjames e6a1d58500 Update documentation for from_transformers function 2024-03-29 01:11:17 +05:30
jeslinpjames a8988d1d4d Enhance from_transformers to support class name extraction for Transformers 2024-03-29 01:05:49 +05:30
jeslinpjames 42a4ed4166 Merge branch 'develop' of github.com:jeslinpjames/supervision into feature/transformers-support 2024-03-29 00:47:29 +05:30
Piotr Skalski f4f9b3d53a Merge pull request #1068 from roboflow/docs/anaconda-install
docs: 📚 conda and mamba installation methods added
2024-03-28 18:55:47 +01:00
pre-commit-ci[bot] 719af725b1 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-03-28 17:53:57 +00:00
SkalskiP e88ab7c125 small update 2024-03-28 18:53:39 +01:00
Piotr Skalski 77e38ba93b Merge pull request #1069 from roboflow/from_transformers_improvements
`from_transformers` improvements
2024-03-28 17:17:18 +01:00
SkalskiP 68e1bae6de Merge remote-tracking branch 'origin/from_transformers_improvements' into from_transformers_improvements 2024-03-28 16:34:25 +01:00
SkalskiP afc31e42a5 few more improvements 2024-03-28 16:34:05 +01:00
pre-commit-ci[bot] 0c7c746f15 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-03-28 15:10:30 +00:00
SkalskiP 4ad78becb6 initial comment 2024-03-28 16:08:05 +01:00
Onuralp SEZER f9fd88fb01 docs: 📚 conda and mamba installation methods added
Signed-off-by: Onuralp SEZER <thunderbirdtr@gmail.com>
2024-03-28 18:00:43 +03:00
pre-commit-ci[bot] c56c446eb6 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-03-26 02:06:09 +00:00
jeslinpjames 8a06de47e9 made id2label param optional and handle class names 2024-03-26 07:35:45 +05:30
jeslinpjames a51267a4fa Merge branch 'develop' of github.com:jeslinpjames/supervision into feature/transformers-support 2024-03-26 07:33:30 +05:30
pre-commit-ci[bot] 8694f0023d fix(pre_commit): 🎨 auto format pre-commit hooks 2024-03-25 19:24:23 +00:00
jeslinpjames b2b417af5b Enhanced from_transformers to support class name extraction 2024-03-26 00:39:11 +05:30
Paweł Pęczek 0aacfa47d3 Add new utils to library interface 2024-03-25 19:47:45 +01:00
Paweł Pęczek de8222203c Add tests for tiles creation 2024-03-25 19:44:46 +01:00
Paweł Pęczek 4adb2339a4 Add tests and docstrings for utils 2024-03-25 16:02:00 +01:00
Paweł Pęczek 444853054f Add docstrings for image module 2024-03-25 15:22:52 +01:00
Paweł Pęczek 4bb711dcea Add draft of changes to support adding titles 2024-03-25 15:09:21 +01:00
Paweł Pęczek 7eba338243 Add first draft of implementation for function creating image tiles 2024-03-20 23:08:39 +01:00
73 changed files with 3245 additions and 635 deletions
@@ -0,0 +1,55 @@
name: Supervision Release Documentation Workflow 📚
on:
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.event_name == 'push' && github.ref}}
cancel-in-progress: true
permissions:
contents: write
pages: write
pull-requests: write
jobs:
doc-build-deploy:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.10"]
steps:
- name: 🛎️ Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
ref: ${{ github.head_ref }}
- name: 🐍 Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.10'
- name: 📦 Install mkdocs-material
run: pip install "mkdocs-material"
- name: 📦 Install mkdocstrings[python]
run: pip install "mkdocstrings[python]"
- name: 📦 Install mkdocs-material[imaging]
run: pip install "mkdocs-material[imaging]"
- name: 📦 Install mike
run: pip install "mike"
- name: 📦 Install mkdocs-git-revision-date-localized-plugin
run: pip install "mkdocs-git-revision-date-localized-plugin"
- name: 📦 Install JupyterLab
run: pip install jupyterlab
- name: 📦 Install mkdocs-jupyter
run: pip install mkdocs-jupyter
- name: 📦 Install mkdocs-git-committers-plugin-2
run: pip install mkdocs-git-committers-plugin-2
- name: ⚙️ Configure git for github-actions 👷
run: |
git config --global user.name "github-actions[bot]"
git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com"
- name: 🚀 Deploy MkDoc-Material 📚
run: |
latest_tag=$(git describe --tags `git rev-list --tags --max-count=1`)
MKDOCS_GIT_COMMITTERS_APIKEY=${{ secrets.GITHUB_TOKEN }} mike deploy --push --update-aliases $latest_tag latest
+2 -3
View File
@@ -7,7 +7,7 @@ ci:
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
rev: v4.6.0
hooks:
- id: end-of-file-fixer
- id: trailing-whitespace
@@ -27,7 +27,6 @@ repos:
- id: mixed-line-ending
- repo: https://github.com/PyCQA/bandit
rev: '1.7.8'
hooks:
@@ -46,7 +45,7 @@ repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.3.4
rev: v0.4.1
hooks:
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
+21 -18
View File
@@ -18,10 +18,10 @@
[![downloads](https://img.shields.io/pypi/dm/supervision)](https://pypistats.org/packages/supervision)
[![license](https://img.shields.io/pypi/l/supervision)](https://github.com/roboflow/supervision/blob/main/LICENSE.md)
[![python-version](https://img.shields.io/pypi/pyversions/supervision)](https://badge.fury.io/py/supervision)
[![Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/roboflow/supervision/blob/main/demo.ipynb)
[![Gradio](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue)](https://huggingface.co/spaces/Roboflow/Annotators)
[![Discord](https://img.shields.io/discord/1159501506232451173)](https://discord.gg/GbfgXGJ8Bk)
[![Built with Material for MkDocs](https://img.shields.io/badge/Material_for_MkDocs-526CFE?logo=MaterialForMkDocs&logoColor=white)](https://squidfunk.github.io/mkdocs-material/)
[![colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/roboflow/supervision/blob/main/demo.ipynb)
[![gradio](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue)](https://huggingface.co/spaces/Roboflow/Annotators)
[![discord](https://img.shields.io/discord/1159501506232451173)](https://discord.gg/GbfgXGJ8Bk)
[![built-with-material-for-mkdocs](https://img.shields.io/badge/Material_for_MkDocs-526CFE?logo=MaterialForMkDocs&logoColor=white)](https://squidfunk.github.io/mkdocs-material/)
</div>
## 👋 hello
@@ -39,7 +39,7 @@ Pip install the supervision package in a
pip install supervision
```
Read more about desktop, headless, and local installation in our [guide](https://roboflow.github.io/supervision/).
Read more about conda, mamba, and installing from source in our [guide](https://roboflow.github.io/supervision/).
## 🔥 quickstart
@@ -71,16 +71,15 @@ len(detections)
```python
import cv2
import supervision as sv
from inference.models.utils import get_roboflow_model
from inference import get_model
image = cv2.imread(...)
model = get_roboflow_model(model_id="yolov8s-640", api_key=<ROBOFLOW API KEY>)
model = get_model(model_id="yolov8s-640", api_key=<ROBOFLOW API KEY>)
result = model.infer(image)[0]
detections = sv.Detections.from_inference(result)
len(detections)
# 5
# 5
```
</details>
@@ -217,19 +216,23 @@ len(dataset)
## 🎬 tutorials
<p align="left">
<a href="https://youtu.be/uWP6UjDeZvY" title="Speed Estimation & Vehicle Tracking | Computer Vision | Open Source"><img src="https://github.com/SkalskiP/SkalskiP/assets/26109316/61a444c8-b135-48ce-b979-2a5ab47c5a91" alt="Speed Estimation & Vehicle Tracking | Computer Vision | Open Source" width="300px" align="left" /></a>
<a href="https://youtu.be/uWP6UjDeZvY" title="Speed Estimation & Vehicle Tracking | Computer Vision | Open Source"><strong>Speed Estimation & Vehicle Tracking | Computer Vision | Open Source</strong></a>
<div><strong>Created: 11 Jan 2024</strong> | <strong>Updated: 11 Jan 2024</strong></div>
<br/> Learn how to track and estimate the speed of vehicles using YOLO, ByteTrack, and Roboflow Inference. This comprehensive tutorial covers object detection, multi-object tracking, filtering detections, perspective transformation, speed estimation, visualization improvements, and more.</p>
Want to learn how to use Supervision? Explore our [how-to guides](https://supervision.roboflow.com/develop/how_to/detect_and_annotate/), [end-to-end examples](https://github.com/roboflow/supervision/tree/develop/examples), and [cookbooks](https://supervision.roboflow.com/develop/cookbooks/)!
<br/>
<p align="left">
<a href="https://youtu.be/4Q3ut7vqD5o" title="Traffic Analysis with YOLOv8 and ByteTrack - Vehicle Detection and Tracking"><img src="https://github.com/roboflow/supervision/assets/26109316/54afdf1c-218c-4451-8f12-627fb85f1682" alt="Traffic Analysis with YOLOv8 and ByteTrack - Vehicle Detection and Tracking" width="300px" align="left" /></a>
<a href="https://youtu.be/4Q3ut7vqD5o" title="Traffic Analysis with YOLOv8 and ByteTrack - Vehicle Detection and Tracking"><strong>Traffic Analysis with YOLOv8 and ByteTrack - Vehicle Detection and Tracking</strong></a>
<div><strong>Created: 6 Sep 2023</strong> | <strong>Updated: 6 Sep 2023</strong></div>
<br/> In this video, we explore real-time traffic analysis using YOLOv8 and ByteTrack to detect and track vehicles on aerial images. Harnessing the power of Python and Supervision, we delve deep into assigning cars to specific entry zones and understanding their direction of movement. By visualizing their paths, we gain insights into traffic flow across bustling roundabouts... </p>
<a href="https://youtu.be/hAWpsIuem10" title="Dwell Time Analysis with Computer Vision | Real-Time Stream Processing"><img src="https://github.com/SkalskiP/SkalskiP/assets/26109316/a742823d-c158-407d-b30f-063a5d11b4e1" alt="Dwell Time Analysis with Computer Vision | Real-Time Stream Processing" width="300px" align="left" /></a>
<a href="https://youtu.be/hAWpsIuem10" title="Dwell Time Analysis with Computer Vision | Real-Time Stream Processing"><strong>Dwell Time Analysis with Computer Vision | Real-Time Stream Processing</strong></a>
<div><strong>Created: 5 Apr 2024</strong></div>
<br/>Learn how to use computer vision to analyze wait times and optimize processes. This tutorial covers object detection, tracking, and calculating time spent in designated zones. Use these techniques to improve customer experience in retail, traffic management, or other scenarios.</p>
<br/>
<p align="left">
<a href="https://youtu.be/uWP6UjDeZvY" title="Speed Estimation & Vehicle Tracking | Computer Vision | Open Source"><img src="https://github.com/SkalskiP/SkalskiP/assets/26109316/61a444c8-b135-48ce-b979-2a5ab47c5a91" alt="Speed Estimation & Vehicle Tracking | Computer Vision | Open Source" width="300px" align="left" /></a>
<a href="https://youtu.be/uWP6UjDeZvY" title="Speed Estimation & Vehicle Tracking | Computer Vision | Open Source"><strong>Speed Estimation & Vehicle Tracking | Computer Vision | Open Source</strong></a>
<div><strong>Created: 11 Jan 2024</strong></div>
<br/>Learn how to track and estimate the speed of vehicles using YOLO, ByteTrack, and Roboflow Inference. This comprehensive tutorial covers object detection, multi-object tracking, filtering detections, perspective transformation, speed estimation, visualization improvements, and more.</p>
## 💜 built with supervision
+2 -2
View File
@@ -19,13 +19,13 @@ as an extra within the Supervision package.
```
<div class="md-typeset">
<h2>download_assets</h2>
<h2><a href="#supervision.assets.downloader.download_assets.download_assets">download_assets</a></h2>
</div>
:::supervision.assets.downloader.download_assets
<div class="md-typeset">
<h2>VideoAssets</h2>
<h2><a href="#supervision.assets.downloader.download_assets.VideoAssets">VideoAssets</a></h2>
</div>
:::supervision.assets.list.VideoAssets
+65
View File
@@ -1,3 +1,68 @@
### 0.20.0 <small>April 24, 2024</small>
- Added [#1128](https://github.com/roboflow/supervision/pull/1128): [`sv.KeyPoints`](/0.20.0/keypoint/core/#supervision.keypoint.core.KeyPoints) to provide initial support for pose estimation and broader keypoint detection models.
- Added [#1128](https://github.com/roboflow/supervision/pull/1128): [`sv.EdgeAnnotator`](/0.20.0/keypoint/annotators/#supervision.keypoint.annotators.EdgeAnnotator) and [`sv.VertexAnnotator`](/0.20.0/keypoint/annotators/#supervision.keypoint.annotators.VertexAnnotator) to enable rendering of results from keypoint detection models.
```python
import cv2
import supervision as sv
from ultralytics import YOLO
image = cv2.imread(<SOURCE_IMAGE_PATH>)
model = YOLO('yolov8l-pose')
result = model(image, verbose=False)[0]
keypoints = sv.KeyPoints.from_ultralytics(result)
edge_annotators = sv.EdgeAnnotator(color=sv.Color.GREEN, thickness=5)
annotated_image = edge_annotators.annotate(image.copy(), keypoints)
```
- Changed [#1037](https://github.com/roboflow/supervision/pull/1037): [`sv.LabelAnnotator`](/0.20.0/annotators/#supervision.annotators.core.LabelAnnotator) by adding an additional `corner_radius` argument that allows for rounding the corners of the bounding box.
- Changed [#1109](https://github.com/roboflow/supervision/pull/1109): [`sv.PolygonZone`](/0.20.0/detection/tools/polygon_zone/#supervision.detection.tools.polygon_zone.PolygonZone) such that the `frame_resolution_wh` argument is no longer required to initialize `sv.PolygonZone`.
!!! failure "Deprecated"
The `frame_resolution_wh` parameter in `sv.PolygonZone` is deprecated and will be removed in `supervision-0.24.0`.
- Changed [#1084](https://github.com/roboflow/supervision/pull/1084): [`sv.get_polygon_center`](/0.20.0/utils/geometry/#supervision.geometry.core.utils.get_polygon_center) to calculate a more accurate polygon centroid.
- Changed [#1069](https://github.com/roboflow/supervision/pull/1069): [`sv.Detections.from_transformers`](/0.20.0/detection/core/#supervision.detection.core.Detections.from_transformers) by adding support for Transformers segmentation models and extract class names values.
```python
import torch
import supervision as sv
from PIL import Image
from transformers import DetrImageProcessor, DetrForSegmentation
processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50-panoptic")
model = DetrForSegmentation.from_pretrained("facebook/detr-resnet-50-panoptic")
image = Image.open(<SOURCE_IMAGE_PATH>)
inputs = processor(images=image, return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
width, height = image.size
target_size = torch.tensor([[height, width]])
results = processor.post_process_segmentation(
outputs=outputs, target_sizes=target_size)[0]
detections = sv.Detections.from_transformers(results, id2label=model.config.id2label)
mask_annotator = sv.MaskAnnotator()
label_annotator = sv.LabelAnnotator(text_position=sv.Position.CENTER)
annotated_image = mask_annotator.annotate(
scene=image, detections=detections)
annotated_image = label_annotator.annotate(
scene=annotated_image, detections=detections)
```
- Fixed [#787](https://github.com/roboflow/supervision/pull/787): [`sv.ByteTrack.update_with_detections`](/0.20.0/trackers/#supervision.tracker.byte_tracker.core.ByteTrack.update_with_detections) which was removing segmentation masks while tracking. Now, `ByteTrack` can be used alongside segmentation models.
### 0.19.0 <small>March 15, 2024</small>
- Added [#818](https://github.com/roboflow/supervision/pull/818): [`sv.CSVSink`](/0.19.0/detection/tools/save_detections/#supervision.detection.tools.csv_sink.CSVSink) allowing for the straightforward saving of image, video, or stream inference results in a `.csv` file.
+2 -1
View File
@@ -12,7 +12,8 @@ These features are phased out due to better alternatives or potential issues in
- The method `Color.green()` is deprecated and will be removed in `supervision-0.22.0`. Use the constant `Color.GREEN` instead.
- The method `Color.blue()` is deprecated and will be removed in `supervision-0.22.0`. Use the constant `Color.BLUE` instead.
- The method [`ColorPalette.default()`](draw/color.md/#supervision.draw.color.ColorPalette.default) is deprecated and will be removed in `supervision-0.22.0`. Use the constant [`ColorPalette.DEFAULT`](draw/color.md/#supervision.draw.color.ColorPalette.DEFAULT) instead.
- `BoxAnnotator` is deprecated and will be removed in `supervision-0.22.0`. Use [`BoundingBoxAnnotator`](annotators.md/#supervision.annotators.core.BoundingBoxAnnotator) and [`LabelAnnotator`](annotators.md/#supervision.annotators.core.LabelAnnotator) instead.
- `BoxAnnotator` is deprecated and will be removed in `supervision-0.22.0`. Use [`BoundingBoxAnnotator`](detection/annotators.md/#supervision.annotators.core.BoundingBoxAnnotator) and [`LabelAnnotator`](detection/annotators.md/#supervision.annotators.core.LabelAnnotator) instead.
- The method [`FPSMonitor.__call__`](utils/video.md/#supervision.utils.video.FPSMonitor.__call__) is deprecated and will be removed in `supervision-0.22.0`. Use the attribute [`FPSMonitor.fps`](utils/video.md/#supervision.utils.video.FPSMonitor.fps) instead.
- The `track_buffer`, `track_thresh`, and `match_thresh` parameters in [`ByterTrack`](trackers.md/#supervision.tracker.byte_tracker.core.ByteTrack) are deprecated and will be removed in `supervision-0.23.0`. Use `lost_track_buffer,` `track_activation_threshold`, and `minimum_matching_threshold` instead.
- The `triggering_position ` parameter in [`sv.PolygonZone`](detection/tools/polygon_zone.md/#supervision.detection.tools.polygon_zone.PolygonZone) is deprecated and will be removed in `supervision-0.23.0`. Use `triggering_anchors ` instead.
- The `frame_resolution_wh ` parameter in [`sv.PolygonZone`](detection/tools/polygon_zone.md/#supervision.detection.tools.polygon_zone.PolygonZone) is deprecated and will be removed in `supervision-0.24.0`.
+17
View File
@@ -0,0 +1,17 @@
---
comments: true
---
# Metrics
<div class="md-typeset">
<h2><a href="#supervision.metrics.detection.ConfusionMatrix">ConfusionMatrix</a></h2>
</div>
:::supervision.metrics.detection.ConfusionMatrix
<div class="md-typeset">
<h2><a href="#supervision.metrics.detection.MeanAveragePrecision">MeanAveragePrecision</a></h2>
</div>
:::supervision.metrics.detection.MeanAveragePrecision
+11 -11
View File
@@ -6,67 +6,67 @@ status: new
# Detection Utils
<div class="md-typeset">
<h2>box_iou_batch</h2>
<h2><a href="#supervision.detection.utils.box_iou_batch">box_iou_batch</a></h2>
</div>
:::supervision.detection.utils.box_iou_batch
<div class="md-typeset">
<h2>mask_iou_batch</h2>
<h2><a href="#supervision.detection.utils.mask_iou_batch">mask_iou_batch</a></h2>
</div>
:::supervision.detection.utils.mask_iou_batch
<div class="md-typeset">
<h2>box_non_max_suppression</h2>
<h2><a href="#supervision.detection.utils.box_non_max_suppression">box_non_max_suppression</a></h2>
</div>
:::supervision.detection.utils.box_non_max_suppression
<div class="md-typeset">
<h2>mask_non_max_suppression</h2>
<h2><a href="#supervision.detection.utils.mask_non_max_suppression">mask_non_max_suppression</a></h2>
</div>
:::supervision.detection.utils.mask_non_max_suppression
<div class="md-typeset">
<h2>polygon_to_mask</h2>
<h2><a href="#supervision.detection.utils.polygon_to_mask">polygon_to_mask</a></h2>
</div>
:::supervision.detection.utils.polygon_to_mask
<div class="md-typeset">
<h2>mask_to_xyxy</h2>
<h2><a href="#supervision.detection.utils.mask_to_xyxy">mask_to_xyxy</a></h2>
</div>
:::supervision.detection.utils.mask_to_xyxy
<div class="md-typeset">
<h2>mask_to_polygons</h2>
<h2><a href="#supervision.detection.utils.mask_to_polygons">mask_to_polygons</a></h2>
</div>
:::supervision.detection.utils.mask_to_polygons
<div class="md-typeset">
<h2>polygon_to_xyxy</h2>
<h2><a href="#supervision.detection.utils.polygon_to_xyxy">polygon_to_xyxy</a></h2>
</div>
:::supervision.detection.utils.polygon_to_xyxy
<div class="md-typeset">
<h2>filter_polygons_by_area</h2>
<h2><a href="#supervision.detection.utils.filter_polygons_by_area">filter_polygons_by_area</a></h2>
</div>
:::supervision.detection.utils.filter_polygons_by_area
<div class="md-typeset">
<h2>move_boxes</h2>
<h2><a href="#supervision.detection.utils.move_boxes">move_boxes</a></h2>
</div>
:::supervision.detection.utils.move_boxes
<div class="md-typeset">
<h2>scale_boxes</h2>
<h2><a href="#supervision.detection.utils.scale_boxes">scale_boxes</a></h2>
</div>
:::supervision.detection.utils.scale_boxes
-13
View File
@@ -1,13 +0,0 @@
---
comments: true
---
# Color
:::supervision.draw.color.Color
<div class="md-typeset">
<h2>ColorPalette</h2>
</div>
:::supervision.draw.color.ColorPalette
-53
View File
@@ -1,53 +0,0 @@
---
comments: true
---
# Draw Utils
<div class="md-typeset">
<h2>draw_line</h2>
</div>
:::supervision.draw.utils.draw_line
<div class="md-typeset">
<h2>draw_rectangle</h2>
</div>
:::supervision.draw.utils.draw_rectangle
<div class="md-typeset">
<h2>draw_filled_rectangle</h2>
</div>
:::supervision.draw.utils.draw_filled_rectangle
<div class="md-typeset">
<h2>draw_polygon</h2>
</div>
:::supervision.draw.utils.draw_polygon
<div class="md-typeset">
<h2>draw_text</h2>
</div>
:::supervision.draw.utils.draw_text
<div class="md-typeset">
<h2>draw_image</h2>
</div>
:::supervision.draw.utils.draw_image
<div class="md-typeset">
<h2>calculate_optimal_font_scale</h2>
</div>
:::supervision.draw.utils.calculate_optimal_text_scale
<div class="md-typeset">
<h2>calculate_optimal_line_thickness</h2>
</div>
:::supervision.draw.utils.calculate_optimal_line_thickness
-7
View File
@@ -1,7 +0,0 @@
---
comments: true
---
# Position
:::supervision.geometry.core.Position
+72 -26
View File
@@ -15,7 +15,7 @@ source image.
![basic-annotation](https://media.roboflow.com/supervision_detect_and_annotate_example_1.png)
## Run Inference
## Run Detection
First, you'll need to obtain predictions from your object detection or segmentation
model.
@@ -27,7 +27,7 @@ model.
from inference import get_model
model = get_model(model_id="yolov8n-640")
image = cv2.imread(<PATH TO IMAGE>)
image = cv2.imread(<SOURCE_IMAGE_PATH>)
results = model.infer(image)[0]
```
@@ -38,7 +38,7 @@ model.
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
image = cv2.imread(<PATH TO IMAGE>)
image = cv2.imread(<SOURCE_IMAGE_PATH>)
results = model(image)[0]
```
@@ -52,7 +52,7 @@ model.
processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")
image = Image.open(<PATH TO IMAGE>)
image = Image.open(<SOURCE_IMAGE_PATH>)
inputs = processor(images=image, return_tensors="pt")
with torch.no_grad():
@@ -78,7 +78,7 @@ Now that we have predictions from a model, we can load them into Supervision.
from inference import get_model
model = get_model(model_id="yolov8n-640")
image = cv2.imread(<PATH TO IMAGE>)
image = cv2.imread(<SOURCE_IMAGE_PATH>)
results = model.infer(image)[0]
detections = sv.Detections.from_inference(results)
```
@@ -93,7 +93,7 @@ Now that we have predictions from a model, we can load them into Supervision.
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
image = cv2.imread(<PATH TO IMAGE>)
image = cv2.imread(<SOURCE_IMAGE_PATH>)
results = model(image)[0]
detections = sv.Detections.from_ultralytics(results)
```
@@ -102,7 +102,7 @@ Now that we have predictions from a model, we can load them into Supervision.
We can do so using the [`sv.Detections.from_transformers`](detection/core/#supervision.detection.core.Detections.from_transformers) method, which accepts model results from both detection and segmentation models.
```{ .py hl_lines="2 19" }
```{ .py hl_lines="2 19-21" }
import torch
import supervision as sv
from PIL import Image
@@ -111,7 +111,7 @@ Now that we have predictions from a model, we can load them into Supervision.
processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")
image = Image.open(<PATH TO IMAGE>)
image = Image.open(<SOURCE_IMAGE_PATH>)
inputs = processor(images=image, return_tensors="pt")
with torch.no_grad():
@@ -121,7 +121,9 @@ Now that we have predictions from a model, we can load them into Supervision.
target_size = torch.tensor([[height, width]])
results = processor.post_process_object_detection(
outputs=outputs, target_sizes=target_size)[0]
detections = sv.Detections.from_transformers(results)
detections = sv.Detections.from_transformers(
transformers_results=results,
id2label=model.config.id2label)
```
You can load predictions from other computer vision frameworks and libraries using:
@@ -144,7 +146,7 @@ Finally, we can annotate the image with the predictions. Since we are working wi
from inference import get_model
model = get_model(model_id="yolov8n-640")
image = cv2.imread(<PATH TO IMAGE>)
image = cv2.imread(<SOURCE_IMAGE_PATH>)
results = model.infer(image)[0]
detections = sv.Detections.from_inference(results)
@@ -165,7 +167,7 @@ Finally, we can annotate the image with the predictions. Since we are working wi
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
image = cv2.imread(<PATH TO IMAGE>)
image = cv2.imread(<SOURCE_IMAGE_PATH>)
results = model(image)[0]
detections = sv.Detections.from_ultralytics(results)
@@ -180,7 +182,7 @@ Finally, we can annotate the image with the predictions. Since we are working wi
=== "Transformers"
```{ .py hl_lines="21-27" }
```{ .py hl_lines="23-30" }
import torch
import supervision as sv
from PIL import Image
@@ -189,7 +191,7 @@ Finally, we can annotate the image with the predictions. Since we are working wi
processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")
image = Image.open(<PATH TO IMAGE>)
image = Image.open(<SOURCE_IMAGE_PATH>)
inputs = processor(images=image, return_tensors="pt")
with torch.no_grad():
@@ -199,7 +201,9 @@ Finally, we can annotate the image with the predictions. Since we are working wi
target_size = torch.tensor([[height, width]])
results = processor.post_process_object_detection(
outputs=outputs, target_sizes=target_size)[0]
detections = sv.Detections.from_transformers(results)
detections = sv.Detections.from_transformers(
transformers_results=results,
id2label=model.config.id2label)
bounding_box_annotator = sv.BoundingBoxAnnotator()
label_annotator = sv.LabelAnnotator()
@@ -226,7 +230,7 @@ override this behavior by passing a list of custom `labels` to the `annotate` me
from inference import get_model
model = get_model(model_id="yolov8n-640")
image = cv2.imread(<PATH TO IMAGE>)
image = cv2.imread(<SOURCE_IMAGE_PATH>)
results = model.infer(image)[0]
detections = sv.Detections.from_inference(results)
@@ -253,7 +257,7 @@ override this behavior by passing a list of custom `labels` to the `annotate` me
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
image = cv2.imread(<PATH TO IMAGE>)
image = cv2.imread(<SOURCE_IMAGE_PATH>)
results = model(image)[0]
detections = sv.Detections.from_ultralytics(results)
@@ -274,7 +278,7 @@ override this behavior by passing a list of custom `labels` to the `annotate` me
=== "Transformers"
```{ .py hl_lines="24-28 33" }
```{ .py hl_lines="26-30 35" }
import torch
import supervision as sv
from PIL import Image
@@ -283,7 +287,7 @@ override this behavior by passing a list of custom `labels` to the `annotate` me
processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")
image = Image.open(<PATH TO IMAGE>)
image = Image.open(<SOURCE_IMAGE_PATH>)
inputs = processor(images=image, return_tensors="pt")
with torch.no_grad():
@@ -293,15 +297,17 @@ override this behavior by passing a list of custom `labels` to the `annotate` me
target_size = torch.tensor([[height, width]])
results = processor.post_process_object_detection(
outputs=outputs, target_sizes=target_size)[0]
detections = sv.Detections.from_transformers(results)
detections = sv.Detections.from_transformers(
transformers_results=results,
id2label=model.config.id2label)
bounding_box_annotator = sv.BoundingBoxAnnotator()
label_annotator = sv.LabelAnnotator()
labels = [
f"{model.config.id2label[class_id]} {confidence:.2f}"
for class_id, confidence
in zip(detections.class_id, detections.confidence)
f"{class_name} {confidence:.2f}"
for class_name, confidence
in zip(detections['class_name'], detections.confidence)
]
annotated_image = bounding_box_annotator.annotate(
@@ -328,12 +334,12 @@ that will allow you to draw masks instead of boxes.
from inference import get_model
model = get_model(model_id="yolov8n-seg-640")
image = cv2.imread(<PATH TO IMAGE>)
image = cv2.imread(<SOURCE_IMAGE_PATH>)
results = model.infer(image)[0]
detections = sv.Detections.from_inference(results)
mask_annotator = sv.MaskAnnotator()
label_annotator = sv.LabelAnnotator(text_position=sv.Position.CENTER)
label_annotator = sv.LabelAnnotator(text_position=sv.Position.CENTER_OF_MASS)
annotated_image = mask_annotator.annotate(
scene=image, detections=detections)
@@ -349,12 +355,12 @@ that will allow you to draw masks instead of boxes.
from ultralytics import YOLO
model = YOLO("yolov8n-seg.pt")
image = cv2.imread(<PATH TO IMAGE>)
image = cv2.imread(<SOURCE_IMAGE_PATH>)
results = model(image)[0]
detections = sv.Detections.from_ultralytics(results)
mask_annotator = sv.MaskAnnotator()
label_annotator = sv.LabelAnnotator(text_position=sv.Position.CENTER)
label_annotator = sv.LabelAnnotator(text_position=sv.Position.CENTER_OF_MASS)
annotated_image = mask_annotator.annotate(
scene=image, detections=detections)
@@ -362,4 +368,44 @@ that will allow you to draw masks instead of boxes.
scene=annotated_image, detections=detections)
```
=== "Transformers"
```python
import torch
import supervision as sv
from PIL import Image
from transformers import DetrImageProcessor, DetrForSegmentation
processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50-panoptic")
model = DetrForSegmentation.from_pretrained("facebook/detr-resnet-50-panoptic")
image = Image.open(<SOURCE_IMAGE_PATH>)
inputs = processor(images=image, return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
width, height = image.size
target_size = torch.tensor([[height, width]])
results = processor.post_process_segmentation(
outputs=outputs, target_sizes=target_size)[0]
detections = sv.Detections.from_transformers(
transformers_results=results,
id2label=model.config.id2label)
mask_annotator = sv.MaskAnnotator()
label_annotator = sv.LabelAnnotator(text_position=sv.Position.CENTER_OF_MASS)
labels = [
f"{class_name} {confidence:.2f}"
for class_name, confidence
in zip(detections['class_name'], detections.confidence)
]
annotated_image = mask_annotator.annotate(
scene=image, detections=detections)
annotated_image = label_annotator.annotate(
scene=annotated_image, detections=detections, labels=labels)
```
![segmentation-annotation](https://media.roboflow.com/supervision_detect_and_annotate_example_3.png)
+8 -8
View File
@@ -28,7 +28,7 @@ size relative to the image resolution.
from inference import get_model
model = get_model(model_id="yolov8x-640")
image = cv2.imread(<PATH TO IMAGE>)
image = cv2.imread(<SOURCE_IMAGE_PATH>)
results = model.infer(image)[0]
detections = sv.Detections.from_inference(results)
@@ -49,7 +49,7 @@ size relative to the image resolution.
from ultralytics import YOLO
model = YOLO("yolov8x.pt")
image = cv2.imread(<PATH TO IMAGE>)
image = cv2.imread(<SOURCE_IMAGE_PATH>)
results = model(image)[0]
detections = sv.Detections.from_ultralytics(results)
@@ -73,7 +73,7 @@ size relative to the image resolution.
processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")
image = Image.open(<PATH TO IMAGE>)
image = Image.open(<SOURCE_IMAGE_PATH>)
inputs = processor(images=image, return_tensors="pt")
with torch.no_grad():
@@ -116,7 +116,7 @@ is less effective for ultra-high-resolution images (4K and above).
from inference import get_model
model = get_model(model_id="yolov8x-1280")
image = cv2.imread(<PATH TO IMAGE>)
image = cv2.imread(<SOURCE_IMAGE_PATH>)
results = model.infer(image)[0]
detections = sv.Detections.from_inference(results)
@@ -137,7 +137,7 @@ is less effective for ultra-high-resolution images (4K and above).
from ultralytics import YOLO
model = YOLO("yolov8x.pt")
image = cv2.imread(<PATH TO IMAGE>)
image = cv2.imread(<SOURCE_IMAGE_PATH>)
results = model(image, imgsz=1280)[0]
detections = sv.Detections.from_ultralytics(results)
@@ -171,7 +171,7 @@ objects within each, and aggregating the results.
from inference import get_model
model = get_model(model_id="yolov8x-640")
image = cv2.imread(<PATH TO IMAGE>)
image = cv2.imread(<SOURCE_IMAGE_PATH>)
def callback(image_slice: np.ndarray) -> sv.Detections:
results = model.infer(image_slice)[0]
@@ -198,7 +198,7 @@ objects within each, and aggregating the results.
from ultralytics import YOLO
model = YOLO("yolov8x.pt")
image = cv2.imread(<PATH TO IMAGE>)
image = cv2.imread(<SOURCE_IMAGE_PATH>)
def callback(image_slice: np.ndarray) -> sv.Detections:
result = model(image_slice)[0]
@@ -229,7 +229,7 @@ objects within each, and aggregating the results.
processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")
image = cv2.imread(<PATH TO IMAGE>)
image = cv2.imread(<SOURCE_IMAGE_PATH>)
def callback(image_slice: np.ndarray) -> sv.Detections:
image_slice = cv2.cvtColor(image_slice, cv2.COLOR_BGR2RGB)
+299
View File
@@ -0,0 +1,299 @@
---
comments: true
status: new
---
# Save Detections
Supervision enables an easy way to save detections in .CSV and .JSON files for offline
processing. This guide demonstrates how to perform video inference using the
[Inference](https://github.com/roboflow/inference),
[Ultralytics](https://github.com/ultralytics/ultralytics) or
[Transformers](https://github.com/huggingface/transformers) packages and save their results with
[`sv.CSVSink`](/latest/detection/tools/save_detections/#supervision.detection.tools.csv_sink.CSVSink) and
[`sv.JSONSink`](/latest/detection/tools/save_detections/#supervision.detection.tools.csv_sink.JSONSink).
## Run Detection
First, you'll need to obtain predictions from your object detection or segmentation
model. You can learn more on this topic in our
[How to Detect and Annotate](/latest/how_to/detect_and_annotate.md) guide.
=== "Inference"
```python
import supervision as sv
from inference import get_model
model = get_model(model_id="yolov8n-640")
frames_generator = sv.get_video_frames_generator(<SOURCE_VIDEO_PATH>)
for frame in frames_generator:
results = model.infer(image)[0]
detections = sv.Detections.from_inference(results)
```
=== "Ultralytics"
```python
import supervision as sv
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
frames_generator = sv.get_video_frames_generator(<SOURCE_VIDEO_PATH>)
for frame in frames_generator:
results = model(frame)[0]
detections = sv.Detections.from_ultralytics(results)
```
=== "Transformers"
```python
import torch
import supervision as sv
from transformers import DetrImageProcessor, DetrForObjectDetection
processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")
frames_generator = sv.get_video_frames_generator(<SOURCE_VIDEO_PATH>)
for frame in frames_generator:
frame = sv.cv2_to_pillow(frame)
inputs = processor(images=frame, return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
width, height = frame.size
target_size = torch.tensor([[height, width]])
results = processor.post_process_object_detection(
outputs=outputs, target_sizes=target_size)[0]
detections = sv.Detections.from_transformers(results)
```
## Save Detections as CSV
To save detections to a `.CSV` file, open our
[`sv.CSVSink`](/latest/detection/tools/save_detections/#supervision.detection.tools.csv_sink.CSVSink)
and then pass the
[`sv.Detections`](/latest/detection/core/#supervision.detection.core.Detections)
object resulting from the inference to it. Its fields are parsed and saved on disk.
=== "Inference"
```{ .py hl_lines="7 12" }
import supervision as sv
from inference import get_model
model = get_model(model_id="yolov8n-640")
frames_generator = sv.get_video_frames_generator(<SOURCE_VIDEO_PATH>)
with sv.CSVSink(<TARGET_CSV_PATH>) as sink:
for frame in frames_generator:
results = model.infer(image)[0]
detections = sv.Detections.from_inference(results)
sink.append(detections, {})
```
=== "Ultralytics"
```{ .py hl_lines="7 12" }
import supervision as sv
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
frames_generator = sv.get_video_frames_generator(<SOURCE_VIDEO_PATH>)
with sv.CSVSink(<TARGET_CSV_PATH>) as sink:
for frame in frames_generator:
results = model(frame)[0]
detections = sv.Detections.from_ultralytics(results)
sink.append(detections, {})
```
=== "Transformers"
```{ .py hl_lines="9 23" }
import torch
import supervision as sv
from transformers import DetrImageProcessor, DetrForObjectDetection
processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")
frames_generator = sv.get_video_frames_generator(<SOURCE_VIDEO_PATH>)
with sv.CSVSink(<TARGET_CSV_PATH>) as sink:
for frame in frames_generator:
frame = sv.cv2_to_pillow(frame)
inputs = processor(images=frame, return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
width, height = frame.size
target_size = torch.tensor([[height, width]])
results = processor.post_process_object_detection(
outputs=outputs, target_sizes=target_size)[0]
detections = sv.Detections.from_transformers(results)
sink.append(detections, {})
```
| x_min | y_min | x_max | y_max | class_id | confidence | tracker_id | class_name |
|---------|----------|---------|----------|----------|------------|------------|------------|
| 2941.14 | 1269.31 | 3220.77 | 1500.67 | 2 | 0.8517 | | car |
| 944.889 | 899.641 | 1235.42 | 1308.80 | 7 | 0.6752 | | truck |
| 1439.78 | 1077.79 | 1621.27 | 1231.40 | 2 | 0.6450 | | car |
## Custom Fields
Besides regular fields in
[`sv.Detections`](/latest/detection/core/#supervision.detection.core.Detections),
[`sv.CSVSink`](/latest/detection/tools/save_detections/#supervision.detection.tools.csv_sink.CSVSink)
also allows you to add custom information to each row, which can be passed via the
`custom_data` dictionary. Let's utilize this feature to save information about the
frame index from which the detections originate.
=== "Inference"
```{ .py hl_lines="8 12" }
import supervision as sv
from inference import get_model
model = get_model(model_id="yolov8n-640")
frames_generator = sv.get_video_frames_generator(<SOURCE_VIDEO_PATH>)
with sv.CSVSink(<TARGET_CSV_PATH>) as sink:
for frame_index, frame in enumerate(frames_generator):
results = model.infer(image)[0]
detections = sv.Detections.from_inference(results)
sink.append(detections, {"frame_index": frame_index})
```
=== "Ultralytics"
```{ .py hl_lines="8 12" }
import supervision as sv
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
frames_generator = sv.get_video_frames_generator(<SOURCE_VIDEO_PATH>)
with sv.CSVSink(<TARGET_CSV_PATH>) as sink:
for frame_index, frame in enumerate(frames_generator):
results = model(frame)[0]
detections = sv.Detections.from_ultralytics(results)
sink.append(detections, {"frame_index": frame_index})
```
=== "Transformers"
```{ .py hl_lines="10 23" }
import torch
import supervision as sv
from transformers import DetrImageProcessor, DetrForObjectDetection
processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")
frames_generator = sv.get_video_frames_generator(<SOURCE_VIDEO_PATH>)
with sv.CSVSink(<TARGET_CSV_PATH>) as sink:
for frame_index, frame in enumerate(frames_generator):
frame = sv.cv2_to_pillow(frame)
inputs = processor(images=frame, return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
width, height = frame.size
target_size = torch.tensor([[height, width]])
results = processor.post_process_object_detection(
outputs=outputs, target_sizes=target_size)[0]
detections = sv.Detections.from_transformers(results)
sink.append(detections, {"frame_index": frame_index})
```
| x_min | y_min | x_max | y_max | class_id | confidence | tracker_id | class_name | frame_index |
|---------|----------|---------|----------|----------|------------|------------|------------|-------------|
| 2941.14 | 1269.31 | 3220.77 | 1500.67 | 2 | 0.8517 | | car | 0 |
| 944.889 | 899.641 | 1235.42 | 1308.80 | 7 | 0.6752 | | truck | 0 |
| 1439.78 | 1077.79 | 1621.27 | 1231.40 | 2 | 0.6450 | | car | 0 |
## Save Detections as JSON
If you prefer to save the result in a `.JSON` file instead of a `.CSV` file, all you
need to do is replace
[`sv.CSVSink`](/latest/detection/tools/save_detections/#supervision.detection.tools.csv_sink.CSVSink)
with
[`sv.JSONSink`](/latest/detection/tools/save_detections/#supervision.detection.tools.csv_sink.JSONSink).
=== "Inference"
```{ .py hl_lines="7" }
import supervision as sv
from inference import get_model
model = get_model(model_id="yolov8n-640")
frames_generator = sv.get_video_frames_generator(<SOURCE_VIDEO_PATH>)
with sv.JSONSink(<TARGET_CSV_PATH>) as sink:
for frame_index, frame in enumerate(frames_generator):
results = model.infer(image)[0]
detections = sv.Detections.from_inference(results)
sink.append(detections, {"frame_index": frame_index})
```
=== "Ultralytics"
```{ .py hl_lines="7" }
import supervision as sv
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
frames_generator = sv.get_video_frames_generator(<SOURCE_VIDEO_PATH>)
with sv.JSONSink(<TARGET_CSV_PATH>) as sink:
for frame_index, frame in enumerate(frames_generator):
results = model(frame)[0]
detections = sv.Detections.from_ultralytics(results)
sink.append(detections, {"frame_index": frame_index})
```
=== "Transformers"
```{ .py hl_lines="9" }
import torch
import supervision as sv
from transformers import DetrImageProcessor, DetrForObjectDetection
processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")
frames_generator = sv.get_video_frames_generator(<SOURCE_VIDEO_PATH>)
with sv.JSONSink(<TARGET_CSV_PATH>) as sink:
for frame_index, frame in enumerate(frames_generator):
frame = sv.cv2_to_pillow(frame)
inputs = processor(images=frame, return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
width, height = frame.size
target_size = torch.tensor([[height, width]])
results = processor.post_process_object_detection(
outputs=outputs, target_sizes=target_size)[0]
detections = sv.Detections.from_transformers(results)
sink.append(detections, {"frame_index": frame_index})
```
+19 -2
View File
@@ -30,7 +30,7 @@ We write your reusable computer vision tools. Whether you need to load your data
## 💻 Install
You can install `supervision` with pip in a
You can install `supervision` in a
[**Python>=3.8**](https://www.python.org/) environment.
!!! example "pip install (recommended)"
@@ -49,6 +49,24 @@ You can install `supervision` with pip in a
pip install "supervision[desktop]"
```
!!! example "conda/mamba install"
=== "conda"
[![conda-recipe](https://img.shields.io/badge/recipe-supervision-green.svg)](https://anaconda.org/conda-forge/supervision) [![conda-downloads](https://img.shields.io/conda/dn/conda-forge/supervision.svg)](https://anaconda.org/conda-forge/supervision) [![conda-version](https://img.shields.io/conda/vn/conda-forge/supervision.svg)](https://anaconda.org/conda-forge/supervision) [![conda-platforms](https://img.shields.io/conda/pn/conda-forge/supervision.svg)](https://anaconda.org/conda-forge/supervision)
```bash
conda install -c conda-forge supervision
```
=== "mamba"
[![mamba-recipe](https://img.shields.io/badge/recipe-supervision-green.svg)](https://anaconda.org/conda-forge/supervision) [![mamba-downloads](https://img.shields.io/conda/dn/conda-forge/supervision.svg)](https://anaconda.org/conda-forge/supervision) [![mamba-version](https://img.shields.io/conda/vn/conda-forge/supervision.svg)](https://anaconda.org/conda-forge/supervision) [![mamba-platforms](https://img.shields.io/conda/pn/conda-forge/supervision.svg)](https://anaconda.org/conda-forge/supervision)
```bash
mamba install -c conda-forge supervision
```
!!! example "git clone (for development)"
=== "virtualenv"
@@ -88,7 +106,6 @@ You can install `supervision` with pip in a
poetry install --extras "desktop"
```
## 🚀 Quickstart
<div class="grid cards" markdown>
+60
View File
@@ -0,0 +1,60 @@
---
comments: true
status: new
---
# Annotators
=== "VertexAnnotator"
```python
import supervision as sv
image = ...
key_points = sv.KeyPoints(...)
vertex_annotator = sv.VertexAnnotator(color=sv.Color.GREEN, radius=10)
annotated_frame = vertex_annotator.annotate(
scene=image.copy(),
key_points=key_points
)
```
<div class="result" markdown>
![vertex-annotator-example](https://media.roboflow.com/supervision-annotator-examples/vertex-annotator-example.png){ align=center width="800" }
</div>
=== "EdgeAnnotator"
```python
import supervision as sv
image = ...
key_points = sv.KeyPoints(...)
edge_annotator = sv.EdgeAnnotator(color=sv.Color.GREEN, thickness=5)
annotated_frame = edge_annotator.annotate(
scene=image.copy(),
key_points=key_points
)
```
<div class="result" markdown>
![edge-annotator-example](https://media.roboflow.com/supervision-annotator-examples/edge-annotator-example.png){ align=center width="800" }
</div>
<div class="md-typeset">
<h2><a href="#supervision.keypoint.annotators.VertexAnnotator">VertexAnnotator</a></h2>
</div>
:::supervision.keypoint.annotators.VertexAnnotator
<div class="md-typeset">
<h2><a href="#supervision.keypoint.annotators.EdgeAnnotator">EdgeAnnotator</a></h2>
</div>
:::supervision.keypoint.annotators.EdgeAnnotator
+8
View File
@@ -0,0 +1,8 @@
---
comments: true
status: new
---
# Keypoint Detection
:::supervision.keypoint.core.KeyPoints
-22
View File
@@ -1,22 +0,0 @@
---
comments: true
---
#  Detection Metrics
!!! warning
Evaluation API is still fluid and may change. If you use Evaluation API in your project until further notice, freeze the
`supervision` version in your `requirements.txt` or `setup.py`.
<div class="md-typeset">
<h2><a href="#supervision.metrics.detection.ConfusionMatrix">ConfusionMatrix</a></h2>
</div>
:::supervision.metrics.detection.ConfusionMatrix
<div class="md-typeset">
<h2><a href="#supervision.annotators.core.MeanAveragePrecision">MeanAveragePrecision</a></h2>
</div>
:::supervision.metrics.detection.MeanAveragePrecision
+65
View File
@@ -0,0 +1,65 @@
---
comments: true
---
# Draw Utils
<div class="md-typeset">
<h2><a href="#supervision.draw.utils.draw_line">draw_line</a></h2>
</div>
:::supervision.draw.utils.draw_line
<div class="md-typeset">
<h2><a href="#supervision.draw.utils.draw_rectangle">draw_rectangle</a></h2>
</div>
:::supervision.draw.utils.draw_rectangle
<div class="md-typeset">
<h2><a href="#supervision.draw.utils.draw_filled_rectangle">draw_filled_rectangle</a></h2>
</div>
:::supervision.draw.utils.draw_filled_rectangle
<div class="md-typeset">
<h2><a href="#supervision.draw.utils.draw_polygon">draw_polygon</a></h2>
</div>
:::supervision.draw.utils.draw_polygon
<div class="md-typeset">
<h2><a href="#supervision.draw.utils.draw_text">draw_text</a></h2>
</div>
:::supervision.draw.utils.draw_text
<div class="md-typeset">
<h2><a href="#supervision.draw.utils.draw_image">draw_image</a></h2>
</div>
:::supervision.draw.utils.draw_image
<div class="md-typeset">
<h2><a href="#supervision.draw.utils.calculate_optimal_font_scale">calculate_optimal_font_scale</a></h2>
</div>
:::supervision.draw.utils.calculate_optimal_text_scale
<div class="md-typeset">
<h2><a href="#supervision.draw.utils.calculate_optimal_line_thickness">calculate_optimal_line_thickness</a></h2>
</div>
:::supervision.draw.utils.calculate_optimal_line_thickness
<div class="md-typeset">
<h2><a href="#supervision.draw.color.Color">Color</a></h2>
</div>
:::supervision.draw.color.Color
<div class="md-typeset">
<h2><a href="#supervision.draw.color.ColorPalette">ColorPalette</a></h2>
</div>
:::supervision.draw.color.ColorPalette
+1 -1
View File
@@ -5,7 +5,7 @@ comments: true
# File Utils
<div class="md-typeset">
<h2>list_files_with_extensions</h2>
<h2><a href="#supervision.utils.file.list_files_with_extensions">list_files_with_extensions</a></h2>
</div>
:::supervision.utils.file.list_files_with_extensions
+15
View File
@@ -0,0 +1,15 @@
---
comments: true
---
<div class="md-typeset">
<h2><a href="#supervision.geometry.core.utils.get_polygon_center">get_polygon_center</a></h2>
</div>
:::supervision.geometry.utils.get_polygon_center
<div class="md-typeset">
<h2><a href="#supervision.geometry.core.Position">Position</a></h2>
</div>
:::supervision.geometry.core.Position
+22 -10
View File
@@ -6,25 +6,37 @@ status: new
# Image Utils
<div class="md-typeset">
<h2>ImageSink</h2>
</div>
:::supervision.utils.image.ImageSink
<div class="md-typeset">
<h2>crop_image</h2>
<h2><a href="#supervision.utils.image.crop_image">crop_image</a></h2>
</div>
:::supervision.utils.image.crop_image
<div class="md-typeset">
<h2>resize_image</h2>
<h2><a href="#supervision.utils.image.scale_image">crop_image</a></h2>
</div>
:::supervision.utils.image.scale_image
<div class="md-typeset">
<h2><a href="#supervision.utils.image.resize_image">resize_image</a></h2>
</div>
:::supervision.utils.image.resize_image
<div class="md-typeset">
<h2>place_image</h2>
<h2><a href="#supervision.utils.image.letterbox_image">letterbox_image</a></h2>
</div>
:::supervision.utils.image.place_image
:::supervision.utils.image.letterbox_image
<div class="md-typeset">
<h2><a href="#supervision.utils.image.overlay_image">overlay_image</a></h2>
</div>
:::supervision.utils.image.overlay_image
<div class="md-typeset">
<h2><a href="#supervision.utils.image.ImageSink">ImageSink</a></h2>
</div>
:::supervision.utils.image.ImageSink
+18
View File
@@ -0,0 +1,18 @@
---
comments: true
status: new
---
# Iterables Utils
<div class="md-typeset">
<h2><a href="#supervision.utils.iterables.create_batches">create_batches</a></h2>
</div>
:::supervision.utils.iterables.create_batches
<div class="md-typeset">
<h2><a href="#supervision.utils.iterables.fill">fill</a></h2>
</div>
:::supervision.utils.iterables.fill
+2 -3
View File
@@ -5,14 +5,13 @@ comments: true
# Notebooks Utils
<div class="md-typeset">
<h2>plot_image</h2>
<h2><a href="#supervision.utils.notebook.plot_image">plot_image</a></h2>
</div>
:::supervision.utils.notebook.plot_image
<div class="md-typeset">
<h2>## plot_images_grid
</h2>
<h2><a href="#supervision.utils.notebook.plot_images_grid">plot_images_grid</a></h2>
</div>
:::supervision.utils.notebook.plot_images_grid
+5 -5
View File
@@ -5,31 +5,31 @@ comments: true
# Video Utils
<div class="md-typeset">
<h2>VideoInfo</h2>
<h2><a href="#supervision.utils.video.VideoInfo">VideoInfo</a></h2>
</div>
:::supervision.utils.video.VideoInfo
<div class="md-typeset">
<h2>VideoSink</h2>
<h2><a href="#supervision.utils.video.VideoSink">VideoSink</a></h2>
</div>
:::supervision.utils.video.VideoSink
<div class="md-typeset">
<h2>FPSMonitor</h2>
<h2><a href="#supervision.utils.video.FPSMonitor">FPSMonitor</a></h2>
</div>
:::supervision.utils.video.FPSMonitor
<div class="md-typeset">
<h2>get_video_frames_generator</h2>
<h2><a href="#supervision.utils.video.get_video_frames_generator">get_video_frames_generator</a></h2>
</div>
:::supervision.utils.video.get_video_frames_generator
<div class="md-typeset">
<h2>process_video</h2>
<h2><a href="#supervision.utils.video.process_video">process_video</a></h2>
</div>
:::supervision.utils.video.process_video
+3 -23
View File
@@ -1,8 +1,8 @@
# Examples
This repository is packed with real-world use-cases, provided through Python scripts or
interactive notebooks. Browse through to understand how the Supervision library
interfaces with diverse applications.
Here, you'll find end-to-end examples that show how to solve common computer vision problems using Supervision.
For more information and examples, visit our [documentation](https://supervision.roboflow.com/develop/annotators/) and explore our [how-to guides](https://supervision.roboflow.com/develop/how_to/detect_and_annotate/) and [cookbooks](https://supervision.roboflow.com/develop/cookbooks/). Join our [Discord](https://discord.com/invite/GbfgXGJ8Bk) and meet other Supervision power users!
- [tracking](./tracking) by [@SkalskiP](https://github.com/SkalskiP)
- [count people in zone](./count_people_in_zone) by [@SkalskiP](https://github.com/SkalskiP)
@@ -10,23 +10,3 @@ interfaces with diverse applications.
- [speed estimation](./speed_estimation) by [@SkalskiP](https://github.com/SkalskiP)
- [time in zone](./time_in_zone) by [@SkalskiP](https://github.com/SkalskiP)
- [heatmap and track](./heatmap_and_track/) by [@HinePo](https://github.com/HinePo)
## Contributing
We welcome contributions from the community in the form of examples, applications, and
guides. To contribute, please follow these steps:
1. Create a pull request (PR) with the `[Example]` prefix in the title, adding your
project folder to the `examples/` directory in the repository.
2. Confirm your project aligns with the following standards:
- Incorporates the `supervision` package.
- Provides a `README.md` file, detailing the instructions to execute the project.
- Showcases visual results, demonstrating the app's functionality.
- Avoids adding large assets or dependencies unless absolutely necessary.
- The contributor is expected to provide support for issues related to their
examples.
- In case the presented model has licensing complications, kindly specify them to
circumvent potential misunderstandings.
For inquiries or concerns about these prerequisites, feel free to raise a PR. We are
committed to assist and guide you.
+3
View File
@@ -1,5 +1,8 @@
# count people in zone
[![Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/roboflow-ai/notebooks/blob/main/notebooks/how-to-detect-and-count-objects-in-polygon-zone.ipynb)
[![YouTube](https://badges.aleen42.com/src/youtube.svg)](https://www.youtube.com/watch?v=l_kf9CfZ_8M)
## 👋 hello
This demo is a video analysis tool that counts and highlights objects in specific zones
+2
View File
@@ -1,5 +1,7 @@
# time in zone
[![YouTube](https://badges.aleen42.com/src/youtube.svg)](https://www.youtube.com/watch?v=hAWpsIuem10)
## 👋 hello
Practical demonstration on leveraging computer vision for analyzing wait times and
+14 -12
View File
@@ -38,16 +38,22 @@ nav:
- Home: index.md
- How to:
- Detect and Annotate: how_to/detect_and_annotate.md
- Save Detections: how_to/save_detections.md
- Filter Detections: how_to/filter_detections.md
- Detect Small Objects: how_to/detect_small_objects.md
- Track Objects: how_to/track_objects.md
- Filter Detections: how_to/filter_detections.md
- API:
- Annotators: annotators.md
- Classifications:
- Core: classification/core.md
- Detections:
- Detection and Segmentation:
- Core: detection/core.md
- Annotators: detection/annotators.md
- Metrics: detection/metrics.md
- Utils: detection/utils.md
- Keypoint Detection:
- Core: keypoint/core.md
- Annotators: keypoint/annotators.md
- Classification:
- Core: classification/core.md
- Tools:
- Line Zone: detection/tools/line_zone.md
- Polygon Zone: detection/tools/polygon_zone.md
@@ -56,18 +62,14 @@ nav:
- Save Detections: detection/tools/save_detections.md
- Trackers: trackers.md
- Datasets: datasets.md
- Metrics:
- Object Detection: metrics/detection.md
- Draw:
- Color: draw/color.md
- Utils: draw/utils.md
- Geometry:
- Position: geometry/core.md
- Utils:
- Video: utils/video.md
- Image: utils/image.md
- Iterables: utils/iterables.md
- Notebook: utils/notebook.md
- File: utils/file.md
- Draw: utils/draw.md
- Geometry: utils/geometry.md
- Assets: assets.md
- Cookbooks: cookbooks.md
- Contribute:
Generated
+106 -109
View File
@@ -244,13 +244,13 @@ css = ["tinycss2 (>=1.1.0,<1.3)"]
[[package]]
name = "build"
version = "1.2.0"
version = "1.2.1"
description = "A simple, correct Python build frontend"
optional = false
python-versions = ">=3.8"
files = [
{file = "build-1.2.0-py3-none-any.whl", hash = "sha256:6105465d9b233433ce8ffa151c760f674446ba766af0290fc14bfa32aef92a04"},
{file = "build-1.2.0.tar.gz", hash = "sha256:49df7f8e1e74d345fe71e54f5d56423b2111eda89e3da53a2c18392954dade1d"},
{file = "build-1.2.1-py3-none-any.whl", hash = "sha256:75e10f767a433d9a86e50d83f418e83efc18ede923ee5ff7df93b6cb0306c5d4"},
{file = "build-1.2.1.tar.gz", hash = "sha256:526263f4870c26f26c433545579475377b2b7588b6f1eac76a001e873ae3e19d"},
]
[package.dependencies]
@@ -1122,13 +1122,13 @@ license = ["ukkonen"]
[[package]]
name = "idna"
version = "3.6"
version = "3.7"
description = "Internationalized Domain Names in Applications (IDNA)"
optional = false
python-versions = ">=3.5"
files = [
{file = "idna-3.6-py3-none-any.whl", hash = "sha256:c05567e9c24a6b9faaa835c4821bad0590fbb9d5779e7caa6e1cc4978e7eb24f"},
{file = "idna-3.6.tar.gz", hash = "sha256:9ecdbbd083b06798ae1e86adcbfe8ab1479cf864e4ee30fe4e46a003d12491ca"},
{file = "idna-3.7-py3-none-any.whl", hash = "sha256:82fee1fc78add43492d3a1898bfa6d8a904cc97d8427f683ed8e798d07761aa0"},
{file = "idna-3.7.tar.gz", hash = "sha256:028ff3aadf0609c1fd278d8ea3089299412a7a8b9bd005dd08b9f8285bcb5cfc"},
]
[[package]]
@@ -2162,13 +2162,12 @@ pytz = "*"
[[package]]
name = "mkdocs-jupyter"
version = "0.24.3"
version = "0.24.7"
description = "Use Jupyter in mkdocs websites"
optional = false
python-versions = ">=3.7"
python-versions = ">=3.8"
files = [
{file = "mkdocs_jupyter-0.24.3-py3-none-any.whl", hash = "sha256:904262a8678a5e5920b7c3c03b5010b36301a69d0a38f2fcbf430493adf6879e"},
{file = "mkdocs_jupyter-0.24.3.tar.gz", hash = "sha256:3d81da9aea27480e93bab22438910c4f0b9630613e74f85b576590d78e0e8b14"},
{file = "mkdocs_jupyter-0.24.7-py3-none-any.whl", hash = "sha256:893d04bea1e007479a46e4e72852cd4d280c4d358ce4a0445250f3f80c639723"},
]
[package.dependencies]
@@ -2179,18 +2178,15 @@ mkdocs-material = ">9.0.0"
nbconvert = ">=7.2.9,<8"
pygments = ">2.12.0"
[package.extras]
test = ["coverage[toml]", "pymdown-extensions", "pytest", "pytest-cov"]
[[package]]
name = "mkdocs-material"
version = "9.5.15"
version = "9.5.18"
description = "Documentation that simply works"
optional = false
python-versions = ">=3.8"
files = [
{file = "mkdocs_material-9.5.15-py3-none-any.whl", hash = "sha256:e5c96dec3d19491de49ca643fc1dbb92b278e43cdb816c775bc47db77d9b62fb"},
{file = "mkdocs_material-9.5.15.tar.gz", hash = "sha256:39f03cca45e82bf54eb7456b5a18bd252eabfdd67f237a229471484a0a4d4635"},
{file = "mkdocs_material-9.5.18-py3-none-any.whl", hash = "sha256:1e0e27fc9fe239f9064318acf548771a4629d5fd5dfd45444fd80a953fe21eb4"},
{file = "mkdocs_material-9.5.18.tar.gz", hash = "sha256:a43f470947053fa2405c33995f282d24992c752a50114f23f30da9d8d0c57e62"},
]
[package.dependencies]
@@ -2226,13 +2222,13 @@ files = [
[[package]]
name = "mkdocstrings"
version = "0.24.1"
version = "0.24.3"
description = "Automatic documentation from sources, for MkDocs."
optional = false
python-versions = ">=3.8"
files = [
{file = "mkdocstrings-0.24.1-py3-none-any.whl", hash = "sha256:b4206f9a2ca8a648e222d5a0ca1d36ba7dee53c88732818de183b536f9042b5d"},
{file = "mkdocstrings-0.24.1.tar.gz", hash = "sha256:cc83f9a1c8724fc1be3c2fa071dd73d91ce902ef6a79710249ec8d0ee1064401"},
{file = "mkdocstrings-0.24.3-py3-none-any.whl", hash = "sha256:5c9cf2a32958cd161d5428699b79c8b0988856b0d4a8c5baf8395fc1bf4087c3"},
{file = "mkdocstrings-0.24.3.tar.gz", hash = "sha256:f327b234eb8d2551a306735436e157d0a22d45f79963c60a8b585d5f7a94c1d2"},
]
[package.dependencies]
@@ -2470,13 +2466,13 @@ setuptools = "*"
[[package]]
name = "notebook"
version = "7.1.2"
version = "7.1.3"
description = "Jupyter Notebook - A web-based notebook environment for interactive computing"
optional = false
python-versions = ">=3.8"
files = [
{file = "notebook-7.1.2-py3-none-any.whl", hash = "sha256:fc6c24b9aef18d0cd57157c9c47e95833b9b0bdc599652639acf0bdb61dc7d5f"},
{file = "notebook-7.1.2.tar.gz", hash = "sha256:efc2c80043909e0faa17fce9e9b37c059c03af0ec99a4d4db84cb21d9d2e936a"},
{file = "notebook-7.1.3-py3-none-any.whl", hash = "sha256:919b911e59f41f6e3857ce93c9d93535ba66bb090059712770e5968c07e1004d"},
{file = "notebook-7.1.3.tar.gz", hash = "sha256:41fcebff44cf7bb9377180808bcbae066629b55d8c7722f1ebbe75ca44f9cfc1"},
]
[package.dependencies]
@@ -2693,79 +2689,80 @@ files = [
[[package]]
name = "pillow"
version = "10.2.0"
version = "10.3.0"
description = "Python Imaging Library (Fork)"
optional = false
python-versions = ">=3.8"
files = [
{file = "pillow-10.2.0-cp310-cp310-macosx_10_10_x86_64.whl", hash = "sha256:7823bdd049099efa16e4246bdf15e5a13dbb18a51b68fa06d6c1d4d8b99a796e"},
{file = "pillow-10.2.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:83b2021f2ade7d1ed556bc50a399127d7fb245e725aa0113ebd05cfe88aaf588"},
{file = "pillow-10.2.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6fad5ff2f13d69b7e74ce5b4ecd12cc0ec530fcee76356cac6742785ff71c452"},
{file = "pillow-10.2.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:da2b52b37dad6d9ec64e653637a096905b258d2fc2b984c41ae7d08b938a67e4"},
{file = "pillow-10.2.0-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:47c0995fc4e7f79b5cfcab1fc437ff2890b770440f7696a3ba065ee0fd496563"},
{file = "pillow-10.2.0-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:322bdf3c9b556e9ffb18f93462e5f749d3444ce081290352c6070d014c93feb2"},
{file = "pillow-10.2.0-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:51f1a1bffc50e2e9492e87d8e09a17c5eea8409cda8d3f277eb6edc82813c17c"},
{file = "pillow-10.2.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:69ffdd6120a4737710a9eee73e1d2e37db89b620f702754b8f6e62594471dee0"},
{file = "pillow-10.2.0-cp310-cp310-win32.whl", hash = "sha256:c6dafac9e0f2b3c78df97e79af707cdc5ef8e88208d686a4847bab8266870023"},
{file = "pillow-10.2.0-cp310-cp310-win_amd64.whl", hash = "sha256:aebb6044806f2e16ecc07b2a2637ee1ef67a11840a66752751714a0d924adf72"},
{file = "pillow-10.2.0-cp310-cp310-win_arm64.whl", hash = "sha256:7049e301399273a0136ff39b84c3678e314f2158f50f517bc50285fb5ec847ad"},
{file = "pillow-10.2.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:35bb52c37f256f662abdfa49d2dfa6ce5d93281d323a9af377a120e89a9eafb5"},
{file = "pillow-10.2.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:9c23f307202661071d94b5e384e1e1dc7dfb972a28a2310e4ee16103e66ddb67"},
{file = "pillow-10.2.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:773efe0603db30c281521a7c0214cad7836c03b8ccff897beae9b47c0b657d61"},
{file = "pillow-10.2.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:11fa2e5984b949b0dd6d7a94d967743d87c577ff0b83392f17cb3990d0d2fd6e"},
{file = "pillow-10.2.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:716d30ed977be8b37d3ef185fecb9e5a1d62d110dfbdcd1e2a122ab46fddb03f"},
{file = "pillow-10.2.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:a086c2af425c5f62a65e12fbf385f7c9fcb8f107d0849dba5839461a129cf311"},
{file = "pillow-10.2.0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:c8de2789052ed501dd829e9cae8d3dcce7acb4777ea4a479c14521c942d395b1"},
{file = "pillow-10.2.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:609448742444d9290fd687940ac0b57fb35e6fd92bdb65386e08e99af60bf757"},
{file = "pillow-10.2.0-cp311-cp311-win32.whl", hash = "sha256:823ef7a27cf86df6597fa0671066c1b596f69eba53efa3d1e1cb8b30f3533068"},
{file = "pillow-10.2.0-cp311-cp311-win_amd64.whl", hash = "sha256:1da3b2703afd040cf65ec97efea81cfba59cdbed9c11d8efc5ab09df9509fc56"},
{file = "pillow-10.2.0-cp311-cp311-win_arm64.whl", hash = "sha256:edca80cbfb2b68d7b56930b84a0e45ae1694aeba0541f798e908a49d66b837f1"},
{file = "pillow-10.2.0-cp312-cp312-macosx_10_10_x86_64.whl", hash = "sha256:1b5e1b74d1bd1b78bc3477528919414874748dd363e6272efd5abf7654e68bef"},
{file = "pillow-10.2.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:0eae2073305f451d8ecacb5474997c08569fb4eb4ac231ffa4ad7d342fdc25ac"},
{file = "pillow-10.2.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b7c2286c23cd350b80d2fc9d424fc797575fb16f854b831d16fd47ceec078f2c"},
{file = "pillow-10.2.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1e23412b5c41e58cec602f1135c57dfcf15482013ce6e5f093a86db69646a5aa"},
{file = "pillow-10.2.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:52a50aa3fb3acb9cf7213573ef55d31d6eca37f5709c69e6858fe3bc04a5c2a2"},
{file = "pillow-10.2.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:127cee571038f252a552760076407f9cff79761c3d436a12af6000cd182a9d04"},
{file = "pillow-10.2.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:8d12251f02d69d8310b046e82572ed486685c38f02176bd08baf216746eb947f"},
{file = "pillow-10.2.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:54f1852cd531aa981bc0965b7d609f5f6cc8ce8c41b1139f6ed6b3c54ab82bfb"},
{file = "pillow-10.2.0-cp312-cp312-win32.whl", hash = "sha256:257d8788df5ca62c980314053197f4d46eefedf4e6175bc9412f14412ec4ea2f"},
{file = "pillow-10.2.0-cp312-cp312-win_amd64.whl", hash = "sha256:154e939c5f0053a383de4fd3d3da48d9427a7e985f58af8e94d0b3c9fcfcf4f9"},
{file = "pillow-10.2.0-cp312-cp312-win_arm64.whl", hash = "sha256:f379abd2f1e3dddb2b61bc67977a6b5a0a3f7485538bcc6f39ec76163891ee48"},
{file = "pillow-10.2.0-cp38-cp38-macosx_10_10_x86_64.whl", hash = "sha256:8373c6c251f7ef8bda6675dd6d2b3a0fcc31edf1201266b5cf608b62a37407f9"},
{file = "pillow-10.2.0-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:870ea1ada0899fd0b79643990809323b389d4d1d46c192f97342eeb6ee0b8483"},
{file = "pillow-10.2.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b4b6b1e20608493548b1f32bce8cca185bf0480983890403d3b8753e44077129"},
{file = "pillow-10.2.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3031709084b6e7852d00479fd1d310b07d0ba82765f973b543c8af5061cf990e"},
{file = "pillow-10.2.0-cp38-cp38-manylinux_2_28_aarch64.whl", hash = "sha256:3ff074fc97dd4e80543a3e91f69d58889baf2002b6be64347ea8cf5533188213"},
{file = "pillow-10.2.0-cp38-cp38-manylinux_2_28_x86_64.whl", hash = "sha256:cb4c38abeef13c61d6916f264d4845fab99d7b711be96c326b84df9e3e0ff62d"},
{file = "pillow-10.2.0-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:b1b3020d90c2d8e1dae29cf3ce54f8094f7938460fb5ce8bc5c01450b01fbaf6"},
{file = "pillow-10.2.0-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:170aeb00224ab3dc54230c797f8404507240dd868cf52066f66a41b33169bdbe"},
{file = "pillow-10.2.0-cp38-cp38-win32.whl", hash = "sha256:c4225f5220f46b2fde568c74fca27ae9771536c2e29d7c04f4fb62c83275ac4e"},
{file = "pillow-10.2.0-cp38-cp38-win_amd64.whl", hash = "sha256:0689b5a8c5288bc0504d9fcee48f61a6a586b9b98514d7d29b840143d6734f39"},
{file = "pillow-10.2.0-cp39-cp39-macosx_10_10_x86_64.whl", hash = "sha256:b792a349405fbc0163190fde0dc7b3fef3c9268292586cf5645598b48e63dc67"},
{file = "pillow-10.2.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:c570f24be1e468e3f0ce7ef56a89a60f0e05b30a3669a459e419c6eac2c35364"},
{file = "pillow-10.2.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d8ecd059fdaf60c1963c58ceb8997b32e9dc1b911f5da5307aab614f1ce5c2fb"},
{file = "pillow-10.2.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c365fd1703040de1ec284b176d6af5abe21b427cb3a5ff68e0759e1e313a5e7e"},
{file = "pillow-10.2.0-cp39-cp39-manylinux_2_28_aarch64.whl", hash = "sha256:70c61d4c475835a19b3a5aa42492409878bbca7438554a1f89d20d58a7c75c01"},
{file = "pillow-10.2.0-cp39-cp39-manylinux_2_28_x86_64.whl", hash = "sha256:b6f491cdf80ae540738859d9766783e3b3c8e5bd37f5dfa0b76abdecc5081f13"},
{file = "pillow-10.2.0-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:9d189550615b4948f45252d7f005e53c2040cea1af5b60d6f79491a6e147eef7"},
{file = "pillow-10.2.0-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:49d9ba1ed0ef3e061088cd1e7538a0759aab559e2e0a80a36f9fd9d8c0c21591"},
{file = "pillow-10.2.0-cp39-cp39-win32.whl", hash = "sha256:babf5acfede515f176833ed6028754cbcd0d206f7f614ea3447d67c33be12516"},
{file = "pillow-10.2.0-cp39-cp39-win_amd64.whl", hash = "sha256:0304004f8067386b477d20a518b50f3fa658a28d44e4116970abfcd94fac34a8"},
{file = "pillow-10.2.0-cp39-cp39-win_arm64.whl", hash = "sha256:0fb3e7fc88a14eacd303e90481ad983fd5b69c761e9e6ef94c983f91025da869"},
{file = "pillow-10.2.0-pp310-pypy310_pp73-macosx_10_10_x86_64.whl", hash = "sha256:322209c642aabdd6207517e9739c704dc9f9db943015535783239022002f054a"},
{file = "pillow-10.2.0-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3eedd52442c0a5ff4f887fab0c1c0bb164d8635b32c894bc1faf4c618dd89df2"},
{file = "pillow-10.2.0-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cb28c753fd5eb3dd859b4ee95de66cc62af91bcff5db5f2571d32a520baf1f04"},
{file = "pillow-10.2.0-pp310-pypy310_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:33870dc4653c5017bf4c8873e5488d8f8d5f8935e2f1fb9a2208c47cdd66efd2"},
{file = "pillow-10.2.0-pp310-pypy310_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:3c31822339516fb3c82d03f30e22b1d038da87ef27b6a78c9549888f8ceda39a"},
{file = "pillow-10.2.0-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:a2b56ba36e05f973d450582fb015594aaa78834fefe8dfb8fcd79b93e64ba4c6"},
{file = "pillow-10.2.0-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:d8e6aeb9201e655354b3ad049cb77d19813ad4ece0df1249d3c793de3774f8c7"},
{file = "pillow-10.2.0-pp39-pypy39_pp73-macosx_10_10_x86_64.whl", hash = "sha256:2247178effb34a77c11c0e8ac355c7a741ceca0a732b27bf11e747bbc950722f"},
{file = "pillow-10.2.0-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:15587643b9e5eb26c48e49a7b33659790d28f190fc514a322d55da2fb5c2950e"},
{file = "pillow-10.2.0-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:753cd8f2086b2b80180d9b3010dd4ed147efc167c90d3bf593fe2af21265e5a5"},
{file = "pillow-10.2.0-pp39-pypy39_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:7c8f97e8e7a9009bcacbe3766a36175056c12f9a44e6e6f2d5caad06dcfbf03b"},
{file = "pillow-10.2.0-pp39-pypy39_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:d1b35bcd6c5543b9cb547dee3150c93008f8dd0f1fef78fc0cd2b141c5baf58a"},
{file = "pillow-10.2.0-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:fe4c15f6c9285dc54ce6553a3ce908ed37c8f3825b5a51a15c91442bb955b868"},
{file = "pillow-10.2.0.tar.gz", hash = "sha256:e87f0b2c78157e12d7686b27d63c070fd65d994e8ddae6f328e0dcf4a0cd007e"},
{file = "pillow-10.3.0-cp310-cp310-macosx_10_10_x86_64.whl", hash = "sha256:90b9e29824800e90c84e4022dd5cc16eb2d9605ee13f05d47641eb183cd73d45"},
{file = "pillow-10.3.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:a2c405445c79c3f5a124573a051062300936b0281fee57637e706453e452746c"},
{file = "pillow-10.3.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:78618cdbccaa74d3f88d0ad6cb8ac3007f1a6fa5c6f19af64b55ca170bfa1edf"},
{file = "pillow-10.3.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:261ddb7ca91fcf71757979534fb4c128448b5b4c55cb6152d280312062f69599"},
{file = "pillow-10.3.0-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:ce49c67f4ea0609933d01c0731b34b8695a7a748d6c8d186f95e7d085d2fe475"},
{file = "pillow-10.3.0-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:b14f16f94cbc61215115b9b1236f9c18403c15dd3c52cf629072afa9d54c1cbf"},
{file = "pillow-10.3.0-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:d33891be6df59d93df4d846640f0e46f1a807339f09e79a8040bc887bdcd7ed3"},
{file = "pillow-10.3.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:b50811d664d392f02f7761621303eba9d1b056fb1868c8cdf4231279645c25f5"},
{file = "pillow-10.3.0-cp310-cp310-win32.whl", hash = "sha256:ca2870d5d10d8726a27396d3ca4cf7976cec0f3cb706debe88e3a5bd4610f7d2"},
{file = "pillow-10.3.0-cp310-cp310-win_amd64.whl", hash = "sha256:f0d0591a0aeaefdaf9a5e545e7485f89910c977087e7de2b6c388aec32011e9f"},
{file = "pillow-10.3.0-cp310-cp310-win_arm64.whl", hash = "sha256:ccce24b7ad89adb5a1e34a6ba96ac2530046763912806ad4c247356a8f33a67b"},
{file = "pillow-10.3.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:5f77cf66e96ae734717d341c145c5949c63180842a545c47a0ce7ae52ca83795"},
{file = "pillow-10.3.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:e4b878386c4bf293578b48fc570b84ecfe477d3b77ba39a6e87150af77f40c57"},
{file = "pillow-10.3.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:fdcbb4068117dfd9ce0138d068ac512843c52295ed996ae6dd1faf537b6dbc27"},
{file = "pillow-10.3.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9797a6c8fe16f25749b371c02e2ade0efb51155e767a971c61734b1bf6293994"},
{file = "pillow-10.3.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:9e91179a242bbc99be65e139e30690e081fe6cb91a8e77faf4c409653de39451"},
{file = "pillow-10.3.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:1b87bd9d81d179bd8ab871603bd80d8645729939f90b71e62914e816a76fc6bd"},
{file = "pillow-10.3.0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:81d09caa7b27ef4e61cb7d8fbf1714f5aec1c6b6c5270ee53504981e6e9121ad"},
{file = "pillow-10.3.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:048ad577748b9fa4a99a0548c64f2cb8d672d5bf2e643a739ac8faff1164238c"},
{file = "pillow-10.3.0-cp311-cp311-win32.whl", hash = "sha256:7161ec49ef0800947dc5570f86568a7bb36fa97dd09e9827dc02b718c5643f09"},
{file = "pillow-10.3.0-cp311-cp311-win_amd64.whl", hash = "sha256:8eb0908e954d093b02a543dc963984d6e99ad2b5e36503d8a0aaf040505f747d"},
{file = "pillow-10.3.0-cp311-cp311-win_arm64.whl", hash = "sha256:4e6f7d1c414191c1199f8996d3f2282b9ebea0945693fb67392c75a3a320941f"},
{file = "pillow-10.3.0-cp312-cp312-macosx_10_10_x86_64.whl", hash = "sha256:e46f38133e5a060d46bd630faa4d9fa0202377495df1f068a8299fd78c84de84"},
{file = "pillow-10.3.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:50b8eae8f7334ec826d6eeffaeeb00e36b5e24aa0b9df322c247539714c6df19"},
{file = "pillow-10.3.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9d3bea1c75f8c53ee4d505c3e67d8c158ad4df0d83170605b50b64025917f338"},
{file = "pillow-10.3.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:19aeb96d43902f0a783946a0a87dbdad5c84c936025b8419da0a0cd7724356b1"},
{file = "pillow-10.3.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:74d28c17412d9caa1066f7a31df8403ec23d5268ba46cd0ad2c50fb82ae40462"},
{file = "pillow-10.3.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:ff61bfd9253c3915e6d41c651d5f962da23eda633cf02262990094a18a55371a"},
{file = "pillow-10.3.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:d886f5d353333b4771d21267c7ecc75b710f1a73d72d03ca06df49b09015a9ef"},
{file = "pillow-10.3.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:4b5ec25d8b17217d635f8935dbc1b9aa5907962fae29dff220f2659487891cd3"},
{file = "pillow-10.3.0-cp312-cp312-win32.whl", hash = "sha256:51243f1ed5161b9945011a7360e997729776f6e5d7005ba0c6879267d4c5139d"},
{file = "pillow-10.3.0-cp312-cp312-win_amd64.whl", hash = "sha256:412444afb8c4c7a6cc11a47dade32982439925537e483be7c0ae0cf96c4f6a0b"},
{file = "pillow-10.3.0-cp312-cp312-win_arm64.whl", hash = "sha256:798232c92e7665fe82ac085f9d8e8ca98826f8e27859d9a96b41d519ecd2e49a"},
{file = "pillow-10.3.0-cp38-cp38-macosx_10_10_x86_64.whl", hash = "sha256:4eaa22f0d22b1a7e93ff0a596d57fdede2e550aecffb5a1ef1106aaece48e96b"},
{file = "pillow-10.3.0-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:cd5e14fbf22a87321b24c88669aad3a51ec052eb145315b3da3b7e3cc105b9a2"},
{file = "pillow-10.3.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1530e8f3a4b965eb6a7785cf17a426c779333eb62c9a7d1bbcf3ffd5bf77a4aa"},
{file = "pillow-10.3.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5d512aafa1d32efa014fa041d38868fda85028e3f930a96f85d49c7d8ddc0383"},
{file = "pillow-10.3.0-cp38-cp38-manylinux_2_28_aarch64.whl", hash = "sha256:339894035d0ede518b16073bdc2feef4c991ee991a29774b33e515f1d308e08d"},
{file = "pillow-10.3.0-cp38-cp38-manylinux_2_28_x86_64.whl", hash = "sha256:aa7e402ce11f0885305bfb6afb3434b3cd8f53b563ac065452d9d5654c7b86fd"},
{file = "pillow-10.3.0-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:0ea2a783a2bdf2a561808fe4a7a12e9aa3799b701ba305de596bc48b8bdfce9d"},
{file = "pillow-10.3.0-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:c78e1b00a87ce43bb37642c0812315b411e856a905d58d597750eb79802aaaa3"},
{file = "pillow-10.3.0-cp38-cp38-win32.whl", hash = "sha256:72d622d262e463dfb7595202d229f5f3ab4b852289a1cd09650362db23b9eb0b"},
{file = "pillow-10.3.0-cp38-cp38-win_amd64.whl", hash = "sha256:2034f6759a722da3a3dbd91a81148cf884e91d1b747992ca288ab88c1de15999"},
{file = "pillow-10.3.0-cp39-cp39-macosx_10_10_x86_64.whl", hash = "sha256:2ed854e716a89b1afcedea551cd85f2eb2a807613752ab997b9974aaa0d56936"},
{file = "pillow-10.3.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:dc1a390a82755a8c26c9964d457d4c9cbec5405896cba94cf51f36ea0d855002"},
{file = "pillow-10.3.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4203efca580f0dd6f882ca211f923168548f7ba334c189e9eab1178ab840bf60"},
{file = "pillow-10.3.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3102045a10945173d38336f6e71a8dc71bcaeed55c3123ad4af82c52807b9375"},
{file = "pillow-10.3.0-cp39-cp39-manylinux_2_28_aarch64.whl", hash = "sha256:6fb1b30043271ec92dc65f6d9f0b7a830c210b8a96423074b15c7bc999975f57"},
{file = "pillow-10.3.0-cp39-cp39-manylinux_2_28_x86_64.whl", hash = "sha256:1dfc94946bc60ea375cc39cff0b8da6c7e5f8fcdc1d946beb8da5c216156ddd8"},
{file = "pillow-10.3.0-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:b09b86b27a064c9624d0a6c54da01c1beaf5b6cadfa609cf63789b1d08a797b9"},
{file = "pillow-10.3.0-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:d3b2348a78bc939b4fed6552abfd2e7988e0f81443ef3911a4b8498ca084f6eb"},
{file = "pillow-10.3.0-cp39-cp39-win32.whl", hash = "sha256:45ebc7b45406febf07fef35d856f0293a92e7417ae7933207e90bf9090b70572"},
{file = "pillow-10.3.0-cp39-cp39-win_amd64.whl", hash = "sha256:0ba26351b137ca4e0db0342d5d00d2e355eb29372c05afd544ebf47c0956ffeb"},
{file = "pillow-10.3.0-cp39-cp39-win_arm64.whl", hash = "sha256:50fd3f6b26e3441ae07b7c979309638b72abc1a25da31a81a7fbd9495713ef4f"},
{file = "pillow-10.3.0-pp310-pypy310_pp73-macosx_10_10_x86_64.whl", hash = "sha256:6b02471b72526ab8a18c39cb7967b72d194ec53c1fd0a70b050565a0f366d355"},
{file = "pillow-10.3.0-pp310-pypy310_pp73-macosx_11_0_arm64.whl", hash = "sha256:8ab74c06ffdab957d7670c2a5a6e1a70181cd10b727cd788c4dd9005b6a8acd9"},
{file = "pillow-10.3.0-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:048eeade4c33fdf7e08da40ef402e748df113fd0b4584e32c4af74fe78baaeb2"},
{file = "pillow-10.3.0-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9e2ec1e921fd07c7cda7962bad283acc2f2a9ccc1b971ee4b216b75fad6f0463"},
{file = "pillow-10.3.0-pp310-pypy310_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:4c8e73e99da7db1b4cad7f8d682cf6abad7844da39834c288fbfa394a47bbced"},
{file = "pillow-10.3.0-pp310-pypy310_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:16563993329b79513f59142a6b02055e10514c1a8e86dca8b48a893e33cf91e3"},
{file = "pillow-10.3.0-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:dd78700f5788ae180b5ee8902c6aea5a5726bac7c364b202b4b3e3ba2d293170"},
{file = "pillow-10.3.0-pp39-pypy39_pp73-macosx_10_10_x86_64.whl", hash = "sha256:aff76a55a8aa8364d25400a210a65ff59d0168e0b4285ba6bf2bd83cf675ba32"},
{file = "pillow-10.3.0-pp39-pypy39_pp73-macosx_11_0_arm64.whl", hash = "sha256:b7bc2176354defba3edc2b9a777744462da2f8e921fbaf61e52acb95bafa9828"},
{file = "pillow-10.3.0-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:793b4e24db2e8742ca6423d3fde8396db336698c55cd34b660663ee9e45ed37f"},
{file = "pillow-10.3.0-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d93480005693d247f8346bc8ee28c72a2191bdf1f6b5db469c096c0c867ac015"},
{file = "pillow-10.3.0-pp39-pypy39_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:c83341b89884e2b2e55886e8fbbf37c3fa5efd6c8907124aeb72f285ae5696e5"},
{file = "pillow-10.3.0-pp39-pypy39_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:1a1d1915db1a4fdb2754b9de292642a39a7fb28f1736699527bb649484fb966a"},
{file = "pillow-10.3.0-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:a0eaa93d054751ee9964afa21c06247779b90440ca41d184aeb5d410f20ff591"},
{file = "pillow-10.3.0.tar.gz", hash = "sha256:9d2455fbf44c914840c793e89aa82d0e1763a14253a000743719ae5946814b2d"},
]
[package.extras]
@@ -3646,28 +3643,28 @@ files = [
[[package]]
name = "ruff"
version = "0.3.4"
version = "0.4.1"
description = "An extremely fast Python linter and code formatter, written in Rust."
optional = false
python-versions = ">=3.7"
files = [
{file = "ruff-0.3.4-py3-none-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl", hash = "sha256:60c870a7d46efcbc8385d27ec07fe534ac32f3b251e4fc44b3cbfd9e09609ef4"},
{file = "ruff-0.3.4-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:6fc14fa742e1d8f24910e1fff0bd5e26d395b0e0e04cc1b15c7c5e5fe5b4af91"},
{file = "ruff-0.3.4-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d3ee7880f653cc03749a3bfea720cf2a192e4f884925b0cf7eecce82f0ce5854"},
{file = "ruff-0.3.4-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:cf133dd744f2470b347f602452a88e70dadfbe0fcfb5fd46e093d55da65f82f7"},
{file = "ruff-0.3.4-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:3f3860057590e810c7ffea75669bdc6927bfd91e29b4baa9258fd48b540a4365"},
{file = "ruff-0.3.4-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:986f2377f7cf12efac1f515fc1a5b753c000ed1e0a6de96747cdf2da20a1b369"},
{file = "ruff-0.3.4-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c4fd98e85869603e65f554fdc5cddf0712e352fe6e61d29d5a6fe087ec82b76c"},
{file = "ruff-0.3.4-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:64abeed785dad51801b423fa51840b1764b35d6c461ea8caef9cf9e5e5ab34d9"},
{file = "ruff-0.3.4-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:df52972138318bc7546d92348a1ee58449bc3f9eaf0db278906eb511889c4b50"},
{file = "ruff-0.3.4-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:98e98300056445ba2cc27d0b325fd044dc17fcc38e4e4d2c7711585bd0a958ed"},
{file = "ruff-0.3.4-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:519cf6a0ebed244dce1dc8aecd3dc99add7a2ee15bb68cf19588bb5bf58e0488"},
{file = "ruff-0.3.4-py3-none-musllinux_1_2_i686.whl", hash = "sha256:bb0acfb921030d00070539c038cd24bb1df73a2981e9f55942514af8b17be94e"},
{file = "ruff-0.3.4-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:cf187a7e7098233d0d0c71175375c5162f880126c4c716fa28a8ac418dcf3378"},
{file = "ruff-0.3.4-py3-none-win32.whl", hash = "sha256:af27ac187c0a331e8ef91d84bf1c3c6a5dea97e912a7560ac0cef25c526a4102"},
{file = "ruff-0.3.4-py3-none-win_amd64.whl", hash = "sha256:de0d5069b165e5a32b3c6ffbb81c350b1e3d3483347196ffdf86dc0ef9e37dd6"},
{file = "ruff-0.3.4-py3-none-win_arm64.whl", hash = "sha256:6810563cc08ad0096b57c717bd78aeac888a1bfd38654d9113cb3dc4d3f74232"},
{file = "ruff-0.3.4.tar.gz", hash = "sha256:f0f4484c6541a99862b693e13a151435a279b271cff20e37101116a21e2a1ad1"},
{file = "ruff-0.4.1-py3-none-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl", hash = "sha256:2d9ef6231e3fbdc0b8c72404a1a0c46fd0dcea84efca83beb4681c318ea6a953"},
{file = "ruff-0.4.1-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:9485f54a7189e6f7433e0058cf8581bee45c31a25cd69009d2a040d1bd4bfaef"},
{file = "ruff-0.4.1-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d2921ac03ce1383e360e8a95442ffb0d757a6a7ddd9a5be68561a671e0e5807e"},
{file = "ruff-0.4.1-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:eec8d185fe193ad053eda3a6be23069e0c8ba8c5d20bc5ace6e3b9e37d246d3f"},
{file = "ruff-0.4.1-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:baa27d9d72a94574d250f42b7640b3bd2edc4c58ac8ac2778a8c82374bb27984"},
{file = "ruff-0.4.1-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:f1ee41580bff1a651339eb3337c20c12f4037f6110a36ae4a2d864c52e5ef954"},
{file = "ruff-0.4.1-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:0926cefb57fc5fced629603fbd1a23d458b25418681d96823992ba975f050c2b"},
{file = "ruff-0.4.1-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:2c6e37f2e3cd74496a74af9a4fa67b547ab3ca137688c484749189bf3a686ceb"},
{file = "ruff-0.4.1-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:efd703a5975ac1998c2cc5e9494e13b28f31e66c616b0a76e206de2562e0843c"},
{file = "ruff-0.4.1-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:b92f03b4aa9fa23e1799b40f15f8b95cdc418782a567d6c43def65e1bbb7f1cf"},
{file = "ruff-0.4.1-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:1c859f294f8633889e7d77de228b203eb0e9a03071b72b5989d89a0cf98ee262"},
{file = "ruff-0.4.1-py3-none-musllinux_1_2_i686.whl", hash = "sha256:b34510141e393519a47f2d7b8216fec747ea1f2c81e85f076e9f2910588d4b64"},
{file = "ruff-0.4.1-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:6e68d248ed688b9d69fd4d18737edcbb79c98b251bba5a2b031ce2470224bdf9"},
{file = "ruff-0.4.1-py3-none-win32.whl", hash = "sha256:b90506f3d6d1f41f43f9b7b5ff845aeefabed6d2494307bc7b178360a8805252"},
{file = "ruff-0.4.1-py3-none-win_amd64.whl", hash = "sha256:c7d391e5936af5c9e252743d767c564670dc3889aff460d35c518ee76e4b26d7"},
{file = "ruff-0.4.1-py3-none-win_arm64.whl", hash = "sha256:a1eaf03d87e6a7cd5e661d36d8c6e874693cb9bc3049d110bc9a97b350680c43"},
{file = "ruff-0.4.1.tar.gz", hash = "sha256:d592116cdbb65f8b1b7e2a2b48297eb865f6bdc20641879aa9d7b9c11d86db79"},
]
[[package]]
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "supervision"
version = "0.20.0rc2"
version = "0.20.0"
description = "A set of easy-to-use utils that will come in handy in any Computer Vision project"
authors = ["Piotr Skalski <piotr.skalski92@gmail.com>"]
maintainers = ["Piotr Skalski <piotr.skalski92@gmail.com>"]
+12 -1
View File
@@ -69,10 +69,21 @@ from supervision.draw.utils import (
)
from supervision.geometry.core import Point, Position, Rect
from supervision.geometry.utils import get_polygon_center
from supervision.keypoint.annotators import EdgeAnnotator, VertexAnnotator
from supervision.keypoint.core import KeyPoints
from supervision.metrics.detection import ConfusionMatrix, MeanAveragePrecision
from supervision.tracker.byte_tracker.core import ByteTrack
from supervision.utils.conversion import cv2_to_pillow, pillow_to_cv2
from supervision.utils.file import list_files_with_extensions
from supervision.utils.image import ImageSink, crop_image, place_image, resize_image
from supervision.utils.image import (
ImageSink,
create_tiles,
crop_image,
letterbox_image,
overlay_image,
resize_image,
scale_image,
)
from supervision.utils.notebook import plot_image, plot_images_grid
from supervision.utils.video import (
FPSMonitor,
+26 -28
View File
@@ -5,19 +5,15 @@ import cv2
import numpy as np
from supervision.annotators.base import BaseAnnotator, ImageType
from supervision.annotators.utils import (
ColorLookup,
Trace,
resolve_color,
scene_to_annotator_img_type,
)
from supervision.annotators.utils import ColorLookup, Trace, resolve_color
from supervision.config import CLASS_NAME_DATA_FIELD, ORIENTED_BOX_COORDINATES
from supervision.detection.core import Detections
from supervision.detection.utils import clip_boxes, mask_to_polygons
from supervision.draw.color import Color, ColorPalette
from supervision.draw.utils import draw_polygon
from supervision.geometry.core import Position
from supervision.utils.image import crop_image, place_image, resize_image
from supervision.utils.conversion import convert_for_annotation_method
from supervision.utils.image import crop_image, overlay_image, scale_image
class BoundingBoxAnnotator(BaseAnnotator):
@@ -43,7 +39,7 @@ class BoundingBoxAnnotator(BaseAnnotator):
self.thickness: int = thickness
self.color_lookup: ColorLookup = color_lookup
@scene_to_annotator_img_type
@convert_for_annotation_method
def annotate(
self,
scene: ImageType,
@@ -124,7 +120,7 @@ class OrientedBoxAnnotator(BaseAnnotator):
self.thickness: int = thickness
self.color_lookup: ColorLookup = color_lookup
@scene_to_annotator_img_type
@convert_for_annotation_method
def annotate(
self,
scene: ImageType,
@@ -212,7 +208,7 @@ class MaskAnnotator(BaseAnnotator):
self.opacity = opacity
self.color_lookup: ColorLookup = color_lookup
@scene_to_annotator_img_type
@convert_for_annotation_method
def annotate(
self,
scene: ImageType,
@@ -299,7 +295,7 @@ class PolygonAnnotator(BaseAnnotator):
self.thickness: int = thickness
self.color_lookup: ColorLookup = color_lookup
@scene_to_annotator_img_type
@convert_for_annotation_method
def annotate(
self,
scene: ImageType,
@@ -385,7 +381,7 @@ class ColorAnnotator(BaseAnnotator):
self.color_lookup: ColorLookup = color_lookup
self.opacity = opacity
@scene_to_annotator_img_type
@convert_for_annotation_method
def annotate(
self,
scene: ImageType,
@@ -479,7 +475,7 @@ class HaloAnnotator(BaseAnnotator):
self.color_lookup: ColorLookup = color_lookup
self.kernel_size: int = kernel_size
@scene_to_annotator_img_type
@convert_for_annotation_method
def annotate(
self,
scene: ImageType,
@@ -577,7 +573,7 @@ class EllipseAnnotator(BaseAnnotator):
self.end_angle: int = end_angle
self.color_lookup: ColorLookup = color_lookup
@scene_to_annotator_img_type
@convert_for_annotation_method
def annotate(
self,
scene: ImageType,
@@ -668,7 +664,7 @@ class BoxCornerAnnotator(BaseAnnotator):
self.corner_length: int = corner_length
self.color_lookup: ColorLookup = color_lookup
@scene_to_annotator_img_type
@convert_for_annotation_method
def annotate(
self,
scene: ImageType,
@@ -756,7 +752,7 @@ class CircleAnnotator(BaseAnnotator):
self.thickness: int = thickness
self.color_lookup: ColorLookup = color_lookup
@scene_to_annotator_img_type
@convert_for_annotation_method
def annotate(
self,
scene: ImageType,
@@ -846,7 +842,7 @@ class DotAnnotator(BaseAnnotator):
self.position: Position = position
self.color_lookup: ColorLookup = color_lookup
@scene_to_annotator_img_type
@convert_for_annotation_method
def annotate(
self,
scene: ImageType,
@@ -993,7 +989,7 @@ class LabelAnnotator:
center_y + text_h // 2,
)
@scene_to_annotator_img_type
@convert_for_annotation_method
def annotate(
self,
scene: ImageType,
@@ -1164,7 +1160,7 @@ class BlurAnnotator(BaseAnnotator):
"""
self.kernel_size: int = kernel_size
@scene_to_annotator_img_type
@convert_for_annotation_method
def annotate(
self,
scene: ImageType,
@@ -1249,7 +1245,7 @@ class TraceAnnotator:
self.thickness = thickness
self.color_lookup: ColorLookup = color_lookup
@scene_to_annotator_img_type
@convert_for_annotation_method
def annotate(
self,
scene: ImageType,
@@ -1356,7 +1352,7 @@ class HeatMapAnnotator:
self.top_hue = top_hue
self.low_hue = low_hue
@scene_to_annotator_img_type
@convert_for_annotation_method
def annotate(self, scene: ImageType, detections: Detections) -> ImageType:
"""
Annotates the scene with a heatmap based on the provided detections.
@@ -1432,7 +1428,7 @@ class PixelateAnnotator(BaseAnnotator):
"""
self.pixel_size: int = pixel_size
@scene_to_annotator_img_type
@convert_for_annotation_method
def annotate(
self,
scene: ImageType,
@@ -1520,7 +1516,7 @@ class TriangleAnnotator(BaseAnnotator):
self.position: Position = position
self.color_lookup: ColorLookup = color_lookup
@scene_to_annotator_img_type
@convert_for_annotation_method
def annotate(
self,
scene: ImageType,
@@ -1616,7 +1612,7 @@ class RoundBoxAnnotator(BaseAnnotator):
raise ValueError("roundness attribute must be float between (0, 1.0]")
self.roundness: float = roundness
@scene_to_annotator_img_type
@convert_for_annotation_method
def annotate(
self,
scene: ImageType,
@@ -1753,7 +1749,7 @@ class PercentageBarAnnotator(BaseAnnotator):
if border_thickness is None:
self.border_thickness = int(0.15 * self.height)
@scene_to_annotator_img_type
@convert_for_annotation_method
def annotate(
self,
scene: ImageType,
@@ -1926,7 +1922,7 @@ class CropAnnotator(BaseAnnotator):
self.border_thickness: int = border_thickness
self.border_color_lookup: ColorLookup = border_color_lookup
@scene_to_annotator_img_type
@convert_for_annotation_method
def annotate(
self,
scene: ImageType,
@@ -1969,7 +1965,7 @@ class CropAnnotator(BaseAnnotator):
crop_image(image=scene, xyxy=xyxy) for xyxy in detections.xyxy.astype(int)
]
resized_crops = [
resize_image(image=crop, scale_factor=self.scale_factor) for crop in crops
scale_image(image=crop, scale_factor=self.scale_factor) for crop in crops
]
anchors = detections.get_anchors_coordinates(anchor=self.position).astype(int)
@@ -1978,7 +1974,9 @@ class CropAnnotator(BaseAnnotator):
(x1, y1), (x2, y2) = self.calculate_crop_coordinates(
anchor=anchor, crop_wh=crop_wh, position=self.position
)
scene = place_image(scene=scene, image=resized_crop, anchor=(x1, y1))
scene = overlay_image(
scene=scene, inserted_image=resized_crop, anchor=(x1, y1)
)
color = resolve_color(
color=self.border_color,
detections=detections,
-34
View File
@@ -1,12 +1,8 @@
from enum import Enum
from functools import wraps
from typing import Optional, Union
import cv2
import numpy as np
from PIL import Image
from supervision.annotators.base import ImageType
from supervision.detection.core import Detections
from supervision.draw.color import Color, ColorPalette
from supervision.geometry.core import Position
@@ -123,33 +119,3 @@ class Trace:
def get(self, tracker_id: int) -> np.ndarray:
return self.xy[self.tracker_id == tracker_id]
def pillow_to_cv2(image: Image.Image) -> np.ndarray:
scene = np.array(image)
scene = cv2.cvtColor(scene, cv2.COLOR_RGB2BGR)
return scene
def scene_to_annotator_img_type(annotate_func):
"""
Decorates `BaseAnnotator.annotate` implementations, converts scene to
an image type used internally by the annotators, converts back when annotation
is complete.
"""
@wraps(annotate_func)
def wrapper(self, scene: ImageType, *args, **kwargs):
if isinstance(scene, np.ndarray):
return annotate_func(self, scene, *args, **kwargs)
if isinstance(scene, Image.Image):
scene = pillow_to_cv2(scene)
annotated = annotate_func(self, scene, *args, **kwargs)
annotated = cv2.cvtColor(annotated, cv2.COLOR_BGR2RGB)
annotated = Image.fromarray(annotated)
return annotated
raise ValueError(f"Unsupported image type: {type(scene)}")
return wrapper
+12
View File
@@ -18,6 +18,8 @@ class VideoAssets(Enum):
| `SUBWAY` | `subway.mp4` | [Link](https://media.roboflow.com/supervision/video-examples/subway.mp4) |
| `MARKET_SQUARE` | `market-square.mp4` | [Link](https://media.roboflow.com/supervision/video-examples/market-square.mp4) |
| `PEOPLE_WALKING` | `people-walking.mp4` | [Link](https://media.roboflow.com/supervision/video-examples/people-walking.mp4) |
| `BEACH` | `beach-1.mp4` | [Link](https://media.roboflow.com/supervision/video-examples/beach-1.mp4) |
| `BASKETBALL` | `basketball-1.mp4` | [Link](https://media.roboflow.com/supervision/video-examples/basketball-1.mp4) |
""" # noqa: E501 // docs
VEHICLES = "vehicles.mp4"
@@ -27,6 +29,8 @@ class VideoAssets(Enum):
SUBWAY = "subway.mp4"
MARKET_SQUARE = "market-square.mp4"
PEOPLE_WALKING = "people-walking.mp4"
BEACH = "beach-1.mp4"
BASKETBALL = "basketball-1.mp4"
@classmethod
def list(cls):
@@ -62,4 +66,12 @@ VIDEO_ASSETS: Dict[str, Tuple[str, str]] = {
f"{BASE_VIDEO_URL}{VideoAssets.PEOPLE_WALKING.value}",
"0574c053c8686c3f1dc0aa3743e45cb9",
),
VideoAssets.BEACH.value: (
f"{BASE_VIDEO_URL}{VideoAssets.BEACH.value}",
"4175d42fec4d450ed081523fd39e0cf8",
),
VideoAssets.BASKETBALL.value: (
f"{BASE_VIDEO_URL}{VideoAssets.BASKETBALL.value}",
"60d94a3c7c47d16f09d342b088012ecc",
),
}
+6 -6
View File
@@ -3,16 +3,12 @@ from typing import List, Optional, Union
import cv2
from supervision.annotators.base import ImageType
from supervision.annotators.utils import scene_to_annotator_img_type
from supervision.detection.core import Detections
from supervision.draw.color import Color, ColorPalette
from supervision.utils.conversion import convert_for_annotation_method
from supervision.utils.internal import deprecated
@deprecated(
"`BoxAnnotator` is deprecated and will be removed in "
"`supervision-0.22.0`. Use `BoundingBoxAnnotator` and `LabelAnnotator` instead"
)
class BoxAnnotator:
"""
A class for drawing bounding boxes on an image using detections provided.
@@ -46,7 +42,11 @@ class BoxAnnotator:
self.text_thickness: int = text_thickness
self.text_padding: int = text_padding
@scene_to_annotator_img_type
@deprecated(
"`BoxAnnotator` is deprecated and will be removed in "
"`supervision-0.22.0`. Use `BoundingBoxAnnotator` and `LabelAnnotator` instead"
)
@convert_for_annotation_method
def annotate(
self,
scene: ImageType,
+143 -64
View File
@@ -17,44 +17,81 @@ from supervision.detection.utils import (
mask_to_xyxy,
merge_data,
process_roboflow_result,
validate_detections_fields,
xywh_to_xyxy,
)
from supervision.geometry.core import Position
from supervision.utils.internal import deprecated
from supervision.validators import validate_detections_fields
@dataclass
class Detections:
"""
The `sv.Detections` allows you to convert results from a variety of object detection
and segmentation models into a single, unified format. The `sv.Detections` class
enables easy data manipulation and filtering, and provides a consistent API for
Supervision's tools like trackers, annotators, and zones.
The `sv.Detections` class in the Supervision library standardizes results from
various object detection and segmentation models into a consistent format. This
class simplifies data manipulation and filtering, providing a uniform API for
integration with Supervision [trackers](/trackers/), [annotators](/detection/annotators/), and [tools](/detection/tools/line_zone/).
```python
import cv2
import supervision as sv
from ultralytics import YOLO
=== "Inference"
image = cv2.imread(<SOURCE_IMAGE_PATH>)
model = YOLO('yolov8s.pt')
annotator = sv.BoundingBoxAnnotator()
Use [`sv.Detections.from_inference`](/detection/core/#supervision.detection.core.Detections.from_inference)
method, which accepts model results from both detection and segmentation models.
result = model(image)[0]
detections = sv.Detections.from_ultralytics(result)
```python
import cv2
import supervision as sv
from inference import get_model
annotated_image = annotator.annotate(image, detections)
```
model = get_model(model_id="yolov8n-640")
image = cv2.imread(<SOURCE_IMAGE_PATH>)
results = model.infer(image)[0]
detections = sv.Detections.from_inference(results)
```
!!! tip
=== "Ultralytics"
In `sv.Detections`, detection data is categorized into two main field types:
fixed and custom. The fixed fields include `xyxy`, `mask`, `confidence`,
`class_id`, and `tracker_id`. For any additional data requirements, custom
fields come into play, stored in the data field. These custom fields are easily
accessible using the `detections[<FIELD_NAME>]` syntax, providing flexibility
for diverse data handling needs.
Use [`sv.Detections.from_ultralytics`](/detection/core/#supervision.detection.core.Detections.from_ultralytics)
method, which accepts model results from both detection and segmentation models.
```python
import cv2
import supervision as sv
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
image = cv2.imread(<SOURCE_IMAGE_PATH>)
results = model(image)[0]
detections = sv.Detections.from_ultralytics(results)
```
=== "Transformers"
Use [`sv.Detections.from_transformers`](/detection/core/#supervision.detection.core.Detections.from_transformers)
method, which accepts model results from both detection and segmentation models.
```python
import torch
import supervision as sv
from PIL import Image
from transformers import DetrImageProcessor, DetrForObjectDetection
processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")
image = Image.open(<SOURCE_IMAGE_PATH>)
inputs = processor(images=image, return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
width, height = image.size
target_size = torch.tensor([[height, width]])
results = processor.post_process_object_detection(
outputs=outputs, target_sizes=target_size)[0]
detections = sv.Detections.from_transformers(
transformers_results=results,
id2label=model.config.id2label)
```
Attributes:
xyxy (np.ndarray): An array of shape `(n, 4)` containing
@@ -70,15 +107,7 @@ class Detections:
data (Dict[str, Union[np.ndarray, List]]): A dictionary containing additional
data where each key is a string representing the data type, and the value
is either a NumPy array or a list of corresponding data.
!!! warning
The `data` field in the `sv.Detections` class is currently in an experimental
phase. Please be aware that its API and functionality are subject to change in
future updates as we continue to refine and improve its capabilities.
We encourage users to experiment with this feature and provide feedback, but
also to be prepared for potential modifications in upcoming releases.
"""
""" # noqa: E501 // docs
xyxy: np.ndarray
mask: Optional[np.ndarray] = None
@@ -177,8 +206,8 @@ class Detections:
@classmethod
def from_ultralytics(cls, ultralytics_results) -> Detections:
"""
Creates a Detections instance from a
[YOLOv8](https://github.com/ultralytics/ultralytics) inference result.
Creates a `sv.Detections` instance from a
[YOLOv8](https://github.com/ultralytics/ultralytics) inference result.
!!! Note
@@ -189,7 +218,7 @@ class Detections:
Args:
ultralytics_results (ultralytics.yolo.engine.results.Results):
The output Results instance from YOLOv8
The output Results instance from Ultralytics
Returns:
Detections: A new Detections object.
@@ -202,13 +231,16 @@ class Detections:
image = cv2.imread(<SOURCE_IMAGE_PATH>)
model = YOLO('yolov8s.pt')
result = model(image)[0]
detections = sv.Detections.from_ultralytics(result)
results = model(image)[0]
detections = sv.Detections.from_ultralytics(results)
```
!!! tip
Class names values can be accessed using `detections["class_name"]`.
""" # noqa: E501 // docs
if ultralytics_results.obb is not None:
if "obb" in ultralytics_results and ultralytics_results.obb is not None:
class_id = ultralytics_results.obb.cls.cpu().numpy().astype(int)
class_names = np.array([ultralytics_results.names[i] for i in class_id])
oriented_box_coordinates = ultralytics_results.obb.xyxyxyxy.cpu().numpy()
@@ -389,31 +421,79 @@ class Detections:
)
@classmethod
def from_transformers(cls, transformers_results: dict) -> Detections:
def from_transformers(
cls, transformers_results: dict, id2label: Optional[Dict[int, str]] = None
) -> Detections:
"""
Creates a Detections instance from object detection or segmentation
[transformer](https://github.com/huggingface/transformers) inference result.
[Transformer](https://github.com/huggingface/transformers) inference result.
Args:
transformers_results (dict): The output of Transformers model inference. A
dictionary containing the `scores`, `labels`, `boxes` and `masks` keys.
id2label (Optional[Dict[int, str]]): A dictionary mapping class IDs to
class names. If provided, the resulting Detections object will contain
`class_name` data field with the class names.
Returns:
Detections: A new Detections object.
"""
boxes = transformers_results.get("boxes")
# If the boxes key is in the transformers_results then we know it's an
# object detection result. Else, we can assume it's a segmentation model
if boxes:
return cls(
xyxy=transformers_results["boxes"].cpu().numpy(),
confidence=transformers_results["scores"].cpu().numpy(),
class_id=transformers_results["labels"].cpu().numpy().astype(int),
Example:
```python
import torch
import supervision as sv
from PIL import Image
from transformers import DetrImageProcessor, DetrForObjectDetection
processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")
image = Image.open(<SOURCE_IMAGE_PATH>)
inputs = processor(images=image, return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
width, height = image.size
target_size = torch.tensor([[height, width]])
results = processor.post_process_object_detection(
outputs=outputs, target_sizes=target_size)[0]
detections = sv.Detections.from_transformers(
transformers_results=results,
id2label=model.config.id2label
)
else:
masks = transformers_results["masks"].cpu().numpy().astype(bool)
```
!!! tip
Class names values can be accessed using `detections["class_name"]`.
""" # noqa: E501 // docs
class_ids = transformers_results["labels"].cpu().detach().numpy().astype(int)
data = {}
if id2label is not None:
class_names = np.array([id2label[class_id] for class_id in class_ids])
data[CLASS_NAME_DATA_FIELD] = class_names
if "boxes" in transformers_results:
return cls(
xyxy=transformers_results["boxes"].cpu().detach().numpy(),
confidence=transformers_results["scores"].cpu().detach().numpy(),
class_id=class_ids,
data=data,
)
elif "masks" in transformers_results:
masks = transformers_results["masks"].cpu().detach().numpy().astype(bool)
return cls(
xyxy=mask_to_xyxy(masks),
mask=masks,
confidence=transformers_results["scores"].cpu().numpy(),
class_id=transformers_results["labels"].cpu().numpy().astype(int),
confidence=transformers_results["scores"].cpu().detach().numpy(),
class_id=class_ids,
data=data,
)
else:
raise NotImplementedError(
"Only object detection and semantic segmentation results are supported."
)
@classmethod
@@ -461,17 +541,12 @@ class Detections:
@classmethod
def from_inference(cls, roboflow_result: Union[dict, Any]) -> Detections:
"""
Create a Detections object from the [Roboflow](https://roboflow.com/)
Create a `sv.Detections` object from the [Roboflow](https://roboflow.com/)
API inference result or the [Inference](https://inference.roboflow.com/)
package results. This method extracts bounding boxes, class IDs,
confidences, and class names from the Roboflow API result and encapsulates
them into a Detections object.
!!! note
Class names can be accessed using the key 'class_name' in the returned
object's data attribute.
Args:
roboflow_result (dict, any): The result from the
Roboflow API or Inference package containing predictions.
@@ -484,14 +559,18 @@ class Detections:
```python
import cv2
import supervision as sv
from inference.models.utils import get_roboflow_model
from inference import get_model
image = cv2.imread(<SOURCE_IMAGE_PATH>)
model = get_roboflow_model(model_id="yolov8s-640")
model = get_model(model_id="yolov8s-640")
result = model.infer(image)[0]
detections = sv.Detections.from_inference(result)
```
!!! tip
Class names values can be accessed using `detections["class_name"]`.
"""
with suppress(AttributeError):
roboflow_result = roboflow_result.dict(exclude_none=True, by_alias=True)
@@ -541,10 +620,10 @@ class Detections:
```python
import cv2
import supervision as sv
from inference.models.utils import get_roboflow_model
from inference import get_model
image = cv2.imread(<SOURCE_IMAGE_PATH>)
model = get_roboflow_model(model_id="yolov8s-640")
model = get_model(model_id="yolov8s-640")
result = model.infer(image)[0]
detections = sv.Detections.from_roboflow(result)
+14 -6
View File
@@ -1,3 +1,4 @@
import warnings
from dataclasses import replace
from typing import Iterable, Optional, Tuple
@@ -11,7 +12,7 @@ from supervision.draw.color import Color
from supervision.draw.utils import draw_polygon, draw_text
from supervision.geometry.core import Position
from supervision.geometry.utils import get_polygon_center
from supervision.utils.internal import deprecated_parameter
from supervision.utils.internal import SupervisionWarnings, deprecated_parameter
class PolygonZone:
@@ -21,7 +22,6 @@ class PolygonZone:
Attributes:
polygon (np.ndarray): A polygon represented by a numpy array of shape
`(N, 2)`, containing the `x`, `y` coordinates of the points.
frame_resolution_wh (Tuple[int, int]): The frame resolution (width, height)
triggering_anchors (Iterable[sv.Position]): A list of positions specifying
which anchors of the detections bounding box to consider when deciding on
whether the detection fits within the PolygonZone
@@ -41,18 +41,26 @@ class PolygonZone:
def __init__(
self,
polygon: npt.NDArray[np.int64],
frame_resolution_wh: Tuple[int, int],
frame_resolution_wh: Optional[Tuple[int, int]] = None,
triggering_anchors: Iterable[Position] = (Position.BOTTOM_CENTER,),
):
if frame_resolution_wh is not None:
warnings.warn(
"The `frame_resolution_wh` parameter is no longer required and will be "
"dropped in version supervision-0.24.0. The mask resolution is now "
"calculated automatically based on the polygon coordinates.",
category=SupervisionWarnings,
)
self.polygon = polygon.astype(int)
self.frame_resolution_wh = frame_resolution_wh
self.triggering_anchors = triggering_anchors
self.current_count = 0
width, height = frame_resolution_wh
x_max, y_max = np.max(polygon, axis=0)
self.frame_resolution_wh = (x_max + 1, y_max + 1)
self.mask = polygon_to_mask(
polygon=polygon, resolution_wh=(width + 1, height + 1)
polygon=polygon, resolution_wh=(x_max + 2, y_max + 2)
)
def trigger(self, detections: Detections) -> npt.NDArray[np.bool_]:
+1 -97
View File
@@ -1,5 +1,5 @@
from itertools import chain
from typing import Any, Dict, List, Optional, Tuple, Union
from typing import Dict, List, Optional, Tuple, Union
import cv2
import numpy as np
@@ -656,102 +656,6 @@ def calculate_masks_centroids(masks: np.ndarray) -> np.ndarray:
return np.column_stack((centroid_x, centroid_y)).astype(int)
def validate_xyxy(xyxy: Any) -> None:
expected_shape = "(_, 4)"
actual_shape = str(getattr(xyxy, "shape", None))
is_valid = isinstance(xyxy, np.ndarray) and xyxy.ndim == 2 and xyxy.shape[1] == 4
if not is_valid:
raise ValueError(
f"xyxy must be a 2D np.ndarray with shape {expected_shape}, but got shape "
f"{actual_shape}"
)
def validate_mask(mask: Any, n: int) -> None:
expected_shape = f"({n}, H, W)"
actual_shape = str(getattr(mask, "shape", None))
is_valid = mask is None or (
isinstance(mask, np.ndarray) and len(mask.shape) == 3 and mask.shape[0] == n
)
if not is_valid:
raise ValueError(
f"mask must be a 3D np.ndarray with shape {expected_shape}, but got shape "
f"{actual_shape}"
)
def validate_class_id(class_id: Any, n: int) -> None:
expected_shape = f"({n},)"
actual_shape = str(getattr(class_id, "shape", None))
is_valid = class_id is None or (
isinstance(class_id, np.ndarray) and class_id.shape == (n,)
)
if not is_valid:
raise ValueError(
f"class_id must be a 1D np.ndarray with shape {expected_shape}, but got "
f"shape {actual_shape}"
)
def validate_confidence(confidence: Any, n: int) -> None:
expected_shape = f"({n},)"
actual_shape = str(getattr(confidence, "shape", None))
is_valid = confidence is None or (
isinstance(confidence, np.ndarray) and confidence.shape == (n,)
)
if not is_valid:
raise ValueError(
f"confidence must be a 1D np.ndarray with shape {expected_shape}, but got "
f"shape {actual_shape}"
)
def validate_tracker_id(tracker_id: Any, n: int) -> None:
expected_shape = f"({n},)"
actual_shape = str(getattr(tracker_id, "shape", None))
is_valid = tracker_id is None or (
isinstance(tracker_id, np.ndarray) and tracker_id.shape == (n,)
)
if not is_valid:
raise ValueError(
f"tracker_id must be a 1D np.ndarray with shape {expected_shape}, but got "
f"shape {actual_shape}"
)
def validate_data(data: Dict[str, Any], n: int) -> None:
for key, value in data.items():
if isinstance(value, list):
if len(value) != n:
raise ValueError(f"Length of list for key '{key}' must be {n}")
elif isinstance(value, np.ndarray):
if value.ndim == 1 and value.shape[0] != n:
raise ValueError(f"Shape of np.ndarray for key '{key}' must be ({n},)")
elif value.ndim > 1 and value.shape[0] != n:
raise ValueError(
f"First dimension of np.ndarray for key '{key}' must have size {n}"
)
else:
raise ValueError(f"Value for key '{key}' must be a list or np.ndarray")
def validate_detections_fields(
xyxy: Any,
mask: Any,
class_id: Any,
confidence: Any,
tracker_id: Any,
data: Dict[str, Any],
) -> None:
validate_xyxy(xyxy)
n = len(xyxy)
validate_mask(mask, n)
validate_class_id(class_id, n)
validate_confidence(confidence, n)
validate_tracker_id(tracker_id, n)
validate_data(data, n)
def is_data_equal(data_a: Dict[str, np.ndarray], data_b: Dict[str, np.ndarray]) -> bool:
"""
Compares the data payloads of two Detections instances.
+71 -3
View File
@@ -1,7 +1,7 @@
from __future__ import annotations
from dataclasses import dataclass
from typing import List, Tuple
from typing import List, Tuple, Union
import matplotlib.pyplot as plt
@@ -104,10 +104,13 @@ class Color:
Create a Color instance from a hex string.
Args:
color_hex (str): Hex string of the color.
color_hex (str): The hex string representing the color. This string can
start with '#' followed by either 3 or 6 hexadecimal characters. In
case of 3 characters, each character is repeated to form the full
6-character hex code.
Returns:
Color: Instance representing the color.
Color: An instance representing the color.
Example:
```python
@@ -115,6 +118,9 @@ class Color:
sv.Color.from_hex('#ff00ff')
# Color(r=255, g=0, b=255)
sv.Color.from_hex('#f0f')
# Color(r=255, g=0, b=255)
```
"""
_validate_color_hex(color_hex)
@@ -124,6 +130,52 @@ class Color:
r, g, b = (int(color_hex[i : i + 2], 16) for i in range(0, 6, 2))
return cls(r, g, b)
@classmethod
def from_rgb_tuple(cls, color_tuple: Tuple[int, int, int]) -> Color:
"""
Create a Color instance from an RGB tuple.
Args:
color_tuple (Tuple[int, int, int]): A tuple representing the color in RGB
format, where each element is an integer in the range 0-255.
Returns:
Color: An instance representing the color.
Example:
```python
import supervision as sv
sv.Color.from_rgb_tuple((255, 255, 0))
# Color(r=255, g=255, b=0)
```
"""
r, g, b = color_tuple
return cls(r=r, g=g, b=b)
@classmethod
def from_bgr_tuple(cls, color_tuple: Tuple[int, int, int]) -> Color:
"""
Create a Color instance from a BGR tuple.
Args:
color_tuple (Tuple[int, int, int]): A tuple representing the color in BGR
format, where each element is an integer in the range 0-255.
Returns:
Color: An instance representing the color.
Example:
```python
import supervision as sv
sv.Color.from_bgr_tuple((0, 255, 255))
# Color(r=255, g=255, b=0)
```
"""
b, g, r = color_tuple
return cls(r=r, g=g, b=b)
def as_hex(self) -> str:
"""
Converts the Color instance to a hex string.
@@ -396,3 +448,19 @@ class ColorPalette:
raise ValueError("idx argument should not be negative")
idx = idx % len(self.colors)
return self.colors[idx]
def unify_to_bgr(color: Union[Tuple[int, int, int], Color]) -> Tuple[int, int, int]:
"""
Converts a color input in multiple formats to a standardized BGR format.
Args:
color (Union[Tuple[int, int, int], Color]): The color input to be converted,
which can be either a tuple of RGB values or an instance of a Color class.
Returns:
Tuple[int, int, int]: The color in BGR format as a tuple of three integers.
"""
if issubclass(type(color), Color):
return color.as_bgr()
return color
+18 -11
View File
@@ -5,12 +5,8 @@ from supervision.geometry.core import Point
def get_polygon_center(polygon: np.ndarray) -> Point:
"""
Calculate the center of a polygon.
This function takes in a polygon as a 2-dimensional numpy ndarray and
returns the center of the polygon as a Point object.
The center is calculated as the mean of the polygon's vertices along each axis,
and is rounded down to the nearest integer.
Calculate the center of a polygon. The center is calculated as the center
of the solid figure formed by the points of the polygon
Parameters:
polygon (np.ndarray): A 2-dimensional numpy ndarray representing the
@@ -22,13 +18,24 @@ def get_polygon_center(polygon: np.ndarray) -> Point:
Examples:
```python
from supervision.geometry.utils import get_polygon_center
import numpy as np
import supervision as sv
vertices = np.array([[0, 0], [0, 1], [1, 1], [1, 0]])
get_center(vertices)
Point(x=0.5, y=0.5)
polygon = np.array([[0, 0], [0, 2], [2, 2], [2, 0]])
sv.get_polygon_center(polygon=polygon)
# Point(x=1, y=1)
```
"""
center = np.mean(polygon, axis=0).astype(int)
# This is one of the 3 candidate algorithms considered for centroid calculation.
# For a more detailed discussion, see PR #1084 and commit eb33176
shift_polygon = np.roll(polygon, -1, axis=0)
signed_areas = np.cross(polygon, shift_polygon) / 2
if signed_areas.sum() == 0:
center = np.mean(polygon, axis=0).round()
return Point(x=center[0], y=center[1])
centroids = (polygon + shift_polygon) / 3.0
center = np.average(centroids, axis=0, weights=signed_areas).round()
return Point(x=center[0], y=center[1])
View File
+177
View File
@@ -0,0 +1,177 @@
from abc import ABC, abstractmethod
from logging import warn
from typing import List, Optional, Tuple
import cv2
import numpy as np
from supervision.annotators.base import ImageType
from supervision.draw.color import Color
from supervision.keypoint.core import KeyPoints
from supervision.keypoint.skeletons import SKELETONS_BY_VERTEX_COUNT
from supervision.utils.conversion import convert_for_annotation_method
class BaseKeyPointAnnotator(ABC):
@abstractmethod
def annotate(self, scene: ImageType, key_points: KeyPoints) -> ImageType:
pass
class VertexAnnotator(BaseKeyPointAnnotator):
"""
A class that specializes in drawing skeleton vertices on images. It uses
specified key points to determine the locations where the vertices should be
drawn.
"""
def __init__(
self,
color: Color = Color.ROBOFLOW,
radius: int = 4,
) -> None:
"""
Args:
color (Color, optional): The color to use for annotating key points.
radius (int, optional): The radius of the circles used to represent the key
points.
"""
self.color = color
self.radius = radius
@convert_for_annotation_method
def annotate(self, scene: ImageType, key_points: KeyPoints) -> ImageType:
"""
Annotates the given scene with skeleton vertices based on the provided key
points. It draws circles at each key point location.
Args:
scene (ImageType): The image where bounding boxes will be drawn. `ImageType`
is a flexible type, accepting either `numpy.ndarray` or
`PIL.Image.Image`.
key_points (KeyPoints): A collection of key points where each key point
consists of x and y coordinates.
Returns:
The annotated image, matching the type of `scene` (`numpy.ndarray`
or `PIL.Image.Image`)
Example:
```python
import supervision as sv
image = ...
key_points = sv.KeyPoints(...)
vertex_annotator = sv.VertexAnnotator(color=sv.Color.GREEN, radius=10)
annotated_frame = vertex_annotator.annotate(
scene=image.copy(),
key_points=key_points
)
```
![vertex-annotator-example](https://media.roboflow.com/
supervision-annotator-examples/vertex-annotator-example.png)
"""
if len(key_points) == 0:
return scene
for xy in key_points.xy:
for x, y in xy:
cv2.circle(
img=scene,
center=(int(x), int(y)),
radius=self.radius,
color=self.color.as_bgr(),
thickness=-1,
)
return scene
class EdgeAnnotator(BaseKeyPointAnnotator):
"""
A class that specializes in drawing skeleton edges on images using specified key
points. It connects key points with lines to form the skeleton structure.
"""
def __init__(
self,
color: Color = Color.ROBOFLOW,
thickness: int = 2,
edges: Optional[List[Tuple[int, int]]] = None,
) -> None:
"""
Args:
color (Color, optional): The color to use for the edges.
thickness (int, optional): The thickness of the edges.
edges (Optional[List[Tuple[int, int]]]): The edges to draw.
If set to `None`, will attempt to select automatically.
"""
self.color = color
self.thickness = thickness
self.edges = edges
@convert_for_annotation_method
def annotate(self, scene: ImageType, key_points: KeyPoints) -> ImageType:
"""
Annotates the given scene by drawing lines between specified key points to form
edges.
Args:
scene (ImageType): The image where bounding boxes will be drawn. `ImageType`
is a flexible type, accepting either `numpy.ndarray` or
`PIL.Image.Image`.
key_points (KeyPoints): A collection of key points where each key point
consists of x and y coordinates.
Returns:
Returns:
The annotated image, matching the type of `scene` (`numpy.ndarray`
or `PIL.Image.Image`)
Example:
```python
import supervision as sv
image = ...
key_points = sv.KeyPoints(...)
edge_annotator = sv.EdgeAnnotator(color=sv.Color.GREEN, thickness=5)
annotated_frame = edge_annotator.annotate(
scene=image.copy(),
key_points=key_points
)
```
![edge-annotator-example](https://media.roboflow.com/
supervision-annotator-examples/edge-annotator-example.png)
"""
if len(key_points) == 0:
return scene
for xy in key_points.xy:
edges = self.edges
if not edges:
edges = SKELETONS_BY_VERTEX_COUNT.get(len(xy))
if not edges:
warn(f"No skeleton found with {len(xy)} vertices")
return scene
for class_a, class_b in edges:
xy_a = xy[class_a - 1]
xy_b = xy[class_b - 1]
missing_a = np.allclose(xy_a, 0)
missing_b = np.allclose(xy_b, 0)
if missing_a or missing_b:
continue
cv2.line(
img=scene,
pt1=(int(xy_a[0]), int(xy_a[1])),
pt2=(int(xy_b[0]), int(xy_b[1])),
color=self.color.as_bgr(),
thickness=self.thickness,
)
return scene
+233
View File
@@ -0,0 +1,233 @@
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
import numpy as np
import numpy.typing as npt
from supervision.config import CLASS_NAME_DATA_FIELD
from supervision.detection.utils import get_data_item, is_data_equal
from supervision.validators import validate_keypoints_fields
@dataclass
class KeyPoints:
"""
The `sv.KeyPoints` class in the Supervision library standardizes results from
various keypoint detection and pose estimation models into a consistent format. This
class simplifies data manipulation and filtering, providing a uniform API for
integration with Supervision annotators.
=== "Ultralytics"
Use [`sv.KeyPoints.from_ultralytics`](/keypoint/core/#supervision.keypoint.core.KeyPoints.from_ultralytics)
method, which accepts model results.
```python
import cv2
import supervision as sv
from ultralytics import YOLO
image = cv2.imread(<SOURCE_IMAGE_PATH>)
model = YOLO('yolov8s-pose.pt')
result = model(image)[0]
key_points = sv.KeyPoints.from_ultralytics(result)
```
Attributes:
xy (np.ndarray): An array of shape `(n, 2)` containing
the bounding boxes coordinates in format `[x1, y1]`
confidence (Optional[np.ndarray]): An array of shape
`(n,)` containing the confidence scores of the keypoint keypoints.
class_id (Optional[np.ndarray]): An array of shape
`(n,)` containing the class ids of the keypoint keypoints.
data (Dict[str, Union[np.ndarray, List]]): A dictionary containing additional
data where each key is a string representing the data type, and the value
is either a NumPy array or a list of corresponding data.
""" # noqa: E501 // docs
xy: npt.NDArray[np.float32]
class_id: Optional[npt.NDArray[np.int_]] = None
confidence: Optional[npt.NDArray[np.float32]] = None
data: Dict[str, Union[npt.NDArray[Any], List]] = field(default_factory=dict)
def __post_init__(self):
validate_keypoints_fields(
xy=self.xy,
confidence=self.confidence,
class_id=self.class_id,
data=self.data,
)
def __len__(self) -> int:
"""
Returns the number of keypoints in the keypoints object.
"""
return len(self.xy)
def __iter__(
self,
) -> Iterator[
Tuple[
np.ndarray,
Optional[np.ndarray],
Optional[float],
Optional[int],
Optional[int],
Dict[str, Union[np.ndarray, List]],
]
]:
"""
Iterates over the Keypoint object and yield a tuple of
`(xy, confidence, class_id, data)` for each keypoint detection.
"""
for i in range(len(self.xy)):
yield (
self.xy[i],
self.confidence[i] if self.confidence is not None else None,
self.class_id[i] if self.class_id is not None else None,
get_data_item(self.data, i),
)
def __eq__(self, other: KeyPoints) -> bool:
return all(
[
np.array_equal(self.xy, other.xy),
np.array_equal(self.class_id, other.class_id),
np.array_equal(self.confidence, other.confidence),
is_data_equal(self.data, other.data),
]
)
@classmethod
def from_ultralytics(cls, ultralytics_results) -> KeyPoints:
"""
Creates a Keypoints instance from a
[YOLOv8](https://github.com/ultralytics/ultralytics) inference result.
Args:
ultralytics_results (ultralytics.engine.results.Keypoints):
The output Results instance from YOLOv8
Returns:
KeyPoints: A new Keypoints object.
Example:
```python
import cv2
import supervision as sv
from ultralytics import YOLO
image = cv2.imread(<SOURCE_IMAGE_PATH>)
model = YOLO('yolov8s-pose.pt')
result = model(image)[0]
keypoints = sv.KeyPoints.from_ultralytics(result)
```
"""
if ultralytics_results.keypoints.xy.numel() == 0:
return cls.empty()
xy = ultralytics_results.keypoints.xy.cpu().numpy()
class_id = ultralytics_results.boxes.cls.cpu().numpy().astype(int)
class_names = np.array([ultralytics_results.names[i] for i in class_id])
confidence = ultralytics_results.keypoints.conf.cpu().numpy()
data = {CLASS_NAME_DATA_FIELD: class_names}
return cls(xy, class_id, confidence, data)
def __getitem__(
self, index: Union[int, slice, List[int], np.ndarray, str]
) -> Union["KeyPoints", List, np.ndarray, None]:
"""
Get a subset of the KeyPoints object or access an item from its data field.
When provided with an integer, slice, list of integers, or a numpy array, this
method returns a new KeyPoints object that represents a subset of the original
keypoints. When provided with a string, it accesses the corresponding item in
the data dictionary.
Args:
index (Union[int, slice, List[int], np.ndarray, str]): The index, indices,
or key to access a subset of the KeyPoints or an item from the data.
Returns:
Union[KeyPoints, Any]: A subset of the KeyPoints object or an item from
the data field.
Example:
```python
import supervision as sv
keypoints = sv.KeyPoints()
first_detection = keypoints[0]
first_10_keypoints = keypoints[0:10]
some_keypoints = keypoints[[0, 2, 4]]
class_0_keypoints = keypoints[keypoints.class_id == 0]
high_confidence_keypoints = keypoints[keypoints.confidence > 0.5]
feature_vector = keypoints['feature_vector']
```
"""
if isinstance(index, str):
return self.data.get(index)
if isinstance(index, int):
index = [index]
return KeyPoints(
xy=self.xy[index],
confidence=self.confidence[index] if self.confidence is not None else None,
class_id=self.class_id[index] if self.class_id is not None else None,
data=get_data_item(self.data, index),
)
def __setitem__(self, key: str, value: Union[np.ndarray, List]):
"""
Set a value in the data dictionary of the KeyPoints object.
Args:
key (str): The key in the data dictionary to set.
value (Union[np.ndarray, List]): The value to set for the key.
Example:
```python
import cv2
import supervision as sv
from ultralytics import YOLO
image = cv2.imread(<SOURCE_IMAGE_PATH>)
model = YOLO('yolov8s.pt')
result = model(image)[0]
keypoints = sv.KeyPoints.from_ultralytics(result)
keypoints['names'] = [
model.model.names[class_id]
for class_id
in keypoints.class_id
]
```
"""
if not isinstance(value, (np.ndarray, list)):
raise TypeError("Value must be a np.ndarray or a list")
if isinstance(value, list):
value = np.array(value)
self.data[key] = value
@classmethod
def empty(cls) -> KeyPoints:
"""
Create an empty Keypoints object with no keypoints.
Returns:
(KeyPoints): An empty Keypoints object.
Example:
```python
from supervision import Keypoints
empty_keypoints = Keypoints.empty()
```
"""
return cls(xy=np.empty((0, 0, 2), dtype=np.float32))
+36
View File
@@ -0,0 +1,36 @@
from enum import Enum
from typing import Dict, List, Tuple
Edges = List[Tuple[int, int]]
class Skeleton(Enum):
COCO = [
(1, 2),
(1, 3),
(2, 3),
(2, 4),
(3, 5),
(6, 12),
(6, 7),
(6, 8),
(7, 13),
(7, 9),
(8, 10),
(9, 11),
(12, 13),
(14, 12),
(15, 13),
(16, 14),
(17, 15),
]
SKELETONS_BY_EDGE_COUNT: Dict[int, Edges] = {}
SKELETONS_BY_VERTEX_COUNT: Dict[int, Edges] = {}
for skeleton in Skeleton:
SKELETONS_BY_EDGE_COUNT[len(skeleton.value)] = skeleton.value
unique_vertices = set(vertex for edge in skeleton.value for vertex in edge)
SKELETONS_BY_VERTEX_COUNT[len(unique_vertices)] = skeleton.value
+103
View File
@@ -0,0 +1,103 @@
from functools import wraps
from typing import List
import cv2
import numpy as np
from PIL import Image
from supervision.annotators.base import ImageType
def convert_for_annotation_method(annotate_func):
"""
Decorates `BaseAnnotator.annotate` implementations, converts scene to
an image type used internally by the annotators, converts back when annotation
is complete.
"""
@wraps(annotate_func)
def wrapper(self, scene: ImageType, *args, **kwargs):
if isinstance(scene, np.ndarray):
return annotate_func(self, scene, *args, **kwargs)
if isinstance(scene, Image.Image):
scene = pillow_to_cv2(scene)
annotated = annotate_func(self, scene, *args, **kwargs)
return cv2_to_pillow(image=annotated)
raise ValueError(f"Unsupported image type: {type(scene)}")
return wrapper
def convert_for_image_processing(image_processing_fun):
"""
Decorates image processing functions that accept np.ndarray, converting `image` to
np.ndarray, converts back when processing is complete.
"""
@wraps(image_processing_fun)
def wrapper(image: ImageType, *args, **kwargs):
if isinstance(image, np.ndarray):
return image_processing_fun(image, *args, **kwargs)
if isinstance(image, Image.Image):
scene = pillow_to_cv2(image)
annotated = image_processing_fun(scene, *args, **kwargs)
return cv2_to_pillow(image=annotated)
raise ValueError(f"Unsupported image type: {type(image)}")
return wrapper
def images_to_cv2(images: List[ImageType]) -> List[np.ndarray]:
"""
Converts images provided either as Pillow images or OpenCV
images into OpenCV format.
Args:
images (List[ImageType]): Images to be converted
Returns:
List[np.ndarray]: List of input images in OpenCV format
(with order preserved).
"""
result = []
for image in images:
if issubclass(type(image), Image.Image):
image = pillow_to_cv2(image=image)
result.append(image)
return result
def pillow_to_cv2(image: Image.Image) -> np.ndarray:
"""
Converts Pillow image into OpenCV image, handling RGB -> BGR
conversion.
Args:
image (Image.Image): Pillow image (in RGB format).
Returns:
(np.ndarray): Input image converted to OpenCV format.
"""
scene = np.array(image)
scene = cv2.cvtColor(scene, cv2.COLOR_RGB2BGR)
return scene
def cv2_to_pillow(image: np.ndarray) -> Image.Image:
"""
Converts OpenCV image into Pillow image, handling BGR -> RGB
conversion.
Args:
image (np.ndarray): OpenCV image (in BGR format).
Returns:
(Image.Image): Input image converted to Pillow format.
"""
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
return Image.fromarray(image)
+652 -54
View File
@@ -1,107 +1,351 @@
import itertools
import math
import os
import shutil
from typing import Optional, Tuple
from functools import partial
from typing import Callable, List, Literal, Optional, Tuple, Union
import cv2
import numpy as np
import numpy.typing as npt
from supervision.annotators.base import ImageType
from supervision.draw.color import Color, unify_to_bgr
from supervision.draw.utils import calculate_optimal_text_scale, draw_text
from supervision.geometry.core import Point
from supervision.utils.conversion import (
convert_for_image_processing,
cv2_to_pillow,
images_to_cv2,
)
from supervision.utils.iterables import create_batches, fill
RelativePosition = Literal["top", "bottom"]
MAX_COLUMNS_FOR_SINGLE_ROW_GRID = 3
def crop_image(image: np.ndarray, xyxy: np.ndarray) -> np.ndarray:
@convert_for_image_processing
def crop_image(
image: ImageType,
xyxy: Union[npt.NDArray[int], List[int], Tuple[int, int, int, int]],
) -> ImageType:
"""
Crops the given image based on the given bounding box.
Args:
image (np.ndarray): The image to be cropped, represented as a numpy array.
xyxy (np.ndarray): A numpy array containing the bounding box coordinates
in the format (x1, y1, x2, y2).
image (ImageType): The image to be cropped. `ImageType` is a flexible type,
accepting either `numpy.ndarray` or `PIL.Image.Image`.
xyxy (Union[np.ndarray, List[int], Tuple[int, int, int, int]]): A bounding box
coordinates in the format `(x_min, y_min, x_max, y_max)`, accepted as either
a `numpy.ndarray`, a `list`, or a `tuple`.
Returns:
(np.ndarray): The cropped image as a numpy array.
(ImageType): The cropped image. The type is determined by the input type and
may be either a `numpy.ndarray` or `PIL.Image.Image`.
=== "OpenCV"
Examples:
```python
import cv2
import supervision as sv
detection = sv.Detections(...)
with sv.ImageSink(target_dir_path='target/directory/path') as sink:
for xyxy in detection.xyxy:
cropped_image = sv.crop_image(image=image, xyxy=xyxy)
sink.save_image(image=cropped_image)
image = cv2.imread(<SOURCE_IMAGE_PATH>)
image.shape
# (1080, 1920, 3)
xyxy = [200, 400, 600, 800]
cropped_image = sv.crop_image(image=image, xyxy=xyxy)
cropped_image.shape
# (400, 400, 3)
```
"""
=== "Pillow"
```python
from PIL import Image
import supervision as sv
image = Image.open(<SOURCE_IMAGE_PATH>)
image.size
# (1920, 1080)
xyxy = [200, 400, 600, 800]
cropped_image = sv.crop_image(image=image, xyxy=xyxy)
cropped_image.size
# (400, 400)
```
![crop_image](https://media.roboflow.com/supervision-docs/crop-image.png){ align=center width="800" }
""" # noqa E501 // docs
if isinstance(xyxy, (list, tuple)):
xyxy = np.array(xyxy)
xyxy = np.round(xyxy).astype(int)
x1, y1, x2, y2 = xyxy
return image[y1:y2, x1:x2]
x_min, y_min, x_max, y_max = xyxy.flatten()
return image[y_min:y_max, x_min:x_max]
def resize_image(image: np.ndarray, scale_factor: float) -> np.ndarray:
@convert_for_image_processing
def scale_image(image: ImageType, scale_factor: float) -> ImageType:
"""
Resizes an image by a given scale factor using cv2.INTER_LINEAR interpolation.
Scales the given image based on the given scale factor.
Args:
image (np.ndarray): The input image to be resized.
scale_factor (float): The factor by which the image will be scaled. Scale factor
> 1.0 zooms in, < 1.0 zooms out.
image (ImageType): The image to be scaled. `ImageType` is a flexible type,
accepting either `numpy.ndarray` or `PIL.Image.Image`.
scale_factor (float): The factor by which the image will be scaled. Scale
factor > `1.0` zooms in, < `1.0` zooms out.
Returns:
np.ndarray: The resized image.
(ImageType): The scaled image. The type is determined by the input type and
may be either a `numpy.ndarray` or `PIL.Image.Image`.
Raises:
ValueError: If the scale factor is non-positive.
=== "OpenCV"
```python
import cv2
import supervision as sv
image = cv2.imread(<SOURCE_IMAGE_PATH>)
image.shape
# (1080, 1920, 3)
scaled_image = sv.scale_image(image=image, scale_factor=0.5)
scaled_image.shape
# (540, 960, 3)
```
=== "Pillow"
```python
from PIL import Image
import supervision as sv
image = Image.open(<SOURCE_IMAGE_PATH>)
image.size
# (1920, 1080)
scaled_image = sv.scale_image(image=image, scale_factor=0.5)
scaled_image.size
# (960, 540)
```
"""
if scale_factor <= 0:
raise ValueError("Scale factor must be positive.")
old_width, old_height = image.shape[1], image.shape[0]
nwe_width = int(old_width * scale_factor)
new_height = int(old_height * scale_factor)
return cv2.resize(image, (nwe_width, new_height), interpolation=cv2.INTER_LINEAR)
width_old, height_old = image.shape[1], image.shape[0]
width_new = int(width_old * scale_factor)
height_new = int(height_old * scale_factor)
return cv2.resize(image, (width_new, height_new), interpolation=cv2.INTER_LINEAR)
def place_image(
scene: np.ndarray, image: np.ndarray, anchor: Tuple[int, int]
) -> np.ndarray:
@convert_for_image_processing
def resize_image(
image: ImageType,
resolution_wh: Tuple[int, int],
keep_aspect_ratio: bool = False,
) -> ImageType:
"""
Resizes the given image to a specified resolution. Can maintain the original aspect
ratio or resize directly to the desired dimensions.
Args:
image (ImageType): The image to be resized. `ImageType` is a flexible type,
accepting either `numpy.ndarray` or `PIL.Image.Image`.
resolution_wh (Tuple[int, int]): The target resolution as
`(width, height)`.
keep_aspect_ratio (bool, optional): Flag to maintain the image's original
aspect ratio. Defaults to `False`.
Returns:
(ImageType): The resized image. The type is determined by the input type and
may be either a `numpy.ndarray` or `PIL.Image.Image`.
=== "OpenCV"
```python
import cv2
import supervision as sv
image = cv2.imread(<SOURCE_IMAGE_PATH>)
image.shape
# (1080, 1920, 3)
resized_image = sv.resize_image(
image=image, resolution_wh=(1000, 1000), keep_aspect_ratio=True
)
resized_image.shape
# (562, 1000, 3)
```
=== "Pillow"
```python
from PIL import Image
import supervision as sv
image = Image.open(<SOURCE_IMAGE_PATH>)
image.size
# (1920, 1080)
resized_image = sv.resize_image(
image=image, resolution_wh=(1000, 1000), keep_aspect_ratio=True
)
resized_image.size
# (1000, 562)
```
![resize_image](https://media.roboflow.com/supervision-docs/resize-image.png){ align=center width="800" }
""" # noqa E501 // docs
if keep_aspect_ratio:
image_ratio = image.shape[1] / image.shape[0]
target_ratio = resolution_wh[0] / resolution_wh[1]
if image_ratio >= target_ratio:
width_new = resolution_wh[0]
height_new = int(resolution_wh[0] / image_ratio)
else:
height_new = resolution_wh[1]
width_new = int(resolution_wh[1] * image_ratio)
else:
width_new, height_new = resolution_wh
return cv2.resize(image, (width_new, height_new), interpolation=cv2.INTER_LINEAR)
@convert_for_image_processing
def letterbox_image(
image: ImageType,
resolution_wh: Tuple[int, int],
color: Union[Tuple[int, int, int], Color] = Color.BLACK,
) -> ImageType:
"""
Resizes and pads an image to a specified resolution with a given color, maintaining
the original aspect ratio.
Args:
image (ImageType): The image to be resized. `ImageType` is a flexible type,
accepting either `numpy.ndarray` or `PIL.Image.Image`.
resolution_wh (Tuple[int, int]): The target resolution as
`(width, height)`.
color (Union[Tuple[int, int, int], Color]): The color to pad with. If tuple
provided it should be in BGR format.
Returns:
(ImageType): The resized image. The type is determined by the input type and
may be either a `numpy.ndarray` or `PIL.Image.Image`.
=== "OpenCV"
```python
import cv2
import supervision as sv
image = cv2.imread(<SOURCE_IMAGE_PATH>)
image.shape
# (1080, 1920, 3)
letterboxed_image = sv.letterbox_image(image=image, resolution_wh=(1000, 1000))
letterboxed_image.shape
# (1000, 1000, 3)
```
=== "Pillow"
```python
from PIL import Image
import supervision as sv
image = Image.open(<SOURCE_IMAGE_PATH>)
image.size
# (1920, 1080)
letterboxed_image = sv.letterbox_image(image=image, resolution_wh=(1000, 1000))
letterboxed_image.size
# (1000, 1000)
```
![letterbox_image](https://media.roboflow.com/supervision-docs/letterbox-image.png){ align=center width="800" }
""" # noqa E501 // docs
color = unify_to_bgr(color=color)
resized_image = resize_image(
image=image, resolution_wh=resolution_wh, keep_aspect_ratio=True
)
height_new, width_new = resized_image.shape[:2]
padding_top = (resolution_wh[1] - height_new) // 2
padding_bottom = resolution_wh[1] - height_new - padding_top
padding_left = (resolution_wh[0] - width_new) // 2
padding_right = resolution_wh[0] - width_new - padding_left
return cv2.copyMakeBorder(
resized_image,
padding_top,
padding_bottom,
padding_left,
padding_right,
cv2.BORDER_CONSTANT,
value=color,
)
def overlay_image(
image: npt.NDArray[np.uint8],
overlay: npt.NDArray[np.uint8],
anchor: Tuple[int, int],
) -> npt.NDArray[np.uint8]:
"""
Places an image onto a scene at a given anchor point, handling cases where
the image's position is partially or completely outside the scene's bounds.
Args:
scene (np.ndarray): The background scene onto which the image is placed.
image (np.ndarray): The image to be placed onto the scene.
anchor (Tuple[int, int]): The (x, y) coordinates in the scene where the
image (np.ndarray): The background scene onto which the image is placed.
overlay (np.ndarray): The image to be placed onto the scene.
anchor (Tuple[int, int]): The `(x, y)` coordinates in the scene where the
top-left corner of the image will be placed.
Returns:
np.ndarray: The modified scene with the image placed at the anchor point,
or unchanged if the image placement is completely outside the scene.
"""
scene_height, scene_width = scene.shape[:2]
image_height, image_width = image.shape[:2]
(np.ndarray): The result image with overlay.
Examples:
```python
import cv2
import numpy as np
import supervision as sv
image = cv2.imread(<SOURCE_IMAGE_PATH>)
overlay = np.zeros((400, 400, 3), dtype=np.uint8)
result_image = sv.overlay_image(image=image, overlay=overlay, anchor=(200, 400))
```
![overlay_image](https://media.roboflow.com/supervision-docs/overlay-image.png){ align=center width="800" }
""" # noqa E501 // docs
scene_height, scene_width = image.shape[:2]
image_height, image_width = overlay.shape[:2]
anchor_x, anchor_y = anchor
is_out_horizontally = anchor_x + image_width <= 0 or anchor_x >= scene_width
is_out_vertically = anchor_y + image_height <= 0 or anchor_y >= scene_height
if is_out_horizontally or is_out_vertically:
return scene
return image
start_y = max(anchor_y, 0)
start_x = max(anchor_x, 0)
end_y = min(scene_height, anchor_y + image_height)
end_x = min(scene_width, anchor_x + image_width)
x_min = max(anchor_x, 0)
y_min = max(anchor_y, 0)
x_max = min(scene_width, anchor_x + image_width)
y_max = min(scene_height, anchor_y + image_height)
crop_start_y = max(-anchor_y, 0)
crop_start_x = max(-anchor_x, 0)
crop_end_y = image_height - max((anchor_y + image_height) - scene_height, 0)
crop_end_x = image_width - max((anchor_x + image_width) - scene_width, 0)
crop_x_min = max(-anchor_x, 0)
crop_y_min = max(-anchor_y, 0)
crop_x_max = image_width - max((anchor_x + image_width) - scene_width, 0)
crop_y_max = image_height - max((anchor_y + image_height) - scene_height, 0)
scene[start_y:end_y, start_x:end_x] = image[
crop_start_y:crop_end_y, crop_start_x:crop_end_x
image[y_min:y_max, x_min:x_max] = overlay[
crop_y_min:crop_y_max, crop_x_min:crop_x_max
]
return scene
return image
class ImageSink:
@@ -125,13 +369,13 @@ class ImageSink:
```python
import supervision as sv
with sv.ImageSink(target_dir_path='target/directory/path',
overwrite=True) as sink:
for image in sv.get_video_frames_generator(
source_path='source_video.mp4', stride=2):
frames_generator = sv.get_video_frames_generator(<SOURCE_VIDEO_PATH>, stride=2)
with sv.ImageSink(target_dir_path=<TARGET_CROPS_DIRECTORY>) as sink:
for image in frames_generator:
sink.save_image(image=image)
```
"""
""" # noqa E501 // docs
self.target_dir_path = target_dir_path
self.overwrite = overwrite
@@ -168,3 +412,357 @@ class ImageSink:
def __exit__(self, exc_type, exc_value, exc_traceback):
pass
def create_tiles(
images: List[ImageType],
grid_size: Optional[Tuple[Optional[int], Optional[int]]] = None,
single_tile_size: Optional[Tuple[int, int]] = None,
tile_scaling: Literal["min", "max", "avg"] = "avg",
tile_padding_color: Union[Tuple[int, int, int], Color] = Color.from_hex("#D9D9D9"),
tile_margin: int = 10,
tile_margin_color: Union[Tuple[int, int, int], Color] = Color.from_hex("#BFBEBD"),
return_type: Literal["auto", "cv2", "pillow"] = "auto",
titles: Optional[List[Optional[str]]] = None,
titles_anchors: Optional[Union[Point, List[Optional[Point]]]] = None,
titles_color: Union[Tuple[int, int, int], Color] = Color.from_hex("#262523"),
titles_scale: Optional[float] = None,
titles_thickness: int = 1,
titles_padding: int = 10,
titles_text_font: int = cv2.FONT_HERSHEY_SIMPLEX,
titles_background_color: Union[Tuple[int, int, int], Color] = Color.from_hex(
"#D9D9D9"
),
default_title_placement: RelativePosition = "top",
) -> ImageType:
"""
Creates tiles mosaic from input images, automating grid placement and
converting images to common resolution maintaining aspect ratio. It is
also possible to render text titles on tiles, using optional set of
parameters specifying text drawing (see parameters description).
Automated grid placement will try to maintain square shape of grid
(with size being the nearest integer square root of #images), up to two exceptions:
* if there are up to 3 images - images will be displayed in single row
* if square-grid placement causes last row to be empty - number of rows is trimmed
until last row has at least one image
Args:
images (List[ImageType]): Images to create tiles. Elements can be either
np.ndarray or PIL.Image, common representation will be agreed by the
function.
grid_size (Optional[Tuple[Optional[int], Optional[int]]]): Expected grid
size in format (n_rows, n_cols). If not given - automated grid placement
will be applied. One may also provide only one out of two elements of the
tuple - then grid will be created with either n_rows or n_cols fixed,
leaving the other dimension to be adjusted by the number of images
single_tile_size (Optional[Tuple[int, int]]): sizeof a single tile element
provided in (width, height) format. If not given - size of tile will be
automatically calculated based on `tile_scaling` parameter.
tile_scaling (Literal["min", "max", "avg"]): If `single_tile_size` is not
given - parameter will be used to calculate tile size - using
min / max / avg size of image provided in `images` list.
tile_padding_color (Union[Tuple[int, int, int], sv.Color]): Color to be used in
images letterbox procedure (while standardising tiles sizes) as a padding.
If tuple provided - should be BGR.
tile_margin (int): size of margin between tiles (in pixels)
tile_margin_color (Union[Tuple[int, int, int], sv.Color]): Color of tile margin.
If tuple provided - should be BGR.
return_type (Literal["auto", "cv2", "pillow"]): Parameter dictates the format of
return image. One may choose specific type ("cv2" or "pillow") to enforce
conversion. "auto" mode takes a majority vote between types of elements in
`images` list - resolving draws in favour of OpenCV format. "auto" can be
safely used when all input images are of the same type.
titles (Optional[List[Optional[str]]]): Optional titles to be added to tiles.
Elements of that list may be empty - then specific tile (in order presented
in `images` parameter) will not be filled with title. It is possible to
provide list of titles shorter than `images` - then remaining titles will
be assumed empty.
titles_anchors (Optional[Union[Point, List[Optional[Point]]]]): Parameter to
specify anchor points for titles. It is possible to specify anchor either
globally or for specific tiles (following order of `images`).
If not given (either globally, or for specific element of the list),
it will be calculated automatically based on `default_title_placement`.
titles_color (Union[Tuple[int, int, int], Color]): Color of titles text.
If tuple provided - should be BGR.
titles_scale (Optional[float]): Scale of titles. If not provided - value will
be calculated using `calculate_optimal_text_scale(...)`.
titles_thickness (int): Thickness of titles text.
titles_padding (int): Size of titles padding.
titles_text_font (int): Font to be used to render titles. Must be integer
constant representing OpenCV font.
(See docs: https://docs.opencv.org/4.x/d6/d6e/group__imgproc__draw.html)
titles_background_color (Union[Tuple[int, int, int], Color]): Color of title
text padding.
default_title_placement (Literal["top", "bottom"]): Parameter specifies title
anchor placement in case if explicit anchor is not provided.
Returns:
ImageType: Image with all input images located in tails grid. The output type is
determined by `return_type` parameter.
Raises:
ValueError: In case when input images list is empty, provided `grid_size` is too
small to fit all images, `tile_scaling` mode is invalid.
"""
if len(images) == 0:
raise ValueError("Could not create image tiles from empty list of images.")
if return_type == "auto":
return_type = _negotiate_tiles_format(images=images)
tile_padding_color = unify_to_bgr(color=tile_padding_color)
tile_margin_color = unify_to_bgr(color=tile_margin_color)
images = images_to_cv2(images=images)
if single_tile_size is None:
single_tile_size = _aggregate_images_shape(images=images, mode=tile_scaling)
resized_images = [
letterbox_image(
image=i, resolution_wh=single_tile_size, color=tile_padding_color
)
for i in images
]
grid_size = _establish_grid_size(images=images, grid_size=grid_size)
if len(images) > grid_size[0] * grid_size[1]:
raise ValueError(
f"Could not place {len(images)} in grid with size: {grid_size}."
)
if titles is not None:
titles = fill(sequence=titles, desired_size=len(images), content=None)
titles_anchors = (
[titles_anchors]
if not issubclass(type(titles_anchors), list)
else titles_anchors
)
titles_anchors = fill(
sequence=titles_anchors, desired_size=len(images), content=None
)
titles_color = unify_to_bgr(color=titles_color)
titles_background_color = unify_to_bgr(color=titles_background_color)
tiles = _generate_tiles(
images=resized_images,
grid_size=grid_size,
single_tile_size=single_tile_size,
tile_padding_color=tile_padding_color,
tile_margin=tile_margin,
tile_margin_color=tile_margin_color,
titles=titles,
titles_anchors=titles_anchors,
titles_color=titles_color,
titles_scale=titles_scale,
titles_thickness=titles_thickness,
titles_padding=titles_padding,
titles_text_font=titles_text_font,
titles_background_color=titles_background_color,
default_title_placement=default_title_placement,
)
if return_type == "pillow":
tiles = cv2_to_pillow(image=tiles)
return tiles
def _negotiate_tiles_format(images: List[ImageType]) -> Literal["cv2", "pillow"]:
number_of_np_arrays = sum(issubclass(type(i), np.ndarray) for i in images)
if number_of_np_arrays >= (len(images) // 2):
return "cv2"
return "pillow"
def _calculate_aggregated_images_shape(
images: List[np.ndarray], aggregator: Callable[[List[int]], float]
) -> Tuple[int, int]:
height = round(aggregator([i.shape[0] for i in images]))
width = round(aggregator([i.shape[1] for i in images]))
return width, height
SHAPE_AGGREGATION_FUN = {
"min": partial(_calculate_aggregated_images_shape, aggregator=np.min),
"max": partial(_calculate_aggregated_images_shape, aggregator=np.max),
"avg": partial(_calculate_aggregated_images_shape, aggregator=np.average),
}
def _aggregate_images_shape(
images: List[np.ndarray], mode: Literal["min", "max", "avg"]
) -> Tuple[int, int]:
if mode not in SHAPE_AGGREGATION_FUN:
raise ValueError(
f"Could not aggregate images shape - provided unknown mode: {mode}. "
f"Supported modes: {list(SHAPE_AGGREGATION_FUN.keys())}."
)
return SHAPE_AGGREGATION_FUN[mode](images)
def _establish_grid_size(
images: List[np.ndarray], grid_size: Optional[Tuple[Optional[int], Optional[int]]]
) -> Tuple[int, int]:
if grid_size is None or all(e is None for e in grid_size):
return _negotiate_grid_size(images=images)
if grid_size[0] is None:
return math.ceil(len(images) / grid_size[1]), grid_size[1]
if grid_size[1] is None:
return grid_size[0], math.ceil(len(images) / grid_size[0])
return grid_size
def _negotiate_grid_size(images: List[np.ndarray]) -> Tuple[int, int]:
if len(images) <= MAX_COLUMNS_FOR_SINGLE_ROW_GRID:
return 1, len(images)
nearest_sqrt = math.ceil(np.sqrt(len(images)))
proposed_columns = nearest_sqrt
proposed_rows = nearest_sqrt
while proposed_columns * (proposed_rows - 1) >= len(images):
proposed_rows -= 1
return proposed_rows, proposed_columns
def _generate_tiles(
images: List[np.ndarray],
grid_size: Tuple[int, int],
single_tile_size: Tuple[int, int],
tile_padding_color: Tuple[int, int, int],
tile_margin: int,
tile_margin_color: Tuple[int, int, int],
titles: Optional[List[Optional[str]]],
titles_anchors: List[Optional[Point]],
titles_color: Tuple[int, int, int],
titles_scale: Optional[float],
titles_thickness: int,
titles_padding: int,
titles_text_font: int,
titles_background_color: Tuple[int, int, int],
default_title_placement: RelativePosition,
) -> np.ndarray:
images = _draw_texts(
images=images,
titles=titles,
titles_anchors=titles_anchors,
titles_color=titles_color,
titles_scale=titles_scale,
titles_thickness=titles_thickness,
titles_padding=titles_padding,
titles_text_font=titles_text_font,
titles_background_color=titles_background_color,
default_title_placement=default_title_placement,
)
rows, columns = grid_size
tiles_elements = list(create_batches(sequence=images, batch_size=columns))
while len(tiles_elements[-1]) < columns:
tiles_elements[-1].append(
_generate_color_image(shape=single_tile_size, color=tile_padding_color)
)
while len(tiles_elements) < rows:
tiles_elements.append(
[_generate_color_image(shape=single_tile_size, color=tile_padding_color)]
* columns
)
return _merge_tiles_elements(
tiles_elements=tiles_elements,
grid_size=grid_size,
single_tile_size=single_tile_size,
tile_margin=tile_margin,
tile_margin_color=tile_margin_color,
)
def _draw_texts(
images: List[np.ndarray],
titles: Optional[List[Optional[str]]],
titles_anchors: List[Optional[Point]],
titles_color: Tuple[int, int, int],
titles_scale: Optional[float],
titles_thickness: int,
titles_padding: int,
titles_text_font: int,
titles_background_color: Tuple[int, int, int],
default_title_placement: RelativePosition,
) -> List[np.ndarray]:
if titles is None:
return images
titles_anchors = _prepare_default_titles_anchors(
images=images,
titles_anchors=titles_anchors,
default_title_placement=default_title_placement,
)
if titles_scale is None:
image_height, image_width = images[0].shape[:2]
titles_scale = calculate_optimal_text_scale(
resolution_wh=(image_width, image_height)
)
result = []
for image, text, anchor in zip(images, titles, titles_anchors):
if text is None:
result.append(image)
continue
processed_image = draw_text(
scene=image,
text=text,
text_anchor=anchor,
text_color=Color.from_bgr_tuple(titles_color),
text_scale=titles_scale,
text_thickness=titles_thickness,
text_padding=titles_padding,
text_font=titles_text_font,
background_color=Color.from_bgr_tuple(titles_background_color),
)
result.append(processed_image)
return result
def _prepare_default_titles_anchors(
images: List[np.ndarray],
titles_anchors: List[Optional[Point]],
default_title_placement: RelativePosition,
) -> List[Point]:
result = []
for image, anchor in zip(images, titles_anchors):
if anchor is not None:
result.append(anchor)
continue
image_height, image_width = image.shape[:2]
if default_title_placement == "top":
default_anchor = Point(x=image_width / 2, y=image_height * 0.1)
else:
default_anchor = Point(x=image_width / 2, y=image_height * 0.9)
result.append(default_anchor)
return result
def _merge_tiles_elements(
tiles_elements: List[List[np.ndarray]],
grid_size: Tuple[int, int],
single_tile_size: Tuple[int, int],
tile_margin: int,
tile_margin_color: Tuple[int, int, int],
) -> np.ndarray:
vertical_padding = (
np.ones((single_tile_size[1], tile_margin, 3)) * tile_margin_color
)
merged_rows = [
np.concatenate(
list(
itertools.chain.from_iterable(
zip(row, [vertical_padding] * grid_size[1])
)
)[:-1],
axis=1,
)
for row in tiles_elements
]
row_width = merged_rows[0].shape[1]
horizontal_padding = (
np.ones((tile_margin, row_width, 3), dtype=np.uint8) * tile_margin_color
)
rows_with_paddings = []
for row in merged_rows:
rows_with_paddings.append(row)
rows_with_paddings.append(horizontal_padding)
return np.concatenate(
rows_with_paddings[:-1],
axis=0,
).astype(np.uint8)
def _generate_color_image(
shape: Tuple[int, int], color: Tuple[int, int, int]
) -> np.ndarray:
return np.ones(shape[::-1] + (3,), dtype=np.uint8) * color
+70
View File
@@ -0,0 +1,70 @@
from typing import Generator, Iterable, List, TypeVar
V = TypeVar("V")
def create_batches(
sequence: Iterable[V], batch_size: int
) -> Generator[List[V], None, None]:
"""
Provides a generator that yields chunks of the input sequence
of the size specified by the `batch_size` parameter. The last
chunk may be a smaller batch.
Args:
sequence (Iterable[V]): The sequence to be split into batches.
batch_size (int): The expected size of a batch.
Returns:
(Generator[List[V], None, None]): A generator that yields chunks
of `sequence` of size `batch_size`, up to the length of
the input `sequence`.
Examples:
```python
list(create_batches([1, 2, 3, 4, 5], 2))
# [[1, 2], [3, 4], [5]]
list(create_batches("abcde", 3))
# [['a', 'b', 'c'], ['d', 'e']]
```
"""
batch_size = max(batch_size, 1)
current_batch = []
for element in sequence:
if len(current_batch) == batch_size:
yield current_batch
current_batch = []
current_batch.append(element)
if current_batch:
yield current_batch
def fill(sequence: List[V], desired_size: int, content: V) -> List[V]:
"""
Fill the sequence with padding elements until the sequence reaches
the desired size.
Args:
sequence (List[V]): The input sequence.
desired_size (int): The expected size of the output list. The
difference between this value and the actual length of `sequence`
(if positive) dictates how many elements will be added as padding.
content (V): The element to be placed at the end of the input
`sequence` as padding.
Returns:
(List[V]): A padded version of the input `sequence` (if needed).
Examples:
```python
fill([1, 2], 4, 0)
# [1, 2, 0, 0]
fill(['a', 'b'], 3, 'c')
# ['a', 'b', 'c']
```
"""
missing_size = max(0, desired_size - len(sequence))
sequence.extend([content] * missing_size)
return sequence
+1 -1
View File
@@ -5,7 +5,7 @@ import matplotlib.pyplot as plt
from PIL import Image
from supervision.annotators.base import ImageType
from supervision.annotators.utils import pillow_to_cv2
from supervision.utils.conversion import pillow_to_cv2
def plot_image(
+141
View File
@@ -0,0 +1,141 @@
from typing import Any, Dict
import numpy as np
def validate_xyxy(xyxy: Any) -> None:
expected_shape = "(_, 4)"
actual_shape = str(getattr(xyxy, "shape", None))
is_valid = isinstance(xyxy, np.ndarray) and xyxy.ndim == 2 and xyxy.shape[1] == 4
if not is_valid:
raise ValueError(
f"xyxy must be a 2D np.ndarray with shape {expected_shape}, but got shape "
f"{actual_shape}"
)
def validate_mask(mask: Any, n: int) -> None:
expected_shape = f"({n}, H, W)"
actual_shape = str(getattr(mask, "shape", None))
is_valid = mask is None or (
isinstance(mask, np.ndarray) and len(mask.shape) == 3 and mask.shape[0] == n
)
if not is_valid:
raise ValueError(
f"mask must be a 3D np.ndarray with shape {expected_shape}, but got shape "
f"{actual_shape}"
)
def validate_class_id(class_id: Any, n: int) -> None:
expected_shape = f"({n},)"
actual_shape = str(getattr(class_id, "shape", None))
is_valid = class_id is None or (
isinstance(class_id, np.ndarray) and class_id.shape == (n,)
)
if not is_valid:
raise ValueError(
f"class_id must be a 1D np.ndarray with shape {expected_shape}, but got "
f"shape {actual_shape}"
)
def validate_confidence(confidence: Any, n: int) -> None:
expected_shape = f"({n},)"
actual_shape = str(getattr(confidence, "shape", None))
is_valid = confidence is None or (
isinstance(confidence, np.ndarray) and confidence.shape == (n,)
)
if not is_valid:
raise ValueError(
f"confidence must be a 1D np.ndarray with shape {expected_shape}, but got "
f"shape {actual_shape}"
)
def validate_keypoint_confidence(confidence: Any, n: int, m: int) -> None:
expected_shape = f"({n,m})"
actual_shape = str(getattr(confidence, "shape", None))
if confidence is not None:
is_valid = isinstance(confidence, np.ndarray) and confidence.shape == (n, m)
if not is_valid:
raise ValueError(
f"confidence must be a 1D np.ndarray with shape {expected_shape}, but "
"got"
f"shape {actual_shape}"
)
def validate_tracker_id(tracker_id: Any, n: int) -> None:
expected_shape = f"({n},)"
actual_shape = str(getattr(tracker_id, "shape", None))
is_valid = tracker_id is None or (
isinstance(tracker_id, np.ndarray) and tracker_id.shape == (n,)
)
if not is_valid:
raise ValueError(
f"tracker_id must be a 1D np.ndarray with shape {expected_shape}, but got "
f"shape {actual_shape}"
)
def validate_data(data: Dict[str, Any], n: int) -> None:
for key, value in data.items():
if isinstance(value, list):
if len(value) != n:
raise ValueError(f"Length of list for key '{key}' must be {n}")
elif isinstance(value, np.ndarray):
if value.ndim == 1 and value.shape[0] != n:
raise ValueError(f"Shape of np.ndarray for key '{key}' must be ({n},)")
elif value.ndim > 1 and value.shape[0] != n:
raise ValueError(
f"First dimension of np.ndarray for key '{key}' must have size {n}"
)
else:
raise ValueError(f"Value for key '{key}' must be a list or np.ndarray")
def validate_xy(xy: Any, n: int, m: int) -> None:
expected_shape = f"({n, m},)"
actual_shape = str(getattr(xy, "shape", None))
is_valid = isinstance(xy, np.ndarray) and (
xy.shape == (n, m, 2) or xy.shape == (n, m, 3)
)
if not is_valid:
raise ValueError(
f"xy must be a 2D np.ndarray with shape {expected_shape}, but got shape "
f"{actual_shape}"
)
def validate_detections_fields(
xyxy: Any,
mask: Any,
class_id: Any,
confidence: Any,
tracker_id: Any,
data: Dict[str, Any],
) -> None:
validate_xyxy(xyxy)
n = len(xyxy)
validate_mask(mask, n)
validate_class_id(class_id, n)
validate_confidence(confidence, n)
validate_tracker_id(tracker_id, n)
validate_data(data, n)
def validate_keypoints_fields(
xy: Any,
class_id: Any,
confidence: Any,
data: Dict[str, Any],
) -> None:
n = len(xy)
m = len(xy[0]) if len(xy) > 0 else 0
validate_xy(xy, n, m)
validate_class_id(class_id, n)
validate_keypoint_confidence(confidence, n, m)
validate_data(data, n)
+52
View File
@@ -0,0 +1,52 @@
import numpy as np
import pytest
from supervision.geometry.core import Point
from supervision.geometry.utils import get_polygon_center
def generate_test_polygon(n: int) -> np.ndarray:
"""
Generate a semicircle with a given number of points.
Parameters:
n (int): amount of points in polygon
Returns:
Polygon: test polygon in the form of a semicircle.
Examples:
```python
from supervision.geometry.utils import get_polygon_center
import numpy as np
test_polygon = generate_test_data(1000)
get_polygon_center(test_polygon)
Point(x=500, y=1212)
```
"""
r: int = n // 2
x_axis = np.linspace(0, 2 * r, n)
y_axis = (r**2 - (x_axis - r) ** 2) ** 0.5 + 2 * r
polygon = np.array([x_axis, y_axis]).T
return polygon
@pytest.mark.parametrize(
"polygon, expected_result",
[
(generate_test_polygon(10), Point(x=5.0, y=12.0)),
(generate_test_polygon(50), Point(x=25.0, y=61.0)),
(generate_test_polygon(100), Point(x=50.0, y=121.0)),
(generate_test_polygon(1000), Point(x=500.0, y=1212.0)),
(generate_test_polygon(3000), Point(x=1500.0, y=3637.0)),
(generate_test_polygon(10000), Point(x=5000.0, y=12122.0)),
(generate_test_polygon(20000), Point(x=10000.0, y=24244.0)),
(generate_test_polygon(50000), Point(x=25000.0, y=60610.0)),
],
)
def test_get_polygon_center(polygon: np.ndarray, expected_result: Point) -> None:
result = get_polygon_center(polygon)
assert result == expected_result
+20
View File
@@ -3,6 +3,7 @@ from typing import Any, Dict, List, Optional
import numpy as np
from supervision.detection.core import Detections
from supervision.keypoint.core import KeyPoints
def mock_detections(
@@ -30,5 +31,24 @@ def mock_detections(
)
def mock_keypoints(
xy: List[List[float]],
confidence: Optional[List[float]] = None,
class_id: Optional[List[int]] = None,
data: Optional[Dict[str, List[Any]]] = None,
) -> KeyPoints:
def convert_data(data: Dict[str, List[Any]]):
return {k: np.array(v) for k, v in data.items()}
return KeyPoints(
xy=np.array(xy, dtype=np.float32),
confidence=(
confidence if confidence is None else np.array(confidence, dtype=np.float32)
),
class_id=(class_id if class_id is None else np.array(class_id, dtype=int)),
data=convert_data(data) if data else {},
)
def assert_almost_equal(actual, expected, tolerance=1e-5):
assert abs(actual - expected) < tolerance, f"Expected {expected}, but got {actual}."
Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 329 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 328 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 332 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 334 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 323 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 266 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 213 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 141 KiB

+99
View File
@@ -0,0 +1,99 @@
import os
from typing import List
import cv2
import numpy as np
from _pytest.fixtures import fixture
from PIL import Image
ASSETS_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "assets"))
ALL_IMAGES_LIST = [os.path.join(ASSETS_DIR, f"{i}.jpg") for i in range(1, 6)]
@fixture(scope="function")
def empty_opencv_image() -> np.ndarray:
return np.zeros((128, 128, 3), dtype=np.uint8)
@fixture(scope="function")
def empty_pillow_image() -> Image.Image:
return Image.new(mode="RGB", size=(128, 128), color=(0, 0, 0))
@fixture(scope="function")
def all_images() -> List[np.ndarray]:
return [cv2.imread(path) for path in ALL_IMAGES_LIST]
@fixture(scope="function")
def one_image() -> np.ndarray:
return cv2.imread(ALL_IMAGES_LIST[0])
@fixture(scope="function")
def two_images() -> List[np.ndarray]:
return [cv2.imread(path) for path in ALL_IMAGES_LIST[:2]]
@fixture(scope="function")
def three_images() -> List[np.ndarray]:
return [cv2.imread(path) for path in ALL_IMAGES_LIST[:3]]
@fixture(scope="function")
def four_images() -> List[np.ndarray]:
return [cv2.imread(path) for path in ALL_IMAGES_LIST[:4]]
@fixture(scope="function")
def all_images_tile() -> np.ndarray:
return cv2.imread(os.path.join(ASSETS_DIR, "all_images_tile.png"))
@fixture(scope="function")
def all_images_tile_and_custom_colors() -> np.ndarray:
return cv2.imread(os.path.join(ASSETS_DIR, "all_images_tile_and_custom_colors.png"))
@fixture(scope="function")
def all_images_tile_and_custom_grid() -> np.ndarray:
return cv2.imread(os.path.join(ASSETS_DIR, "all_images_tile_and_custom_grid.png"))
@fixture(scope="function")
def four_images_tile() -> np.ndarray:
return cv2.imread(os.path.join(ASSETS_DIR, "four_images_tile.png"))
@fixture(scope="function")
def single_image_tile() -> np.ndarray:
return cv2.imread(os.path.join(ASSETS_DIR, "single_image_tile.png"))
@fixture(scope="function")
def single_image_tile_enforced_grid() -> np.ndarray:
return cv2.imread(os.path.join(ASSETS_DIR, "single_image_tile_enforced_grid.png"))
@fixture(scope="function")
def three_images_tile() -> np.ndarray:
return cv2.imread(os.path.join(ASSETS_DIR, "three_images_tile.png"))
@fixture(scope="function")
def two_images_tile() -> np.ndarray:
return cv2.imread(os.path.join(ASSETS_DIR, "two_images_tile.png"))
@fixture(scope="function")
def all_images_tile_and_custom_colors_and_titles() -> np.ndarray:
return cv2.imread(
os.path.join(ASSETS_DIR, "all_images_tile_and_custom_colors_and_titles.png")
)
@fixture(scope="function")
def all_images_tile_and_titles_with_custom_configs() -> np.ndarray:
return cv2.imread(
os.path.join(ASSETS_DIR, "all_images_tile_and_titles_with_custom_configs.png")
)
+173
View File
@@ -0,0 +1,173 @@
import numpy as np
from PIL import Image, ImageChops
from supervision.utils.conversion import (
convert_for_image_processing,
cv2_to_pillow,
images_to_cv2,
pillow_to_cv2,
)
def test_convert_for_image_processing_when_pillow_image_submitted(
empty_opencv_image: np.ndarray, empty_pillow_image: Image.Image
) -> None:
# given
param_a_value = 3
param_b_value = "some"
@convert_for_image_processing
def my_custom_processing_function(
image: np.ndarray,
param_a: int,
param_b: str,
) -> np.ndarray:
assert np.allclose(
image, empty_opencv_image
), "Expected conversion to OpenCV image to happen"
assert (
param_a == param_a_value
), f"Parameter a expected to be {param_a_value} in target function"
assert (
param_b == param_b_value
), f"Parameter b expected to be {param_b_value} in target function"
return image
# when
result = my_custom_processing_function(
empty_pillow_image,
param_a_value,
param_b=param_b_value,
)
# then
difference = ImageChops.difference(result, empty_pillow_image)
assert difference.getbbox() is None, (
"Wrapper is expected to convert-back the OpenCV image "
"into Pillow format without changes to content"
)
def test_convert_for_image_processing_when_opencv_image_submitted(
empty_opencv_image: np.ndarray,
) -> None:
# given
param_a_value = 3
param_b_value = "some"
@convert_for_image_processing
def my_custom_processing_function(
image: np.ndarray,
param_a: int,
param_b: str,
) -> np.ndarray:
assert np.allclose(
image, empty_opencv_image
), "Expected conversion to OpenCV image to happen"
assert (
param_a == param_a_value
), f"Parameter a expected to be {param_a_value} in target function"
assert (
param_b == param_b_value
), f"Parameter b expected to be {param_b_value} in target function"
return image
# when
result = my_custom_processing_function(
empty_opencv_image,
param_a_value,
param_b=param_b_value,
)
# then
assert (
result is empty_opencv_image
), "Expected to return OpenCV image without changes"
def test_cv2_to_pillow(
empty_opencv_image: np.ndarray, empty_pillow_image: Image.Image
) -> None:
# when
result = cv2_to_pillow(image=empty_opencv_image)
# then
difference = ImageChops.difference(result, empty_pillow_image)
assert (
difference.getbbox() is None
), "Conversion to PIL.Image expected not to change the content of image"
def test_pillow_to_cv2(
empty_opencv_image: np.ndarray, empty_pillow_image: Image.Image
) -> None:
# when
result = pillow_to_cv2(image=empty_pillow_image)
# then
assert np.allclose(
result, empty_opencv_image
), "Conversion to OpenCV image expected not to change the content of image"
def test_images_to_cv2_when_empty_input_provided() -> None:
# when
result = images_to_cv2(images=[])
# then
assert result == [], "Expected empty output when empty input provided"
def test_images_to_cv2_when_only_cv2_images_provided(
empty_opencv_image: np.ndarray,
) -> None:
# given
images = [empty_opencv_image] * 5
# when
result = images_to_cv2(images=images)
# then
assert len(result) == 5, "Expected the same number of output element as input ones"
for result_element in result:
assert (
result_element is empty_opencv_image
), "Expected CV images not to be touched by conversion"
def test_images_to_cv2_when_only_pillow_images_provided(
empty_pillow_image: Image.Image,
empty_opencv_image: np.ndarray,
) -> None:
# given
images = [empty_pillow_image] * 5
# when
result = images_to_cv2(images=images)
# then
assert len(result) == 5, "Expected the same number of output element as input ones"
for result_element in result:
assert np.allclose(
result_element, empty_opencv_image
), "Output images expected to be equal to empty OpenCV image"
def test_images_to_cv2_when_mixed_input_provided(
empty_pillow_image: Image.Image,
empty_opencv_image: np.ndarray,
) -> None:
# given
images = [empty_pillow_image, empty_opencv_image]
# when
result = images_to_cv2(images=images)
# then
assert len(result) == 2, "Expected the same number of output element as input ones"
assert np.allclose(
result[0], empty_opencv_image
), "PIL image should be converted to OpenCV one, equal to example empty image"
assert (
result[1] is empty_opencv_image
), "Expected CV images not to be touched by conversion"
+244
View File
@@ -0,0 +1,244 @@
from typing import List
import numpy as np
import pytest
from PIL import Image, ImageChops
from supervision import Color, Point
from supervision.utils.image import create_tiles, letterbox_image, resize_image
def test_resize_image_for_opencv_image() -> None:
# given
image = np.zeros((480, 640, 3), dtype=np.uint8)
expected_result = np.zeros((768, 1024, 3), dtype=np.uint8)
# when
result = resize_image(
image=image,
resolution_wh=(1024, 1024),
keep_aspect_ratio=True,
)
# then
assert np.allclose(
result, expected_result
), "Expected output shape to be (w, h): (1024, 768)"
def test_resize_image_for_pillow_image() -> None:
# given
image = Image.new(mode="RGB", size=(640, 480), color=(0, 0, 0))
expected_result = Image.new(mode="RGB", size=(1024, 768), color=(0, 0, 0))
# when
result = resize_image(
image=image,
resolution_wh=(1024, 1024),
keep_aspect_ratio=True,
)
# then
assert result.size == (1024, 768), "Expected output shape to be (w, h): (1024, 768)"
difference = ImageChops.difference(result, expected_result)
assert (
difference.getbbox() is None
), "Expected no difference in resized image content as the image is all zeros"
def test_letterbox_image_for_opencv_image() -> None:
# given
image = np.zeros((480, 640, 3), dtype=np.uint8)
expected_result = np.concatenate(
[
np.ones((128, 1024, 3), dtype=np.uint8) * 255,
np.zeros((768, 1024, 3), dtype=np.uint8),
np.ones((128, 1024, 3), dtype=np.uint8) * 255,
],
axis=0,
)
# when
result = letterbox_image(
image=image, resolution_wh=(1024, 1024), color=(255, 255, 255)
)
# then
assert np.allclose(result, expected_result), (
"Expected output shape to be (w, h): "
"(1024, 1024) with padding added top and bottom"
)
def test_letterbox_image_for_pillow_image() -> None:
# given
image = Image.new(mode="RGB", size=(640, 480), color=(0, 0, 0))
expected_result = Image.fromarray(
np.concatenate(
[
np.ones((128, 1024, 3), dtype=np.uint8) * 255,
np.zeros((768, 1024, 3), dtype=np.uint8),
np.ones((128, 1024, 3), dtype=np.uint8) * 255,
],
axis=0,
)
)
# when
result = letterbox_image(
image=image, resolution_wh=(1024, 1024), color=(255, 255, 255)
)
# then
assert result.size == (
1024,
1024,
), "Expected output shape to be (w, h): (1024, 1024)"
difference = ImageChops.difference(result, expected_result)
assert (
difference.getbbox() is None
), "Expected padding to be added top and bottom with padding added top and bottom"
def test_create_tiles_with_one_image(
one_image: np.ndarray, single_image_tile: np.ndarray
) -> None:
# when
result = create_tiles(images=[one_image], single_tile_size=(240, 240))
# # then
assert np.allclose(result, single_image_tile, atol=5.0)
def test_create_tiles_with_one_image_and_enforced_grid(
one_image: np.ndarray, single_image_tile_enforced_grid: np.ndarray
) -> None:
# when
result = create_tiles(
images=[one_image],
grid_size=(None, 3),
single_tile_size=(240, 240),
)
# then
assert np.allclose(result, single_image_tile_enforced_grid, atol=5.0)
def test_create_tiles_with_two_images(
two_images: List[np.ndarray], two_images_tile: np.ndarray
) -> None:
# when
result = create_tiles(images=two_images, single_tile_size=(240, 240))
# then
assert np.allclose(result, two_images_tile, atol=5.0)
def test_create_tiles_with_three_images(
three_images: List[np.ndarray], three_images_tile: np.ndarray
) -> None:
# when
result = create_tiles(images=three_images, single_tile_size=(240, 240))
# then
assert np.allclose(result, three_images_tile, atol=5.0)
def test_create_tiles_with_four_images(
four_images: List[np.ndarray],
four_images_tile: np.ndarray,
) -> None:
# when
result = create_tiles(images=four_images, single_tile_size=(240, 240))
# then
assert np.allclose(result, four_images_tile, atol=5.0)
def test_create_tiles_with_all_images(
all_images: List[np.ndarray],
all_images_tile: np.ndarray,
) -> None:
# when
result = create_tiles(images=all_images, single_tile_size=(240, 240))
# then
assert np.allclose(result, all_images_tile, atol=5.0)
def test_create_tiles_with_all_images_and_custom_grid(
all_images: List[np.ndarray], all_images_tile_and_custom_grid: np.ndarray
) -> None:
# when
result = create_tiles(
images=all_images,
grid_size=(3, 3),
single_tile_size=(240, 240),
)
# then
assert np.allclose(result, all_images_tile_and_custom_grid, atol=5.0)
def test_create_tiles_with_all_images_and_custom_colors(
all_images: List[np.ndarray], all_images_tile_and_custom_colors: np.ndarray
) -> None:
# when
result = create_tiles(
images=all_images,
tile_margin_color=(127, 127, 127),
tile_padding_color=(224, 224, 224),
single_tile_size=(240, 240),
)
# then
assert np.allclose(result, all_images_tile_and_custom_colors, atol=5.0)
def test_create_tiles_with_all_images_and_titles(
all_images: List[np.ndarray],
all_images_tile_and_custom_colors_and_titles: np.ndarray,
) -> None:
# when
result = create_tiles(
images=all_images,
titles=["Image 1", None, "Image 3", "Image 4"],
single_tile_size=(240, 240),
)
# then
assert np.allclose(result, all_images_tile_and_custom_colors_and_titles, atol=5.0)
def test_create_tiles_with_all_images_and_titles_with_custom_configs(
all_images: List[np.ndarray],
all_images_tile_and_titles_with_custom_configs: np.ndarray,
) -> None:
# when
result = create_tiles(
images=all_images,
titles=["Image 1", None, "Image 3", "Image 4"],
single_tile_size=(240, 240),
titles_anchors=[
Point(x=200, y=300),
Point(x=300, y=400),
None,
Point(x=300, y=400),
],
titles_color=Color.RED,
titles_scale=1.5,
titles_thickness=3,
titles_padding=20,
titles_background_color=Color.BLACK,
default_title_placement="bottom",
)
# then
assert np.allclose(result, all_images_tile_and_titles_with_custom_configs, atol=5.0)
def test_create_tiles_with_all_images_and_custom_grid_to_small_to_fit_images(
all_images: List[np.ndarray],
) -> None:
with pytest.raises(ValueError):
_ = create_tiles(images=all_images, grid_size=(2, 2))
+43
View File
@@ -0,0 +1,43 @@
import pytest
from supervision.utils.iterables import create_batches, fill
@pytest.mark.parametrize(
"sequence, batch_size, expected",
[
# Empty sequence, non-zero batch size. Expect empty list.
([], 4, []),
# Non-zero size sequence, batch size of 0. Each item is its own batch.
([1, 2, 3], 0, [[1], [2], [3]]),
# Batch size larger than sequence. All items in a single batch.
([1, 2], 4, [[1, 2]]),
# Batch size evenly divides the sequence. Equal size batches.
([1, 2, 3, 4], 2, [[1, 2], [3, 4]]),
# Batch size doesn't evenly divide sequence. Last batch smaller.
([1, 2, 3, 4], 3, [[1, 2, 3], [4]]),
],
)
def test_create_batches(sequence, batch_size, expected) -> None:
result = list(create_batches(sequence=sequence, batch_size=batch_size))
assert result == expected
@pytest.mark.parametrize(
"sequence, desired_size, content, expected",
[
# Empty sequence, desired size 0. Expect empty list.
([], 0, 1, []),
# Empty sequence, non-zero desired size. Filled with padding.
([], 3, 1, [1, 1, 1]),
# Sequence at desired size. No changes.
([2, 2, 2], 3, 1, [2, 2, 2]),
# Sequence exceeds desired size. No changes.
([2, 2, 2, 2], 3, 1, [2, 2, 2, 2]),
# Non-empty sequence, shorter than desired. Padding added.
([2], 3, 1, [2, 1, 1]),
],
)
def test_fill(sequence, desired_size, content, expected) -> None:
result = fill(sequence=sequence, desired_size=desired_size, content=content)
assert result == expected