Compare commits

...
866 Commits
Author SHA1 Message Date
Linas Kondrackis 93c1b947fc Merge pull request #1351 from roboflow/develop
`supervision-0.22.0` release
2024-07-12 19:59:08 +03:00
SkalskiP 66d1f4c67d bump version from 0.22.0rc1 to 0.22.0 2024-07-12 18:53:53 +02:00
Linas Kondrackis 70a13fbf1e Merge pull request #1342 from roboflow/release/supervision-0.22.0-deprecations
Deprecations, changelog, notebook cleanup, 'new' markers
2024-07-12 19:49:17 +03:00
SkalskiP 1db8e12e1b small changes 2024-07-12 18:47:41 +02:00
LinasKo 8853321058 Release process: push to 'main', not 'master' 2024-07-12 19:10:25 +03:00
LinasKo 0a5e830159 Add release process doc 2024-07-12 18:59:06 +03:00
pre-commit-ci[bot] fb041f9b6c fix(pre_commit): 🎨 auto format pre-commit hooks 2024-07-12 15:20:00 +00:00
LinasKo 28f83b18f9 Deprecate BoundingBoxAnnotator, rename to BoxAnnotator 2024-07-12 18:18:50 +03:00
LinasKo feb779bae9 Extended code examples in changelog 2024-07-12 15:48:07 +03:00
LinasKo 521dc57b76 Brief early mention that Dataset.images is deprecated 2024-07-12 15:18:20 +03:00
LinasKo a0775544df Fix typo: future deprecation will be removed, not 'were' removed 2024-07-12 15:11:17 +03:00
LinasKo 14a0e299a1 Changelog, reorder deprecations 2024-07-12 15:08:11 +03:00
LinasKo 1e783b623b Wording: <TTF_FONT_PATH> 2024-07-12 15:05:09 +03:00
LinasKo c7a8654390 deprections text: five subsequent release 2024-07-12 15:03:24 +03:00
Piotr Skalski a7f8aee2c7 Merge pull request #1332 from roboflow/feat/cheatsheet-links
Add cheatsheet links in supervision docs, readme
2024-07-12 13:25:15 +02:00
Piotr Skalski 5ed03491f9 Merge pull request #1327 from roboflow/fix/florence2-region-xyxy
Fix bug where florence2 returns normalized xyxy regions
2024-07-12 12:17:18 +02:00
LinasKo 5d979df2f9 Add CropAnnotator PR link 2024-07-12 01:19:46 +03:00
LinasKo 5006f8c2f7 Add heading to deprecations page 2024-07-12 00:19:46 +03:00
LinasKo 8570ce68e2 'new' marker on Detections/Utils 2024-07-12 00:18:21 +03:00
LinasKo 3d3bbb4095 Add recently removed deprecations 2024-07-12 00:08:12 +03:00
LinasKo a1e3543897 Redo demo.ipynb, quickstart.ipynb images 2024-07-12 00:04:48 +03:00
LinasKo 4b82679b00 Add to changelog: KeyPoints.from_detectron2, xcycwh_to_xyxy 2024-07-11 23:17:18 +03:00
Linas Kondrackis 5d4abe6e0d Merge pull request #1310 from onuralpszr/detectron2-keypoint
feat: 🚀 Keypoint support for detectron2
2024-07-11 14:58:21 +03:00
Piotr Skalski 0405c74cf3 Merge pull request #1340 from roboflow/feature/box_utils
`xywh_to_xyxy` and `xcycwh_to_xyxy` box utils
2024-07-11 11:20:19 +02:00
Onuralp SEZER 13fe6e0942 fix: 🐞 add check if keypoints size is 0 return empty keypoint result
Signed-off-by: Onuralp SEZER <thunderbirdtr@gmail.com>
2024-07-11 04:41:29 +03:00
Onuralp SEZER 03c92f7652 Merge pull request #1341 from roboflow/dependabot/pip/jupytext-1.16.3
⬆️ Bump jupytext from 1.16.2 to 1.16.3
2024-07-11 04:14:37 +03:00
LinasKo 084926ded3 Deprecations, changelog, notebook cleanup, 'new' markers 2024-07-11 03:21:41 +03:00
dependabot[bot] 382ed8e609 ⬆️ Bump jupytext from 1.16.2 to 1.16.3
Bumps [jupytext](https://github.com/mwouts/jupytext) from 1.16.2 to 1.16.3.
- [Release notes](https://github.com/mwouts/jupytext/releases)
- [Changelog](https://github.com/mwouts/jupytext/blob/main/CHANGELOG.md)
- [Commits](https://github.com/mwouts/jupytext/compare/v1.16.2...v1.16.3)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-07-11 00:17:30 +00:00
pre-commit-ci[bot] 2ed2a793cd fix(pre_commit): 🎨 auto format pre-commit hooks 2024-07-10 10:15:01 +00:00
SkalskiP e0fb73f18a xywh_to_xyxy and xcycwh_to_xyxy box utils 2024-07-10 12:13:07 +02:00
Piotr Skalski de896189b8 Merge pull request #1326 from roboflow/feat/dataset-lazy-loading
Lazy Dataset Loading
2024-07-10 11:52:57 +02:00
Onuralp SEZER fbfd078795 Merge pull request #1336 from cdragos/docs/revise-contributing-guidelines
docs: revise and restructure CONTRIBUTING.md
2024-07-09 21:34:43 +03:00
Dragos Catarahia e31aad242a docs: revise and restructure CONTRIBUTING.md 2024-07-10 01:22:23 +09:00
LinasKo 93c5c39f8f as_pascal_voc now loads image paths 2024-07-09 15:30:19 +03:00
LinasKo 810148550b Bugfix: XML parse in object_to_pascal_voc 2024-07-09 15:23:48 +03:00
LinasKo 172877a3cf Fix accidental changes, rearrange utils, rename methods 2024-07-09 14:56:30 +03:00
pre-commit-ci[bot] a91fc1e4f3 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-07-09 11:31:00 +00:00
LinasKo f4fd595783 Fix image poaths in save_dataset, copy images if lazy 2024-07-09 14:30:07 +03:00
LinasKo e690b92688 Move back save_images to utils 2024-07-09 14:17:04 +03:00
LinasKo c8f771ec69 Move coco and yolo loaders back into utils 2024-07-09 14:04:11 +03:00
LinasKo 6b09e1d67c ClassificationDataset, moved coco save function into dataset 2024-07-09 11:57:42 +03:00
LinasKo 12195705f5 LazyLoaded DetectionDataset 2024-07-09 02:13:56 +03:00
Onuralp SEZER 9f7871b4be Merge pull request #1334 from roboflow/pre-commit-ci-update-config
chore(pre_commit): ⬆ pre_commit autoupdate
2024-07-08 22:26:54 +03:00
pre-commit-ci[bot] 44890dc712 chore(pre_commit): ⬆ pre_commit autoupdate
updates:
- [github.com/astral-sh/ruff-pre-commit: v0.5.0 → v0.5.1](https://github.com/astral-sh/ruff-pre-commit/compare/v0.5.0...v0.5.1)
2024-07-08 17:39:23 +00:00
LinasKo 57ae7467b9 Add cheatsheet links in supervision docs, readme 2024-07-08 13:57:12 +03:00
Iuri de Silvio 1e5e25c54a Merge pull request #1331 from roboflow/dependabot/pip/ruff-0.5.1
⬆️ Bump ruff from 0.5.0 to 0.5.1
2024-07-08 10:17:18 +02:00
dependabot[bot] ba7c4f4404 ⬆️ Bump ruff from 0.5.0 to 0.5.1
Bumps [ruff](https://github.com/astral-sh/ruff) from 0.5.0 to 0.5.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/0.5.0...0.5.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-07-08 01:13:42 +00:00
Onuralp SEZER f3b52c08a7 Merge pull request #1329 from roboflow/dependabot/pip/certifi-2024.7.4
⬆️ Bump certifi from 2024.6.2 to 2024.7.4
2024-07-06 11:39:25 +03:00
dependabot[bot] 1a36842407 ⬆️ Bump certifi from 2024.6.2 to 2024.7.4
Bumps [certifi](https://github.com/certifi/python-certifi) from 2024.6.2 to 2024.7.4.
- [Commits](https://github.com/certifi/python-certifi/compare/2024.06.02...2024.07.04)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-07-06 02:32:58 +00:00
LinasKo a8b12914c8 Fix florence 2 tests 2024-07-05 13:21:59 +03:00
LinasKo d3db15fcd0 Fix bug where florence2 returns normalized xyxy regions 2024-07-05 13:14:27 +03:00
Linas Kondrackis c40734fb8d Merge pull request #1316 from David-rn/feat/facemesh_from_mediapipe
Facemesh from mediapipe
2024-07-05 12:56:50 +03:00
LinasKo 55a9cef270 Minor edit: add Python label to dosctring example 2024-07-05 12:41:02 +03:00
LinasKo 4b9b70fbb2 LazyDataset Loading - accept List[str] of images
* Unfinished
* Untested
* Committing to show Piotr a bit earlier
2024-07-04 14:21:45 +03:00
Onuralp SEZER e61a1074ac Merge pull request #1324 from roboflow/dependabot/pip/tox-4.16.0
⬆️ Bump tox from 4.15.1 to 4.16.0
2024-07-04 13:44:27 +03:00
dependabot[bot] e6c7f970f0 ⬆️ Bump tox from 4.15.1 to 4.16.0
Bumps [tox](https://github.com/tox-dev/tox) from 4.15.1 to 4.16.0.
- [Release notes](https://github.com/tox-dev/tox/releases)
- [Changelog](https://github.com/tox-dev/tox/blob/main/docs/changelog.rst)
- [Commits](https://github.com/tox-dev/tox/compare/4.15.1...4.16.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-07-04 01:08:33 +00:00
Piotr Skalski f06dcf73a5 Merge pull request #1277 from roboflow/feat/patch-rich-label-annotator
Patch RichLabelAnnotator, fix in-place functionality of other annotators
2024-07-03 13:39:10 +02:00
SkalskiP 0bb25fdd91 bump version from 0.21.0 to 0.22.0rc1 2024-07-03 13:15:49 +02:00
Onuralp SEZER 9501a0c72e Merge pull request #1323 from roboflow/dependabot/pip/mkdocs-jupyter-0.24.8
⬆️ Bump mkdocs-jupyter from 0.24.7 to 0.24.8
2024-07-03 13:05:22 +03:00
Onuralp SEZER d9b9143f07 Merge pull request #1322 from roboflow/dependabot/pip/mkdocs-material-9.5.28
⬆️ Bump mkdocs-material from 9.5.27 to 9.5.28
2024-07-03 13:04:46 +03:00
dependabot[bot] b7e6bcc15f ⬆️ Bump mkdocs-jupyter from 0.24.7 to 0.24.8
Bumps [mkdocs-jupyter](https://github.com/danielfrg/mkdocs-jupyter) from 0.24.7 to 0.24.8.
- [Changelog](https://github.com/danielfrg/mkdocs-jupyter/blob/main/CHANGELOG.md)
- [Commits](https://github.com/danielfrg/mkdocs-jupyter/compare/0.24.7...0.24.8)

---
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-07-03 00:44:18 +00:00
dependabot[bot] 08fbcbd8ea ⬆️ Bump mkdocs-material from 9.5.27 to 9.5.28
Bumps [mkdocs-material](https://github.com/squidfunk/mkdocs-material) from 9.5.27 to 9.5.28.
- [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.27...9.5.28)

---
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-07-03 00:43:11 +00:00
Onuralp SEZER e5114a233c Merge pull request #1321 from roboflow/dependabot/pip/pillow-10.4.0
⬆️ Bump pillow from 10.3.0 to 10.4.0
2024-07-02 04:06:01 +03:00
dependabot[bot] dea7f83e50 ⬆️ Bump pillow from 10.3.0 to 10.4.0
Bumps [pillow](https://github.com/python-pillow/Pillow) from 10.3.0 to 10.4.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.3.0...10.4.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-07-02 00:58:12 +00:00
Onuralp SEZER 034d3eaaac Merge pull request #1319 from roboflow/pre-commit-ci-update-config
chore(pre_commit): ⬆ pre_commit autoupdate
2024-07-01 20:58:13 +03:00
pre-commit-ci[bot] 7397d8a240 chore(pre_commit): ⬆ pre_commit autoupdate
updates:
- [github.com/astral-sh/ruff-pre-commit: v0.4.10 → v0.5.0](https://github.com/astral-sh/ruff-pre-commit/compare/v0.4.10...v0.5.0)
2024-07-01 17:57:15 +00:00
David Redo a023259445 Updated from_mediapipe docstring with FaceLandmaker 2024-07-01 19:30:17 +02:00
Linas Kondrackis 09a06e10a1 Merge pull request #1312 from Bhavay-2001/overlay_image
Updated overlay_image function in CropAnnotator
2024-07-01 14:32:31 +03:00
Linas Kondrackis 8d26a9291b Merge pull request #1317 from roboflow/fix/poetry/dep
fix: 🐞 skip broken docutils package, revert numpy version lock
2024-07-01 11:12:07 +03:00
Onuralp SEZER 28d219c86d fix: 🐞 skip broken docutils and remove numpy version lock
Signed-off-by: Onuralp SEZER <thunderbirdtr@gmail.com>
2024-06-29 00:42:11 +03:00
Onuralp SEZER 89ef841955 Merge pull request #1314 from roboflow/dependabot/pip/ruff-0.5.0
⬆️ Bump ruff from 0.4.10 to 0.5.0
2024-06-28 23:21:12 +03:00
David Redo b164ef1111 Added check for FaceMesh legacy object when no faces are detected 2024-06-28 15:30:07 +02:00
dependabot[bot] 2f39a2c3c6 ⬆️ Bump ruff from 0.4.10 to 0.5.0
Bumps [ruff](https://github.com/astral-sh/ruff) from 0.4.10 to 0.5.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.4.10...0.5.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-06-28 00:45:48 +00:00
Onuralp SEZER d8f990231c Merge pull request #1300 from kirilman/develop
detectron2 mask convert to detection
2024-06-27 22:21:51 +03:00
David Redo 74d19dd069 Added FaceMesh support in from_mediapipe KeyPoints fuction 2024-06-27 17:21:30 +02:00
pre-commit-ci[bot] 552c8dbede fix(pre_commit): 🎨 auto format pre-commit hooks 2024-06-27 12:21:29 +00:00
Bhavay Malhotra e421af494f Changed the parameters of overlay_image function 2024-06-27 17:43:10 +05:30
Onuralp SEZER 5b3fc12aea Merge pull request #1311 from roboflow/dependabot/pip/twine-5.1.1
⬆️ Bump twine from 5.1.0 to 5.1.1
2024-06-27 09:22:41 +03:00
dependabot[bot] 854fb18b34 ⬆️ Bump twine from 5.1.0 to 5.1.1
Bumps [twine](https://github.com/pypa/twine) from 5.1.0 to 5.1.1.
- [Release notes](https://github.com/pypa/twine/releases)
- [Changelog](https://github.com/pypa/twine/blob/main/docs/changelog.rst)
- [Commits](https://github.com/pypa/twine/compare/5.1.0...v5.1.1)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-06-27 01:03:10 +00:00
Onuralp SEZER 185ae462a4 fix: 🐞 confidence shape size fix for validation
Signed-off-by: Onuralp SEZER <thunderbirdtr@gmail.com>
2024-06-26 16:09:10 +03:00
Onuralp SEZER 3676f07168 fix: 🐞 doc and validation typo fix
Signed-off-by: Onuralp SEZER <thunderbirdtr@gmail.com>
2024-06-26 15:51:32 +03:00
Onuralp SEZER 099258baa6 feat: ✨ check pred_keypoints is exist if not return empty
Signed-off-by: Onuralp SEZER <thunderbirdtr@gmail.com>
2024-06-26 15:44:32 +03:00
Onuralp SEZER 0bb3839d29 feat: ✨ Keypoints for detectron2 added
Signed-off-by: Onuralp SEZER <thunderbirdtr@gmail.com>
2024-06-26 15:38:31 +03:00
Onuralp SEZER f66444bc91 fix: 🐞 add if condition for check existince of 'pred_masks' for detectron2
Signed-off-by: Onuralp SEZER <thunderbirdtr@gmail.com>
2024-06-25 16:25:28 +03:00
Onuralp SEZER 6de21048d2 Merge pull request #1307 from roboflow/docs/suppress-mkdocs-relative-link-messages
Suppress mkdocs relative link INFO messages
2024-06-25 10:40:15 +03:00
Onuralp SEZER db9d6c623b Merge pull request #1305 from roboflow/dependabot/pip/mypy-1.10.1
⬆️ Bump mypy from 1.10.0 to 1.10.1
2024-06-25 10:15:08 +03:00
Onuralp SEZER fb7ecd73d9 Merge pull request #1304 from roboflow/pre-commit-ci-update-config
chore(pre_commit): ⬆ pre_commit autoupdate
2024-06-25 10:14:55 +03:00
Onuralp SEZER 2bc19d69af Merge pull request #1306 from roboflow/dependabot/pip/mike-2.1.2
⬆️ Bump mike from 2.1.1 to 2.1.2
2024-06-25 10:14:39 +03:00
LinasKo a377b54a60 Merge branch 'develop' into feat/supervision-cleanup 2024-06-25 09:57:13 +03:00
dependabot[bot] db1998c155 ⬆️ Bump mike from 2.1.1 to 2.1.2
Bumps [mike](https://github.com/jimporter/mike) from 2.1.1 to 2.1.2.
- [Release notes](https://github.com/jimporter/mike/releases)
- [Changelog](https://github.com/jimporter/mike/blob/master/CHANGES.md)
- [Commits](https://github.com/jimporter/mike/compare/v2.1.1...v2.1.2)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-06-25 01:04:21 +00:00
dependabot[bot] ef6369b93d ⬆️ Bump mypy from 1.10.0 to 1.10.1
Bumps [mypy](https://github.com/python/mypy) from 1.10.0 to 1.10.1.
- [Changelog](https://github.com/python/mypy/blob/master/CHANGELOG.md)
- [Commits](https://github.com/python/mypy/compare/v1.10.0...v1.10.1)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-06-25 01:02:06 +00:00
pre-commit-ci[bot] a21a17ba29 chore(pre_commit): ⬆ pre_commit autoupdate
updates:
- [github.com/astral-sh/ruff-pre-commit: v0.4.9 → v0.4.10](https://github.com/astral-sh/ruff-pre-commit/compare/v0.4.9...v0.4.10)
2024-06-24 17:47:27 +00:00
Onuralp SEZER c973647cb8 Merge pull request #975 from roboflow/cookbooks/json-csv-sinks
docs(notebooks): 📝 json and csv sink cookbooks are added
2024-06-24 15:53:08 +03:00
LinasKo 71bdb01547 Sinks cookbooks: add 'person' label, min_consectutive_frames 2024-06-24 15:35:21 +03:00
LinasKo 92a5a931a8 Merge branch 'develop' into cookbooks/json-csv-sinks 2024-06-24 15:08:16 +03:00
LinasKo 0ecd88d4d1 Sink cookbooks: Fix cell output error 2024-06-24 14:36:03 +03:00
LinasKo 4d12853b95 Sink cookbooks fix: _to_detections unpacks into List[Detections]
* 1 sv.Detections per frame
2024-06-24 14:31:59 +03:00
LinasKo 9333460ee9 Tidy up Sink cookbook text 2024-06-24 13:31:35 +03:00
Piotr Skalski d5cebd4fd2 Merge pull request #1296 from LinasKo/feat/florence-2-support
Add Florence 2 support
2024-06-21 11:40:00 -07:00
LinasKo 61579af25a Make ruff happy 2024-06-21 17:49:43 +03:00
pre-commit-ci[bot] bcd3e1be17 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-06-21 13:59:41 +00:00
LinasKo 9ef697cd10 Florence 2 units tests 2024-06-21 16:59:01 +03:00
LinasKo 19bf417810 Special case for REGION_TO_DESCRIPTION when nothing is detected 2024-06-21 15:38:21 +03:00
pre-commit-ci[bot] 3df33f0f9d fix(pre_commit): 🎨 auto format pre-commit hooks 2024-06-21 11:24:24 +00:00
kirilman b8b31f6f00 detectron2 mask convert to detection 2024-06-21 16:15:34 +05:00
LinasKo fc11f4d7af Masks are now bool 2024-06-21 12:56:14 +03:00
LinasKo ec517124f8 florence_2: Clean up task selector 2024-06-21 12:34:09 +03:00
Onuralp SEZER f00dcede1a Merge pull request #1299 from roboflow/dependabot/pip/ruff-0.4.10
⬆️ Bump ruff from 0.4.9 to 0.4.10
2024-06-21 09:23:46 +03:00
dependabot[bot] 6fb90f6b75 ⬆️ Bump ruff from 0.4.9 to 0.4.10
Bumps [ruff](https://github.com/astral-sh/ruff) from 0.4.9 to 0.4.10.
- [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.9...v0.4.10)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-06-21 01:01:46 +00:00
LinasKo 23e63501eb fix, from_florence_2: extra dimension for xyxy, REGION_TO_CATEGORY 2024-06-20 21:35:49 +03:00
Onuralp SEZER 0df56b1d66 docs(notebook): code clean up and table of content fixes made for mkdocs version
Signed-off-by: Onuralp SEZER <thunderbirdtr@gmail.com>
2024-06-20 21:26:56 +03:00
LinasKo ec75a86a83 Fix, from_florence_2: polygon_to_mask expects np.int32 2024-06-20 21:26:54 +03:00
LinasKo 4599548eeb Fix, from_florence_2: polygons must be shaped (-1, 2) 2024-06-20 21:22:15 +03:00
LinasKo bb513f880a Add segmentation and region methods 2024-06-20 21:08:42 +03:00
Onuralp SEZER fbce6e45d4 Merge pull request #1298 from roboflow/fix/readme-broken-links
Readme: fix broken links
2024-06-20 16:23:45 +03:00
LinasKo a00e2d22ba Readme: fix broken links 2024-06-20 16:12:35 +03:00
LinasKo 04c5f18da0 Bugfix: florence 2, handle case with no detections 2024-06-20 15:49:13 +03:00
Onuralp SEZER 8b933f640e Merge pull request #1297 from roboflow/readme/hackfest-banner
Readme: change hackfest banner link to project page
2024-06-20 15:23:12 +03:00
LinasKo f01ca33511 Readme: change hackfest banner link to project page 2024-06-20 15:14:33 +03:00
LinasKo 2f88bb2b8e Add Florence 2 support 2024-06-20 14:50:10 +03:00
Onuralp SEZERandpre-commit-ci[bot] b2b251a424 feat: 🚀 Triangle and Dot annotators outline thickness level and triangle and circle shapes added (#1294)
* feat: 🚀 Triangle_annotator and Dot_annotator outline thickness value added
* feat: 🚀 Triangle_annotator and Dot_annotator outline triangle and circle added
* docs: 📝 outline_thickness py docs added
* refactor: remove else statement for thickness in circle not needed 
* fix(pre_commit): 🎨 auto format pre-commit hooks

---------

Signed-off-by: Onuralp SEZER <thunderbirdtr@gmail.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Onuralp SEZER <thunderbirdtr@gmail.com>
2024-06-20 12:49:36 +03:00
Onuralp SEZER eec3615250 refactor: remove else statement for thickness in circle not needed
Signed-off-by: Onuralp SEZER <thunderbirdtr@gmail.com>
2024-06-20 12:45:55 +03:00
pre-commit-ci[bot] 272a9cb35e fix(pre_commit): 🎨 auto format pre-commit hooks 2024-06-19 18:43:35 +00:00
Dripto Saha 0d0328ef22 Updated the Triangle_annotator and the Dot_annotator in the annotator-core.py file 2024-06-20 00:12:42 +05:30
Dripto Saha d821fca2af Updated the Triangle_annotator and the Dot_annotator in the annotator-core.py 2024-06-19 23:59:27 +05:30
pre-commit-ci[bot] ff9a63a68b fix(pre_commit): 🎨 auto format pre-commit hooks 2024-06-19 18:15:45 +00:00
Dripto Saha a6222a065c Updated the Triangle_annotator and the Dot_annotator in the annotator-core.py 2024-06-19 23:44:30 +05:30
Onuralp SEZER 1489f82e0f docs: 📝 outline_thickness py docs added
Signed-off-by: Onuralp SEZER <thunderbirdtr@gmail.com>
2024-06-19 20:43:55 +03:00
pre-commit-ci[bot] 12722df65b fix(pre_commit): 🎨 auto format pre-commit hooks 2024-06-19 17:38:49 +00:00
Dripto Saha 900952acae Modified annotators-core.py 2024-06-19 23:08:36 +05:30
pre-commit-ci[bot] 95308126c7 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-06-19 17:28:09 +00:00
Dripto Saha e7de6859e9 Updated annotation-core.py 2024-06-19 22:57:52 +05:30
pre-commit-ci[bot] feeea38e6e fix(pre_commit): 🎨 auto format pre-commit hooks 2024-06-19 14:11:46 +00:00
Dripto Saha 6ea07a1c2a Updated dot-annotator-core.py 2024-06-19 19:11:52 +05:30
Linas Kondrackis fbb770a486 Merge pull request #1227 from Bhavay-2001/OBB
Adding support for Yolo-OBB (Oriented Bounding Boxes) format
2024-06-19 12:10:23 +03:00
Linas Kondrackis 09f663139c Merge pull request #1290 from roboflow/expose_file_script
file utilities ret-type updated and extended function to work with Pathlib
2024-06-19 12:02:11 +03:00
hardikdava 9efd04925c Merge remote-tracking branch 'origin/expose_file_script' into expose_file_script 2024-06-19 09:46:46 +02:00
hardikdava 14ce0799ce revert global import 2024-06-19 09:46:38 +02:00
LinasKo a81f24e08d Explain OBB format in docstring 2024-06-19 01:06:39 +03:00
LinasKo 257e73fb37 Change uncommon np.int0 type to its alias np.intp 2024-06-19 00:36:27 +03:00
LinasKo dcfb122816 Fix xyxyxyxy shape
* Ultralytics return (-1, 4, 2), and that's waht our annotators expect
2024-06-19 00:33:00 +03:00
LinasKo 79ea168fd4 Merge branch 'develop' into OBB 2024-06-18 23:59:36 +03:00
LinasKo d35830ddeb Include tests 2024-06-18 22:19:36 +03:00
LinasKo c5ff58910d Reduce number of copy operations 2024-06-18 21:32:40 +03:00
Linas Kondrackis 15d9b75225 Merge pull request #1287 from roboflow/dependabot/pip/mkdocs-material-9.5.27
⬆️ Bump mkdocs-material from 9.5.26 to 9.5.27
2024-06-18 16:12:04 +03:00
Linas Kondrackis 49318ffe31 Merge pull request #1289 from roboflow/pre-commit-ci-update-config
chore(pre_commit): ⬆ pre_commit autoupdate
2024-06-18 16:05:56 +03:00
Linas Kondrackis b52a0297f1 Merge pull request #1291 from roboflow/dependabot/pip/urllib3-2.2.2
⬆️ Bump urllib3 from 2.2.1 to 2.2.2
2024-06-18 15:12:13 +03:00
dependabot[bot] eceebb33e3 ⬆️ Bump urllib3 from 2.2.1 to 2.2.2
Bumps [urllib3](https://github.com/urllib3/urllib3) from 2.2.1 to 2.2.2.
- [Release notes](https://github.com/urllib3/urllib3/releases)
- [Changelog](https://github.com/urllib3/urllib3/blob/main/CHANGES.rst)
- [Commits](https://github.com/urllib3/urllib3/compare/2.2.1...2.2.2)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-06-17 23:02:23 +00:00
pre-commit-ci[bot] fa7821b1c4 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-06-17 18:54:25 +00:00
hardikdava a56a16937f missing rettype added 2024-06-17 20:54:08 +02:00
hardikdava 0c95a6126d converting paths to string 2024-06-17 20:50:40 +02:00
hardikdava c14642accf docstrings updated 2024-06-17 20:47:36 +02:00
hardikdava 8c0e2fb362 exposing some file utilities 2024-06-17 20:44:48 +02:00
pre-commit-ci[bot] e5fb43aea6 chore(pre_commit): ⬆ pre_commit autoupdate
updates:
- [github.com/PyCQA/bandit: 1.7.8 → 1.7.9](https://github.com/PyCQA/bandit/compare/1.7.8...1.7.9)
- [github.com/astral-sh/ruff-pre-commit: v0.4.8 → v0.4.9](https://github.com/astral-sh/ruff-pre-commit/compare/v0.4.8...v0.4.9)
2024-06-17 17:46:44 +00:00
Onuralp SEZER 32b70c5d37 Merge pull request #1286 from roboflow/dependabot/pip/ruff-0.4.9
⬆️ Bump ruff from 0.4.8 to 0.4.9
2024-06-17 18:07:47 +03:00
dependabot[bot] b9e98a5e20 ⬆️ Bump ruff from 0.4.8 to 0.4.9
Bumps [ruff](https://github.com/astral-sh/ruff) from 0.4.8 to 0.4.9.
- [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.8...v0.4.9)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-06-17 15:05:59 +00:00
Onuralp SEZER 246b8a720c Merge pull request #1288 from roboflow/feat/disalllow-numpy-v2
Numpy upper limit: `<2.0.0`
2024-06-17 18:03:07 +03:00
LinasKo a43970fb65 Pin numpy to <2.0.0 2024-06-17 16:46:47 +03:00
Dripto Saha ff5709def2 Updated annotators-core.py 2024-06-17 16:46:41 +05:30
Dripto Saha 2805f41675 Updated annotators-core.py 2024-06-17 16:08:12 +05:30
dependabot[bot] 4eaa897f2c ⬆️ Bump mkdocs-material from 9.5.26 to 9.5.27
Bumps [mkdocs-material](https://github.com/squidfunk/mkdocs-material) from 9.5.26 to 9.5.27.
- [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.26...9.5.27)

---
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-06-17 00:44:28 +00:00
Piotr Skalski f96e7766f3 Merge pull request #1232 from David-rn/feat/keypoints-from-mediapipe
Feat/keypoints from mediapipe
2024-06-13 14:09:56 -04:00
pre-commit-ci[bot] 07cb0d8ccf fix(pre_commit): 🎨 auto format pre-commit hooks 2024-06-13 17:50:45 +00:00
SkalskiP 3725beb2db docs improvements 2024-06-13 13:50:27 -04:00
Bhavay Malhotra d5f8b94d65 Merge branch 'OBB' of https://github.com/Bhavay-2001/roboflow-supervision into OBB 2024-06-13 20:22:36 +05:30
Bhavay Malhotra 6f7f728044 Changed the position of a line 2024-06-13 20:22:26 +05:30
LinasKo aad3c4fce4 Defensive default font loading 2024-06-12 15:48:53 +03:00
LinasKo 52724ca673 RichLabelAnnotator: Minor docstring styling 2024-06-12 15:38:52 +03:00
LinasKo e3fc238c70 Revert RichLabelAnnotator font size 2024-06-12 15:33:04 +03:00
LinasKo cfe29cd05f Bugfix: MaskAnnotator and HaloAnnotator now work in-place 2024-06-12 15:09:50 +03:00
LinasKo 0f76f731ee bugfix: ColorAnnotator is now in-place 2024-06-12 14:58:48 +03:00
LinasKo c239291541 Bugfix: PIL exposes font size param, but complains if set 2024-06-12 11:08:30 +03:00
LinasKo a446ffd021 Bugfix: decorators for annotators now work in-place 2024-06-12 10:59:25 +03:00
LinasKo c2084c4d0f Add missing base classes for annotators 2024-06-11 17:34:51 +03:00
LinasKo e3cb417129 RichLabelAnnotator fix: convert back to numpy 2024-06-11 16:15:23 +03:00
LinasKo 27de665940 Docs: Remove INFO about absolute links when building 2024-06-11 15:19:52 +03:00
LinasKo 93b21a8d2d minor improvement to code clarity 2024-06-11 14:02:52 +03:00
LinasKo a4bdfc2062 minor tidy-up for mediapipe 2024-06-11 13:51:23 +03:00
LinasKo fd1a07cb6b Adjust long lines 2024-06-11 13:14:38 +03:00
LinasKo edfb814fc4 Merge branch 'develop' into feat/keypoints-from-mediapipe 2024-06-11 13:06:40 +03:00
Onuralp SEZER 3d5437b960 Merge pull request #1273 from roboflow/pre-commit-ci-update-config
chore(pre_commit): ⬆ pre_commit autoupdate
2024-06-10 20:51:46 +03:00
pre-commit-ci[bot] 68c2504d61 chore(pre_commit): ⬆ pre_commit autoupdate
updates:
- [github.com/astral-sh/ruff-pre-commit: v0.4.7 → v0.4.8](https://github.com/astral-sh/ruff-pre-commit/compare/v0.4.7...v0.4.8)
2024-06-10 17:50:26 +00:00
Onuralp SEZER 6984d72f4a Merge pull request #1272 from roboflow/dependabot/pip/notebook-7.2.1
⬆️ Bump notebook from 7.2.0 to 7.2.1
2024-06-10 09:09:23 +03:00
dependabot[bot] 6f5b477ac0 ⬆️ Bump notebook from 7.2.0 to 7.2.1
Bumps [notebook](https://github.com/jupyter/notebook) from 7.2.0 to 7.2.1.
- [Release notes](https://github.com/jupyter/notebook/releases)
- [Changelog](https://github.com/jupyter/notebook/blob/@jupyter-notebook/tree@7.2.1/CHANGELOG.md)
- [Commits](https://github.com/jupyter/notebook/compare/@jupyter-notebook/tree@7.2.0...@jupyter-notebook/tree@7.2.1)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-06-10 01:16:42 +00:00
Onuralp SEZER b19511968d Merge pull request #1271 from mqasim41/develop
Fix Grammatical Mistake In CONTRIBUTING.md
2024-06-08 19:45:24 +03:00
mqasim41 165c77d830 Fix Grammatical Mistake In CONTRIBUTING.md 2024-06-07 18:03:12 +05:00
Onuralp SEZER 558581943b Merge pull request #1268 from roboflow/dependabot/pip/mkdocs-material-9.5.26
⬆️ Bump mkdocs-material from 9.5.25 to 9.5.26
2024-06-07 11:43:01 +03:00
Onuralp SEZER 8acbc422c9 Merge pull request #1267 from roboflow/dependabot/pip/tornado-6.4.1
⬆️ Bump tornado from 6.4 to 6.4.1
2024-06-07 11:37:20 +03:00
dependabot[bot] 9995771604 ⬆️ Bump mkdocs-material from 9.5.25 to 9.5.26
Bumps [mkdocs-material](https://github.com/squidfunk/mkdocs-material) from 9.5.25 to 9.5.26.
- [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.25...9.5.26)

---
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-06-07 01:07:22 +00:00
dependabot[bot] bcc1bc1ff2 ⬆️ Bump tornado from 6.4 to 6.4.1
Bumps [tornado](https://github.com/tornadoweb/tornado) from 6.4 to 6.4.1.
- [Changelog](https://github.com/tornadoweb/tornado/blob/master/docs/releases.rst)
- [Commits](https://github.com/tornadoweb/tornado/compare/v6.4.0...v6.4.1)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-06-06 23:39:07 +00:00
pre-commit-ci[bot] cce69d893e fix(pre_commit): 🎨 auto format pre-commit hooks 2024-06-06 16:57:06 +00:00
Bhavay Malhotra 3e2fe835db Merge branch 'OBB' of https://github.com/Bhavay-2001/roboflow-supervision into OBB 2024-06-06 22:24:29 +05:30
Bhavay Malhotra 47f1c44e20 Updated criteria for xyxyxyxy 2024-06-06 22:22:54 +05:30
pre-commit-ci[bot] 420543534d fix(pre_commit): 🎨 auto format pre-commit hooks 2024-06-06 16:45:31 +00:00
Bhavay Malhotra 1ea9345845 Merge branch 'OBB' of https://github.com/Bhavay-2001/roboflow-supervision into OBB 2024-06-06 22:14:11 +05:30
Bhavay Malhotra 6ca09ccbfc Added default value for is_obb parameter 2024-06-06 22:14:02 +05:30
Onuralp SEZER 7f78f93407 Merge pull request #1263 from roboflow/dependabot/pip/ruff-0.4.8
⬆️ Bump ruff from 0.4.7 to 0.4.8
2024-06-06 11:03:11 +03:00
Onuralp SEZER 05ceca70ef Merge pull request #1262 from roboflow/dependabot/pip/tox-4.15.1
⬆️ Bump tox from 4.15.0 to 4.15.1
2024-06-06 11:02:56 +03:00
Piotr Skalski e8f8c38f39 Merge pull request #1264 from roboflow/main
Merge pull request #1258 from roboflow/develop
2024-06-06 08:13:34 +02:00
Piotr Skalski e50c761b83 Merge pull request #1258 from roboflow/develop
`supervision-0.21.0` release
2024-06-06 08:11:08 +02:00
dependabot[bot] 0739e24b25 ⬆️ Bump ruff from 0.4.7 to 0.4.8
Bumps [ruff](https://github.com/astral-sh/ruff) from 0.4.7 to 0.4.8.
- [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.7...v0.4.8)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-06-06 01:33:50 +00:00
dependabot[bot] 560760993a ⬆️ Bump tox from 4.15.0 to 4.15.1
Bumps [tox](https://github.com/tox-dev/tox) from 4.15.0 to 4.15.1.
- [Release notes](https://github.com/tox-dev/tox/releases)
- [Changelog](https://github.com/tox-dev/tox/blob/main/docs/changelog.rst)
- [Commits](https://github.com/tox-dev/tox/compare/4.15.0...4.15.1)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-06-06 01:31:57 +00:00
pre-commit-ci[bot] 859f0258bc fix(pre_commit): 🎨 auto format pre-commit hooks 2024-06-05 17:34:09 +00:00
Bhavay Malhotra 2f644c52e3 Merge branch 'OBB' of https://github.com/Bhavay-2001/roboflow-supervision into OBB 2024-06-05 23:03:33 +05:30
Bhavay Malhotra a82c37c7fa Updated yolo.py for OBB support 2024-06-05 23:03:24 +05:30
pre-commit-ci[bot] fc2710c9c9 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-06-05 17:31:11 +00:00
Bhavay Malhotra 29161a485e Merge branch 'OBB' of https://github.com/Bhavay-2001/roboflow-supervision into OBB 2024-06-05 23:00:45 +05:30
Bhavay Malhotra 523d218dd4 Made few changes to add OBB support 2024-06-05 22:59:04 +05:30
SkalskiP 0200fd307b mark InferenceSlicer with new status 2024-06-05 18:00:54 +02:00
Piotr Skalski 6a199c5d7e Merge pull request #1260 from roboflow/final-changes-before-supervision-0.21.0-release
final changes before `supervision-0.21.0`
2024-06-05 17:55:51 +02:00
Piotr Skalski d19c44c991 Merge pull request #1261 from roboflow/docs/new-status-tags-for-0.21.0
Update "New" tags in docs, fixed typo in one heading
2024-06-05 17:55:32 +02:00
SkalskiP 2d5de66a9b code snippets updates 2024-06-05 17:53:38 +02:00
LinasKo 13b46dda67 Update "New" tags in docs, fix typo in one heading 2024-06-05 17:44:25 +02:00
SkalskiP a3f299ceb0 update docs headers 2024-06-05 17:40:39 +02:00
SkalskiP 9a42372ff6 changelog updated 2024-06-05 17:37:01 +02:00
SkalskiP 47b9ab8f96 Merge remote-tracking branch 'origin/final-changes-before-supervision-0.21.0-release' into final-changes-before-supervision-0.21.0-release 2024-06-05 16:52:27 +02:00
SkalskiP b476acc1f3 bump version from 0.21.0rc5 to 0.21.0 2024-06-05 16:52:18 +02:00
pre-commit-ci[bot] 3cee266f71 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-06-05 14:33:09 +00:00
Piotr Skalski 111d4c6c91 Merge pull request #1206 from tc360950/line-zone-unit-tests
Add LineZone unit tests
2024-06-05 16:30:20 +02:00
LinasKo a77a2ba8aa LineZone: uncomment unit tests, set expected results 2024-06-05 16:27:53 +02:00
Piotr Skalski fb9024bc75 Merge pull request #1255 from roboflow/fix/detections-merge-revert-and-filter-out-empty
Revert flexible merging, Filter out empty detections
2024-06-05 16:01:38 +02:00
LinasKo ceecb8bbd7 Cleanup: Remove print statements from tests 2024-06-05 15:42:00 +02:00
SkalskiP c28c93bd4f non-max-merging visualization + from_lmm updates 2024-06-05 15:40:28 +02:00
pre-commit-ci[bot] 46bd267079 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-06-05 12:17:11 +00:00
Bhavay Malhotra d025791805 Merge branch 'OBB' of https://github.com/Bhavay-2001/roboflow-supervision into OBB 2024-06-05 17:46:12 +05:30
Bhavay Malhotra 7e4fc8a485 Made few changes to add OBB support 2024-06-05 17:43:58 +05:30
LinasKo ca482967c4 Add note that merge ignores empty detections 2024-06-05 12:28:09 +02:00
LinasKo 57fa637eea Move is_empty into Detections 2024-06-05 12:18:57 +02:00
Linas Kondrackis 59c5ab5252 Merge pull request #1228 from tc360950/vectorize-line-zone
Vectorize line zone
2024-06-05 10:26:23 +02:00
LinasKo c27a28235e LineZone: Remove comment 2024-06-05 10:24:25 +02:00
Onuralp SEZER cfbb6681cc Merge pull request #1257 from roboflow/dependabot/pip/pytest-8.2.2
⬆️ Bump pytest from 8.2.1 to 8.2.2
2024-06-05 10:44:46 +03:00
dependabot[bot] 24b1db9e25 ⬆️ Bump pytest from 8.2.1 to 8.2.2
Bumps [pytest](https://github.com/pytest-dev/pytest) from 8.2.1 to 8.2.2.
- [Release notes](https://github.com/pytest-dev/pytest/releases)
- [Changelog](https://github.com/pytest-dev/pytest/blob/main/CHANGELOG.rst)
- [Commits](https://github.com/pytest-dev/pytest/compare/8.2.1...8.2.2)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-06-05 00:43:32 +00:00
pre-commit-ci[bot] 8c92072ecd fix(pre_commit): 🎨 auto format pre-commit hooks 2024-06-04 19:07:59 +00:00
tc360950 38d442c176 PR fixes 2024-06-04 21:06:51 +02:00
Onuralp SEZER 2f09e51458 Merge pull request #1254 from roboflow/pre-commit-ci-update-config
chore(pre_commit): ⬆ pre_commit autoupdate
2024-06-03 23:25:56 +03:00
pre-commit-ci[bot] 56eb8e1698 chore(pre_commit): ⬆ pre_commit autoupdate
updates:
- [github.com/astral-sh/ruff-pre-commit: v0.4.5 → v0.4.7](https://github.com/astral-sh/ruff-pre-commit/compare/v0.4.5...v0.4.7)
2024-06-03 17:47:16 +00:00
LinasKo 5bfd51fdec is_empty check that includes data
* We need to decide if this or from_inference data appended to empty Detections is correct
2024-06-03 14:01:03 +02:00
LinasKo a5d4612402 Revert Detections.merge to 0.20.0, but filter out empty detections 2024-06-03 10:43:31 +02:00
Onuralp SEZER 941b7e30aa Merge pull request #1253 from roboflow/dependabot/pip/ruff-0.4.7
⬆️ Bump ruff from 0.4.6 to 0.4.7
2024-06-03 05:16:00 +03:00
Onuralp SEZER f4f2626b44 Merge pull request #1252 from roboflow/dependabot/pip/mkdocs-git-revision-date-localized-plugin-1.2.6
⬆️ Bump mkdocs-git-revision-date-localized-plugin from 1.2.5 to 1.2.6
2024-06-03 05:15:44 +03:00
dependabot[bot] 8f198e80cd ⬆️ Bump ruff from 0.4.6 to 0.4.7
Bumps [ruff](https://github.com/astral-sh/ruff) from 0.4.6 to 0.4.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.4.6...v0.4.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-06-03 01:14:18 +00:00
dependabot[bot] 612ac6145a ⬆️ Bump mkdocs-git-revision-date-localized-plugin
Bumps [mkdocs-git-revision-date-localized-plugin](https://github.com/timvink/mkdocs-git-revision-date-localized-plugin) from 1.2.5 to 1.2.6.
- [Release notes](https://github.com/timvink/mkdocs-git-revision-date-localized-plugin/releases)
- [Commits](https://github.com/timvink/mkdocs-git-revision-date-localized-plugin/compare/v1.2.5...v1.2.6)

---
updated-dependencies:
- dependency-name: mkdocs-git-revision-date-localized-plugin
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-06-03 01:05:47 +00:00
pre-commit-ci[bot] 26d70219bf fix(pre_commit): 🎨 auto format pre-commit hooks 2024-06-02 15:34:54 +00:00
David Redo daf13442f3 Updated from_mediapipe method to support two results types 2024-06-02 17:34:36 +02:00
LinasKo 2b5d430382 LineZone - does not work with movement to or from zones outside limits 2024-06-01 15:44:20 +02:00
LinasKo b6ff9242fc LineZone tests: add extreme coordinate test 2024-06-01 16:19:09 +03:00
LinasKo d2f169bcfa Line zone tests - replace multi detection tests 2024-06-01 15:59:46 +03:00
Linas Kondrackis 33e10ff722 Add unit tests covering most single-detection cases
* Add Colab for visuals: https://colab.research.google.com/drive/179sq8joJ-7JSYMqYNBQlMIPYEClq1PDi?usp=sharing
* Need to visualise other cases - not sure if all are necessary
2024-05-31 20:13:13 +03:00
Linas Kondrackis 883a6bed3c Merge pull request #1236 from roboflow/feat/slicer-select-nms-or-nmm
Select overlap filtering strategy
2024-05-30 14:06:00 +03:00
Linas Kondrackis f7bd7011fe OverlapFilter: Add and validate docs, rename 2024-05-30 13:45:12 +03:00
Onuralp SEZER 6193128774 Merge pull request #1245 from roboflow/dependabot/pip/requests-2.32.3
⬆️ Bump requests from 2.32.2 to 2.32.3
2024-05-30 11:49:13 +03:00
dependabot[bot] bdc10f83fe ⬆️ Bump requests from 2.32.2 to 2.32.3
Bumps [requests](https://github.com/psf/requests) from 2.32.2 to 2.32.3.
- [Release notes](https://github.com/psf/requests/releases)
- [Changelog](https://github.com/psf/requests/blob/main/HISTORY.md)
- [Commits](https://github.com/psf/requests/compare/v2.32.2...v2.32.3)

---
updated-dependencies:
- dependency-name: requests
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-05-30 01:05:20 +00:00
tc360950 dc1249969f Improve variable naming 2024-05-29 18:34:35 +02:00
Linas Kondrackis 34353aac54 Add overlap handling example image :) 2024-05-29 18:39:41 +03:00
Linas Kondrackis 6ad32406af fix: change doc path for overlap_handling, add box_non_max_merge 2024-05-29 16:31:29 +03:00
Linas Kondrackis 315c4295ff Move NMS and NMM related methods from utils into overlap_handling.py 2024-05-29 16:17:20 +03:00
Linas Kondrackis 4dc001d9bf Renamed overlap strategy, added into InferenceSlicer docs page 2024-05-29 15:53:04 +03:00
Linas Kondrackis 9d60b2009f Merge pull request #1237 from roboflow/feat/get-class-member-vars
Dynamically select Detections member variables
2024-05-29 11:12:39 +03:00
Linas Kondrackis c98698d442 get_instance_variables: test dataclass fields 2024-05-29 11:08:17 +03:00
Onuralp SEZER 3bda0bfc11 Merge pull request #1241 from roboflow/dependabot/pip/ruff-0.4.6
⬆️ Bump ruff from 0.4.5 to 0.4.6
2024-05-29 04:28:02 +03:00
Onuralp SEZER 0e19c581e4 Merge pull request #1240 from roboflow/dependabot/pip/ipywidgets-8.1.3
⬆️ Bump ipywidgets from 8.1.2 to 8.1.3
2024-05-29 04:27:52 +03:00
dependabot[bot] 8fb843ec8e ⬆️ Bump ruff from 0.4.5 to 0.4.6
Bumps [ruff](https://github.com/astral-sh/ruff) from 0.4.5 to 0.4.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.4.5...v0.4.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-05-29 01:10:56 +00:00
dependabot[bot] ba2b60ffb4 ⬆️ Bump ipywidgets from 8.1.2 to 8.1.3
Bumps [ipywidgets](https://github.com/jupyter-widgets/ipywidgets) from 8.1.2 to 8.1.3.
- [Release notes](https://github.com/jupyter-widgets/ipywidgets/releases)
- [Commits](https://github.com/jupyter-widgets/ipywidgets/compare/8.1.2...8.1.3)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-05-29 01:04:41 +00:00
Onuralp SEZER a6b985ff4b refactor: 📦 supervision updated to 0.21.0
Signed-off-by: Onuralp SEZER <thunderbirdtr@gmail.com>
2024-05-28 22:53:07 +03:00
LinasKo d59467b4f4 Add anchor check and tests to polygon zone 2024-05-28 15:12:48 +03:00
LinasKo c0486b7f94 Remove docstrings
The class names were descriptive enough
2024-05-28 14:46:55 +03:00
Linas Kondrackis f24c6f38a0 get_instance_variables only accepts instance, more tests 2024-05-28 14:09:38 +03:00
Linas Kondrackis a6c995c9a9 More tests for get_instance_variables 2024-05-28 11:14:29 +03:00
pre-commit-ci[bot] 3c3a0792f3 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-28 07:42:33 +00:00
Linas Kondrackis 1d13397503 Dynamically select Detections fields, not hardcoded 2024-05-28 10:38:54 +03:00
Linas Kondrackis f0e88b1982 Select overlap filtering strategy 2024-05-28 09:52:46 +03:00
Onuralp SEZER 9bc2907c49 Merge pull request #1235 from roboflow/dependabot/pip/mkdocs-material-9.5.25
⬆️ Bump mkdocs-material from 9.5.24 to 9.5.25
2024-05-28 03:43:10 +03:00
dependabot[bot] e7dfc04fd3 ⬆️ Bump mkdocs-material from 9.5.24 to 9.5.25
Bumps [mkdocs-material](https://github.com/squidfunk/mkdocs-material) from 9.5.24 to 9.5.25.
- [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.24...9.5.25)

---
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-05-28 00:31:55 +00:00
Piotr Skalski a0d0d45890 Merge pull request #500 from mario-dg/add_nmm_to_detections
Add Non-Maximum Merging (NMM) to Detections
2024-05-27 21:34:49 +02:00
SkalskiP 4a365fb907 add LMM to __init__.py 2024-05-27 21:31:25 +02:00
Onuralp SEZER a60cfe08e2 Merge pull request #1233 from roboflow/pre-commit-ci-update-config
chore(pre_commit): ⬆ pre_commit autoupdate
2024-05-27 20:50:48 +03:00
pre-commit-ci[bot] c1ebb81d47 chore(pre_commit): ⬆ pre_commit autoupdate
updates:
- [github.com/astral-sh/ruff-pre-commit: v0.4.4 → v0.4.5](https://github.com/astral-sh/ruff-pre-commit/compare/v0.4.4...v0.4.5)
2024-05-27 17:42:51 +00:00
Linas Kondrackis 2ee9e08446 Renamed to group_overlapping_boxes 2024-05-27 16:21:40 +03:00
Linas Kondrackis 530e1d01e1 Address comments 2024-05-27 16:17:27 +03:00
David Redo 4fea0031ba Updated docstring comment due to line too large 2024-05-26 21:45:59 +02:00
David Redo 490a341d5d add method in KeyPoints class 2024-05-26 20:14:57 +02:00
David Redo 2c3fa27929 add GHUM Skeleton enum 2024-05-26 20:14:09 +02:00
tc360950 404be16126 Code reformatting 2024-05-24 18:14:18 +02:00
tc360950 72d677ad89 Merge branch 'develop' of https://github.com/tc360950/supervision into line-zone-unit-tests 2024-05-24 18:11:17 +02:00
tc360950 d6ae86e97b Merge remote-tracking branch 'origin/vectorize-line-zone' into vectorize-line-zone 2024-05-24 18:04:54 +02:00
tc360950 ed5c26527a Code reformatting 2024-05-24 18:04:43 +02:00
pre-commit-ci[bot] d23cc008f8 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-24 16:02:31 +00:00
tc360950 9d54d91791 Pull changes from develop 2024-05-24 18:02:13 +02:00
tc360950 80feb2b12f Add comments 2024-05-24 17:43:02 +02:00
pre-commit-ci[bot] 51c7ebdf60 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-24 14:56:03 +00:00
Bhavay Malhotra 2653f5a090 Adding support for Yolo-OBB format 2024-05-24 20:23:17 +05:30
tc360950 fb30bab0fd Vectorize line zone 2024-05-24 16:50:42 +02:00
tc360950 a09b6fac6f Merge remote-tracking branch 'origin/line-zone-unit-tests' into line-zone-unit-tests
# Conflicts:
#	test/detection/test_line_counter.py
2024-05-24 16:43:03 +02:00
tc360950 4e2eb0afc2 Code reformatting 2024-05-24 16:42:40 +02:00
pre-commit-ci[bot] 1a021d5792 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-24 14:40:32 +00:00
tc360950 909ae2a8ff Merge remote-tracking branch 'origin/line-zone-unit-tests' into line-zone-unit-tests 2024-05-24 16:39:43 +02:00
tc360950 7d0488efc0 Add unit tests for negative coordinates and empty anchors 2024-05-24 16:39:30 +02:00
Piotr Skalski 2723735b01 Merge pull request #1221 from roboflow/from_paligemma_support
initial commit adding support for `from_lmm` and specifically for Pal…
2024-05-24 15:09:40 +02:00
Onuralp SEZER 7757d86abc Merge pull request #1225 from roboflow/dependabot/pip/ruff-0.4.5
⬆️ Bump ruff from 0.4.4 to 0.4.5
2024-05-24 13:55:40 +03:00
Piotr Skalski f40dd38b1a Merge pull request #1214 from roboflow/fix/remove-none-tracker-id-contents-checks
tracker_id contents are never `None`
2024-05-24 09:17:47 +02:00
Piotr Skalski ad7e643c83 Merge pull request #1180 from rolson24/fix_NaN_values_in_ByteTrack
Fix Cost Matrix containing NaN Values in ByteTrack
2024-05-24 09:01:12 +02:00
Piotr Skalski eae4040b17 Merge pull request #1224 from roboflow/docs/how-to-track-rename-title
Docs: shorter title for object tracking how-to
2024-05-24 07:59:41 +02:00
dependabot[bot] 9afca17854 ⬆️ Bump ruff from 0.4.4 to 0.4.5
Bumps [ruff](https://github.com/astral-sh/ruff) from 0.4.4 to 0.4.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.4.4...v0.4.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-05-24 00:13:26 +00:00
Linas Kondrackis 19296a73f6 ious: Replace 0-area check with nan conversion 2024-05-23 18:45:23 +03:00
Linas Kondrackis 0721bc289b Remove _set_at_index 2024-05-23 16:21:54 +03:00
pre-commit-ci[bot] db1b4737fe fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-23 13:04:11 +00:00
Linas Kondrackis 6fbca8333e Address review comments, simplify merge
* Reintroduced iou check before response - necessary for algorithm
2024-05-23 16:01:34 +03:00
pre-commit-ci[bot] ad2220bc1d fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-23 07:12:19 +00:00
SkalskiP 0115ef8b7d small fix when mask is empty 2024-05-23 09:11:47 +02:00
Onuralp SEZER d4541e1469 Merge pull request #1222 from roboflow/fix/yolo-obb
fix: 🐞 yolo obb condition check set or for newer and older version
2024-05-23 01:37:08 +03:00
Linas Kondrackis c9c2dad316 Docs: shorter title for object tracking how-to 2024-05-22 23:47:45 +03:00
Onuralp SEZER e59e2822d8 Merge pull request #1223 from roboflow/docs/how-to-track-rename-title
minor docs change: rename How To - Track Objects
2024-05-22 23:32:10 +03:00
Linas Kondrackis 99854a5b66 minor docs change: rename How To - Track Objects 2024-05-22 23:14:17 +03:00
Onuralp SEZER 251185ba67 fix: 🐞 yolo obb hasstr added into condition
Signed-off-by: Onuralp SEZER <thunderbirdtr@gmail.com>
2024-05-22 23:08:04 +03:00
Linas Kondrackis 8b4884ec9e tracker, smoother: SupervisionWarnings 2024-05-22 21:33:34 +03:00
SkalskiP 07c36c6223 make linter happy 2024-05-22 17:47:52 +02:00
pre-commit-ci[bot] bf43d6566b fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-22 14:29:23 +00:00
SkalskiP b59d17fdae Merge remote-tracking branch 'origin/from_paligemma_support' into from_paligemma_support
# Conflicts:
#	supervision/detection/lmm.py
#	test/detection/test_lmm.py
2024-05-22 16:29:04 +02:00
SkalskiP b81c5e8475 update to allow multi-word class names 2024-05-22 16:28:24 +02:00
pre-commit-ci[bot] 7eb918282c fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-22 12:27:56 +00:00
SkalskiP 36a73f7d49 clean up 2024-05-22 14:26:13 +02:00
SkalskiP a2195aa378 initial commit adding support for from_lmm and specifically for PaliGemma 2024-05-22 14:24:52 +02:00
Onuralp SEZER 2bd4348e5d Merge pull request #1220 from roboflow/dependabot/pip/requests-2.32.2
⬆️ Bump requests from 2.32.1 to 2.32.2
2024-05-22 04:00:05 +03:00
dependabot[bot] 6b7861d4d1 ---
updated-dependencies:
- dependency-name: requests
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-05-22 00:29:25 +00:00
pre-commit-ci[bot] 8a2f5d4726 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-21 19:19:16 +00:00
tc360950 dcfa916c75 Add docstrings with test description for LineZone tests 2024-05-21 21:18:51 +02:00
pre-commit-ci[bot] 54a0422b58 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-21 19:08:36 +00:00
tc360950 089916e26f Improve variable naming in LineZone unit tests, remove redundant test for empty tracker_id 2024-05-21 21:08:18 +02:00
Piotr Skalski 1bbe03ca27 Merge pull request #1163 from emSko/1114_RLE_support_for_COCO
1114 rle support for coco
2024-05-21 13:29:16 +02:00
pre-commit-ci[bot] 5840889818 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-21 11:08:22 +00:00
SkalskiP c3855c9828 small refactor + docs improvements 2024-05-21 13:08:02 +02:00
Linas Kondrackis 40b537c0be tracker_id contents are never None 2024-05-21 13:58:20 +03:00
SkalskiP 1d43042c55 small refactor + docs improvements 2024-05-21 12:01:05 +02:00
pre-commit-ci[bot] 996b0a3af3 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-21 09:43:30 +00:00
SkalskiP f2716252d5 small refactor + docs improvements 2024-05-21 11:43:09 +02:00
Linas Kondrackis b916dc547c Merge pull request #1212 from roboflow/dependabot/pip/mkdocs-material-9.5.24
⬆️ Bump mkdocs-material from 9.5.23 to 9.5.24
2024-05-21 11:31:54 +03:00
Linas Kondrackis e1be566861 Merge pull request #1211 from roboflow/dependabot/pip/requests-2.32.1
⬆️ Bump requests from 2.31.0 to 2.32.1
2024-05-21 10:21:28 +03:00
dependabot[bot] 32f773548e ---
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-05-21 01:02:35 +00:00
dependabot[bot] 414d3e9afb ---
updated-dependencies:
- dependency-name: requests
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-05-21 01:01:12 +00:00
magda skoczen 6dbf3f61e3 fix for unit tests for test_mask_has_holes 2024-05-20 21:47:04 +02:00
pre-commit-ci[bot] ab55e81087 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-20 19:41:35 +00:00
magda_sk 7b42d8381b Merge branch 'develop' into 1114_RLE_support_for_COCO 2024-05-20 21:41:22 +02:00
magda skoczen dfac30cba7 change docu for mask_has_multiple_segments and mask_has_holes and add to global __init__.py 2024-05-20 20:45:17 +02:00
magda skoczen c26eb1a70f unit tests for test_mask_has_multiple_segments 2024-05-20 19:52:48 +02:00
magda skoczen f0fc76c8c7 Merge branch '1114_RLE_support_for_COCO' of github.com:emSko/supervision into 1114_RLE_support_for_COCO 2024-05-20 19:23:29 +02:00
magda skoczen 68f07e18f3 tests for mask_has_holes 2024-05-20 19:23:22 +02:00
pre-commit-ci[bot] 7ee84c48e0 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-20 16:56:49 +00:00
magda skoczen 179d00bead merge 2024-05-20 18:56:25 +02:00
magda skoczen 2626263ff3 move has_holes and mask_has_multiple_segments to detections utils 2024-05-20 18:54:10 +02:00
magda skoczen a40bf78bb2 coco mock method refactoring 2024-05-20 18:17:03 +02:00
tc360950 41ca70aab6 Add missing type hints and consistent variable naming 2024-05-20 17:01:46 +02:00
Linas Kondrackis 3fbce7b6bb Merge pull request #1208 from roboflow/dependabot/pip/pytest-8.2.1
⬆️ Bump pytest from 8.2.0 to 8.2.1
2024-05-20 10:23:42 +03:00
dependabot[bot] b761a5c32b ⬆️ Bump pytest from 8.2.0 to 8.2.1
Bumps [pytest](https://github.com/pytest-dev/pytest) from 8.2.0 to 8.2.1.
- [Release notes](https://github.com/pytest-dev/pytest/releases)
- [Changelog](https://github.com/pytest-dev/pytest/blob/main/CHANGELOG.rst)
- [Commits](https://github.com/pytest-dev/pytest/compare/8.2.0...8.2.1)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-05-20 00:53:40 +00:00
tc360950 12a455eafa Replace unnecessary generator expressions with explicit lists 2024-05-18 17:06:28 +02:00
pre-commit-ci[bot] 6c9f8302a5 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-17 14:19:52 +00:00
tc360950 da904ad2da Add LineZone unit tests 2024-05-17 16:17:31 +02:00
pre-commit-ci[bot] 8d432c78b1 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-17 09:16:59 +00:00
magda skoczen 0cd2c9d146 documentation change for as_coco 2024-05-17 11:16:37 +02:00
magda skoczen aad5e2a212 merge seg fault fix 2024-05-17 11:11:40 +02:00
Linas Kondrackis ab775d9f76 Attempt to fix SegFault
* https://github.com/opencv/opencv-python/issues/706
2024-05-17 11:45:00 +03:00
Onuralp SEZER 1779014fd9 Merge pull request #1201 from roboflow/dependabot/pip/notebook-7.2.0
⬆️ Bump notebook from 7.1.3 to 7.2.0
2024-05-17 11:41:39 +03:00
Onuralp SEZER 84d8d98619 Merge pull request #1204 from roboflow/docs/docs-incorrect-optimal-scale-entry
docs: calculate_optimal_text_scale, not calculate_optimal_font_scale
2024-05-17 11:37:51 +03:00
magda skoczen 879ae9416a test polygon mask when mask in single component and no holes 2024-05-17 10:34:53 +02:00
Linas Kondrackis 9024396f6c Add npt.NDarray[x] types, remove resolution_wh default val 2024-05-17 10:58:45 +03:00
Linas Kondrackis de5349ad6d docs: calculate_optimal_text_scale, not calculate_optimal_font_scale
* Latter does not exist
2024-05-17 09:17:38 +03:00
Linas Kondrackis d391376912 Merge pull request #1202 from roboflow/dependabot/pip/twine-5.1.0
⬆️ Bump twine from 5.0.0 to 5.1.0
2024-05-17 09:06:37 +03:00
dependabot[bot] eb84d41c61 ⬆️ Bump twine from 5.0.0 to 5.1.0
Bumps [twine](https://github.com/pypa/twine) from 5.0.0 to 5.1.0.
- [Release notes](https://github.com/pypa/twine/releases)
- [Changelog](https://github.com/pypa/twine/blob/main/docs/changelog.rst)
- [Commits](https://github.com/pypa/twine/compare/5.0.0...5.1.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-05-17 01:00:50 +00:00
dependabot[bot] 0252cf210c ⬆️ Bump notebook from 7.1.3 to 7.2.0
Bumps [notebook](https://github.com/jupyter/notebook) from 7.1.3 to 7.2.0.
- [Release notes](https://github.com/jupyter/notebook/releases)
- [Changelog](https://github.com/jupyter/notebook/blob/main/CHANGELOG.md)
- [Commits](https://github.com/jupyter/notebook/compare/@jupyter-notebook/tree@7.1.3...@jupyter-notebook/tree@7.2.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-05-17 00:59:54 +00:00
pre-commit-ci[bot] b3b745508b fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-16 07:23:55 +00:00
magda skoczen 511f0ab9b2 check for empty mask 2024-05-16 09:23:22 +02:00
magda skoczen 3ee72e38c3 check for empty mask 2024-05-16 09:20:26 +02:00
Piotr Skalski 5acfb9531e Merge pull request #1200 from roboflow/docs/missing-return-in-slicer-callback-2
Missing return in another slicer callback
2024-05-16 09:18:37 +02:00
Linas Kondrackis 2c769e2f72 Missing return in another slicer callback 2024-05-16 10:11:03 +03:00
pre-commit-ci[bot] ce05a0c544 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-16 06:57:26 +00:00
magda skoczen 1e8ee47db2 craete copies of mask in _has_holes and _mask_has_multiple_segments 2024-05-16 08:56:58 +02:00
pre-commit-ci[bot] eefa05cf01 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-16 06:40:58 +00:00
magda skoczen d8679d9c46 automatic RLE for masks with holes or in multiple pieces 2024-05-16 08:40:28 +02:00
Onuralp SEZER 25ceb46ed4 Merge pull request #1199 from roboflow/dependabot/pip/mkdocs-material-9.5.23
⬆️ Bump mkdocs-material from 9.5.22 to 9.5.23
2024-05-16 04:16:20 +03:00
dependabot[bot] a615dfccb6 ⬆️ Bump mkdocs-material from 9.5.22 to 9.5.23
Bumps [mkdocs-material](https://github.com/squidfunk/mkdocs-material) from 9.5.22 to 9.5.23.
- [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.22...9.5.23)

---
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-05-16 00:44:29 +00:00
Onuralp SEZER 1776bf1670 Merge pull request #1116 from jeslinpjames/RichLabelAnnotator
Adds support for unicode labels with new `RichLabelAnnotator` class
2024-05-15 19:07:51 +03:00
pre-commit-ci[bot] d983177c3a fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-15 19:01:16 +03:00
Onuralp SEZER 7b259145bb Merge branch 'develop' into RichLabelAnnotator 2024-05-15 18:53:25 +03:00
Onuralp SEZER 24d1840ea1 docs: 📝 RichLabelAnnotator documentation added into docs and minor var fixes
Signed-off-by: Onuralp SEZER <thunderbirdtr@gmail.com>
2024-05-15 18:35:36 +03:00
Linas Kondrackis f8f3647a98 Removed suprplus NMM code for 20% speedup 2024-05-15 15:32:26 +03:00
Linas Kondrackis 559ef90d83 Simplify box_non_max_merge 2024-05-15 12:14:24 +03:00
Linas Kondrackis 0e2eec08c8 Revert np.bool comparisons with is
* Ruff complains when `== True` is used
* Different behaviour with `is True`
2024-05-15 11:48:48 +03:00
Linas Kondrackis 53f345e916 Minor renaming 2024-05-15 11:35:59 +03:00
Linas Kondrackis 6c40935266 box_non_max_merge: use our functions to compute iou 2024-05-15 11:32:30 +03:00
Linas Kondrackis 145b5fe56c Rename to batch_box_non_max_merge to box_non_max_merge_batch 2024-05-15 10:46:56 +03:00
Onuralp SEZER aed9221307 Merge pull request #1198 from xaristeidou/develop
Correct sentence spacing in `annotators/utils.py`
2024-05-15 10:44:37 +03:00
pre-commit-ci[bot] f08404eb7d fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-15 06:56:08 +00:00
magda skoczen aab861c2db test_coco_annotations_to_detections result matrices defined in place 2024-05-15 08:55:47 +02:00
Christoforos Aristeidou 9c0d647fdf Merge branch 'correct-spacing' into develop 2024-05-15 09:53:16 +03:00
Christoforos Aristeidou 5ef934e780 fixed sentence spacing 2024-05-15 09:51:55 +03:00
Linas Kondrackis 2d740bdcb6 fix: merge_object_detection_pair 2024-05-15 09:38:58 +03:00
Linas Kondrackis d2d50fbe46 renamed bbox -> xyxy 2024-05-15 09:26:18 +03:00
Linas Kondrackis 26bafec8f7 Test box_non_max_merge, rename threshold,to __init__ 2024-05-15 09:23:34 +03:00
Linas Kondrackis 8014e88944 Test box_non_max_merge 2024-05-14 17:42:47 +03:00
Linas Kondrackis c3b77d05c0 Rename, remove functions, unit-test & change merge_object_detection_pair 2024-05-14 17:13:33 +03:00
LinasKo 2eb0c7c242 Merge remote-tracking branch 'upstream/develop' into add_nmm_to_detections 2024-05-14 09:46:11 +03:00
Onuralp SEZER 41a08b87be Merge pull request #1193 from roboflow/pre-commit-ci-update-config
chore(pre_commit): ⬆ pre_commit autoupdate
2024-05-13 21:14:50 +03:00
pre-commit-ci[bot] 2bcd81e5fd chore(pre_commit): ⬆ pre_commit autoupdate
updates:
- [github.com/astral-sh/ruff-pre-commit: v0.4.3 → v0.4.4](https://github.com/astral-sh/ruff-pre-commit/compare/v0.4.3...v0.4.4)
2024-05-13 17:41:06 +00:00
SkalskiP 19396771f1 bump package version from 0.21.0rc4 to 0.21.0rc5 2024-05-13 15:58:22 +02:00
Onuralp SEZER f5324897a3 Merge pull request #1189 from roboflow/dependabot/pip/mkdocs-material-9.5.22
⬆️ Bump mkdocs-material from 9.5.21 to 9.5.22
2024-05-13 16:56:57 +03:00
Piotr Skalski cd8a2be04b Merge pull request #1178 from roboflow/feat/inference-slicer-segmentation
Feat/inference slicer segmentation
2024-05-13 15:55:02 +02:00
Linas Kondrackis 8901192b92 ruff 2024-05-13 16:53:06 +03:00
Linas Kondrackis a9044e4fed Merge branch 'develop' into feat/inference-slicer-segmentation 2024-05-13 16:52:50 +03:00
Linas Kondrackis 85e4c0ec65 Slicer: highlight & mask docstring 2024-05-13 16:51:59 +03:00
Linas Kondrackis 93398108ee Slier docs: remove transfomer example - has issues. 2024-05-13 16:26:35 +03:00
Piotr Skalski f41adca384 Merge pull request #1173 from roboflow/vertex_label_annotator
`VertexLabelAnnotator`
2024-05-13 15:23:51 +02:00
SkalskiP d64bb3879c Merge remote-tracking branch 'origin/vertex_label_annotator' into vertex_label_annotator 2024-05-13 15:21:35 +02:00
SkalskiP 452e1f1ea4 more VertexLabelAnnotator docs 2024-05-13 15:21:25 +02:00
Linas Kondrackis 45e5f49c5a Infrence slicer docs: fix callbacks in transfomers 2024-05-13 16:20:05 +03:00
LinasKo 4c36b39f94 Untested: Small object segmentationation 2024-05-13 15:41:43 +03:00
pre-commit-ci[bot] e13c7dc22c fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-13 12:31:37 +00:00
SkalskiP 713719a582 Merge remote-tracking branch 'origin/vertex_label_annotator' into vertex_label_annotator 2024-05-13 14:31:12 +02:00
SkalskiP 051fe5178b VertexLabelAnnotator plugged into docs 2024-05-13 14:30:55 +02:00
pre-commit-ci[bot] 1ebccebf4c fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-13 12:01:26 +00:00
SkalskiP f56d7a1733 changes after code review 2024-05-13 14:01:07 +02:00
LinasKo 82ab6c57cb infrenceSlicer: resolution_wh 2024-05-13 14:14:42 +03:00
pre-commit-ci[bot] cccacab621 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-13 10:25:48 +00:00
SkalskiP 59b273ba87 small refactor 2024-05-13 12:25:25 +02:00
pre-commit-ci[bot] 9a1c11218c fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-13 10:06:57 +00:00
SkalskiP d21c98a4d2 docs updated; rle_to_mask and mask_to_rle added to __init__.py 2024-05-13 12:06:38 +02:00
Linas Kondrackis 816aecb51b PR comments: tuples, docs, optional 2024-05-13 11:35:23 +03:00
dependabot[bot] 3c8995758d ⬆️ Bump mkdocs-material from 9.5.21 to 9.5.22
Bumps [mkdocs-material](https://github.com/squidfunk/mkdocs-material) from 9.5.21 to 9.5.22.
- [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.21...9.5.22)

---
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-05-13 01:21:27 +00:00
pre-commit-ci[bot] 14b57345a7 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-12 21:31:18 +00:00
magda skoczen d292cbf80e Merge branch '1114_RLE_support_for_COCO' of github.com:emSko/supervision into 1114_RLE_support_for_COCO 2024-05-12 23:02:45 +02:00
magda skoczen 8c857dd9a6 speed up rle to mask 2024-05-12 23:02:22 +02:00
Onuralp SEZER acfabc247f Merge pull request #1185 from roboflow/dependabot/pip/ruff-0.4.4
⬆️ Bump ruff from 0.4.3 to 0.4.4
2024-05-11 23:54:29 +03:00
Onuralp SEZER 61a63c83d9 Merge pull request #1188 from roboflow/docs/missing-return-in-slicer-callback
Minor docs update: missing return in inference slicer callback
2024-05-11 21:56:13 +03:00
Linas Kondrackis 528c960587 Minor docs update: missing return in inference slicer callback 2024-05-11 13:38:59 +03:00
Linas Kondrackis 6c6171b5d5 Simpify passing of shape 2024-05-10 18:25:02 +03:00
Linas Kondrackis b8efa25e93 Merge branch 'develop' into feat/inference-slicer-segmentation 2024-05-10 17:18:07 +03:00
SkalskiP 17c8e41fb3 bump version from 0.21.0rc3 to 0.21.0rc4 2024-05-10 15:50:03 +02:00
Piotr Skalski 0c3594432c Merge pull request #1177 from roboflow/fix/detections-merge-flexibility
More flexibility in Detections.merge
2024-05-10 15:40:06 +02:00
SkalskiP a8c44cfaff ready for merge 2024-05-10 15:36:44 +02:00
pre-commit-ci[bot] 3d0c3d9182 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-10 13:08:35 +00:00
SkalskiP 2364abf481 small error message update + few more test cases for merge_data 2024-05-10 15:08:18 +02:00
pre-commit-ci[bot] 7bd92b096f fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-10 08:18:38 +00:00
magda skoczen 39477feaf6 Merge branch '1114_RLE_support_for_COCO' of github.com:emSko/supervision into 1114_RLE_support_for_COCO 2024-05-10 10:17:13 +02:00
magda skoczen e4e66f8a9a faster mask to rle 2024-05-10 10:16:34 +02:00
dependabot[bot] 3b61ee674e ⬆️ Bump ruff from 0.4.3 to 0.4.4
Bumps [ruff](https://github.com/astral-sh/ruff) from 0.4.3 to 0.4.4.
- [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.3...v0.4.4)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-05-10 00:28:34 +00:00
Linas Kondrackis 01f7eb5be6 Retain type info by not excluding empty detections 2024-05-09 18:19:51 +03:00
pre-commit-ci[bot] 4cd1fbcef9 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-09 14:15:31 +00:00
Linas Kondrackis b6a55694f2 Move type resolution logic to loop where it's used 2024-05-09 17:12:53 +03:00
Linas Kondrackis 8c58ebe30d Roll back flex-merge on data, merge when key missing 2024-05-09 17:06:51 +03:00
Piotr Skalski 77034700dd Merge pull request #767 from DrawingProcess/mmdetectionmask
Mmdetection mask
2024-05-09 13:19:00 +02:00
Linas Kondrackis 1ebbe3a8d1 Removed comments, deindented, removed unused var 2024-05-09 09:17:37 +03:00
Onuralp SEZER 617bd30c5f Merge pull request #1175 from roboflow/pre-commit-ci-update-config
chore(pre_commit): ⬆ pre_commit autoupdate
2024-05-08 22:50:20 +03:00
Onuralp SEZER 2e8720f156 Merge pull request #1176 from roboflow/dependabot/pip/jinja2-3.1.4
⬆️ Bump jinja2 from 3.1.3 to 3.1.4
2024-05-08 22:49:59 +03:00
Raif Olson c47b0ce990 filter out detections with zero area. 2024-05-08 11:07:14 -04:00
Linas Kondrackis 45563dfddf InferenceSlicer: Now works with segmentation 2024-05-08 14:07:37 +03:00
pre-commit-ci[bot] 008711aac4 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-08 10:50:32 +00:00
magda skoczen 649e27323d fix the line lengths 2024-05-08 12:49:25 +02:00
pre-commit-ci[bot] 36a301e7fc fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-07 16:01:37 +00:00
magda skoczen aac1d8862a assertion for valid mask in mask_to_rle function 2024-05-07 18:01:14 +02:00
pre-commit-ci[bot] d59ec0f223 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-07 15:36:47 +00:00
magda skoczen 3618ac35ec merge 2024-05-07 17:36:26 +02:00
magda skoczen a9f821c28a Assertion error when number of pixel in RLE does not match the nuber of pixels computed as width*height 2024-05-07 17:34:13 +02:00
Linas Kondrackis 7bb94ce966 Detections.merge merges None and []
* Detections.merge is much friendlier now. If there's a None
  or an empty array, it will merge it happily rather than
  complaining that everything needs to be either None or [].
* Data merge follows suit.
2024-05-07 17:30:12 +03:00
Linas Kondrackis fb49be8197 Tests for the new merge function 2024-05-07 16:09:05 +03:00
Piotr Skalski d7b6af84e6 Update README.md
fix errors in example commands
2024-05-07 12:25:41 +02:00
Piotr Skalski d3b845fea5 Merge pull request #1172 from ManzarIMalik/develop
Update README.md
2024-05-07 12:24:35 +02:00
Piotr Skalski 330eae4411 Merge pull request #1166 from tc360950/fix-inreasing-memory-consumption-in-bytetrack
Fix ever increasing memory consumption in ByteTrack
2024-05-07 12:20:18 +02:00
pre-commit-ci[bot] 6b5dacd8e3 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-06 22:22:49 +00:00
magda skoczen 88a43cc795 unit tests for rle_to_mask and mask_to_rle functions 2024-05-07 00:22:24 +02:00
pre-commit-ci[bot] a941583bb0 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-06 21:07:51 +00:00
magda skoczen 2727152465 merge with upstream 2024-05-06 23:07:27 +02:00
dependabot[bot] 4d25437459 ⬆️ Bump jinja2 from 3.1.3 to 3.1.4
Bumps [jinja2](https://github.com/pallets/jinja) from 3.1.3 to 3.1.4.
- [Release notes](https://github.com/pallets/jinja/releases)
- [Changelog](https://github.com/pallets/jinja/blob/main/CHANGES.rst)
- [Commits](https://github.com/pallets/jinja/compare/3.1.3...3.1.4)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-05-06 20:43:41 +00:00
magda skoczen 3ade7f060a fix order caused error with mask generation in coco_annotations_to_detections 2024-05-06 22:42:26 +02:00
magda skoczen 18a790e9ea typing chanches and doc strings for rle_to_mask and mask_to_rle functions 2024-05-06 20:21:02 +02:00
pre-commit-ci[bot] 478fbd5751 chore(pre_commit): ⬆ pre_commit autoupdate
updates:
- [github.com/astral-sh/ruff-pre-commit: v0.4.2 → v0.4.3](https://github.com/astral-sh/ruff-pre-commit/compare/v0.4.2...v0.4.3)
2024-05-06 17:48:31 +00:00
pre-commit-ci[bot] 7823e0de89 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-06 16:16:39 +00:00
SkalskiP ab0882dd55 initial version of VertexLabelAnnotator 2024-05-06 18:15:05 +02:00
SkalskiP ec6864ff04 roll back new draw_rounded_rectangle implementation 2024-05-06 18:00:13 +02:00
SkalskiP 81786ff9d3 Merge remote-tracking branch 'origin/vertex_label_annotator' into vertex_label_annotator 2024-05-06 17:40:43 +02:00
SkalskiP 95c243c058 better draw_rounded_rectangle implementation 2024-05-06 17:40:33 +02:00
pre-commit-ci[bot] 204669b08c fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-06 14:25:15 +00:00
Linas Kondrackis 97c407101a NMM: Move detections merge into Detections class.
* No other changes!
2024-05-06 17:24:41 +03:00
pre-commit-ci[bot] bee3252110 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-06 14:22:34 +00:00
Linas Kondrackis d7e52bee26 NMM: Add None-checks, fix area normalization, style 2024-05-06 17:22:04 +03:00
Linas Kondrackis b1598733c2 Merge remote-tracking branch 'upstream/develop' into add_nmm_to_detections 2024-05-06 17:01:04 +03:00
pre-commit-ci[bot] 5c539c3bda fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-06 13:49:24 +00:00
SkalskiP 5d38120743 added from_xyxy and as_xyxy_int_tuple methods to Rect. added draw_rounded_rectangle function. 2024-05-06 15:39:59 +02:00
Manzar Iqbal Malik aaf5df2f6a Update README.md
Aligned draw zones file name for both examples, fixed file name for ultralytics example
2024-05-06 12:15:38 +01:00
Onuralp SEZER 447ef41fc4 Merge pull request #1171 from roboflow/dependabot/pip/ruff-0.4.3
⬆️ Bump ruff from 0.4.2 to 0.4.3
2024-05-06 12:41:10 +03:00
dependabot[bot] edd944fff8 ⬆️ Bump ruff from 0.4.2 to 0.4.3
Bumps [ruff](https://github.com/astral-sh/ruff) from 0.4.2 to 0.4.3.
- [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.2...v0.4.3)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-05-06 01:18:43 +00:00
Onuralp SEZER a75efbbf73 Merge pull request #1170 from roboflow/dependabot/pip/mkdocstrings-0.25.1
⬆️ Bump mkdocstrings from 0.25.0 to 0.25.1
2024-05-06 04:16:35 +03:00
Onuralp SEZER e9c8a80823 Merge pull request #1167 from roboflow/dependabot/pip/mike-2.1.1
⬆️ Bump mike from 2.1.0 to 2.1.1
2024-05-06 04:16:01 +03:00
Onuralp SEZER 0b92417948 Merge pull request #1168 from roboflow/dependabot/pip/mkdocs-material-9.5.21
⬆️ Bump mkdocs-material from 9.5.20 to 9.5.21
2024-05-06 04:15:20 +03:00
dependabot[bot] aebbd01830 ⬆️ Bump mkdocstrings from 0.25.0 to 0.25.1
Bumps [mkdocstrings](https://github.com/mkdocstrings/mkdocstrings) from 0.25.0 to 0.25.1.
- [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.25.0...0.25.1)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-05-06 01:15:08 +00:00
Onuralp SEZER c3ebccabe8 Merge pull request #1169 from roboflow/dependabot/pip/jupytext-1.16.2
⬆️ Bump jupytext from 1.16.1 to 1.16.2
2024-05-06 04:14:43 +03:00
dependabot[bot] ff52352b00 ⬆️ Bump jupytext from 1.16.1 to 1.16.2
Bumps [jupytext](https://github.com/mwouts/jupytext) from 1.16.1 to 1.16.2.
- [Release notes](https://github.com/mwouts/jupytext/releases)
- [Changelog](https://github.com/mwouts/jupytext/blob/main/CHANGELOG.md)
- [Commits](https://github.com/mwouts/jupytext/compare/v1.16.1...v1.16.2)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-05-06 01:12:45 +00:00
dependabot[bot] f7d21acd3a ⬆️ Bump mkdocs-material from 9.5.20 to 9.5.21
Bumps [mkdocs-material](https://github.com/squidfunk/mkdocs-material) from 9.5.20 to 9.5.21.
- [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.20...9.5.21)

---
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-05-06 01:09:12 +00:00
dependabot[bot] 92d56eda15 ⬆️ Bump mike from 2.1.0 to 2.1.1
Bumps [mike](https://github.com/jimporter/mike) from 2.1.0 to 2.1.1.
- [Release notes](https://github.com/jimporter/mike/releases)
- [Changelog](https://github.com/jimporter/mike/blob/master/CHANGES.md)
- [Commits](https://github.com/jimporter/mike/compare/v2.1.0...v2.1.1)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-05-06 01:06:46 +00:00
tc360950 d37a5f90a4 Remove old tracklets from ByteTrack.removed_tracks collection 2024-05-05 17:16:05 +02:00
pre-commit-ci[bot] 869204d42d fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-05 11:59:23 +00:00
magda skoczen dc1ce02860 move rle encode decode functions to dataset/utils.py 2024-05-04 10:34:08 +02:00
Onuralp SEZER 34a5b34c88 Merge pull request #1162 from roboflow/dependabot/pip/examples/speed_estimation/tqdm-4.66.3
Bump tqdm from 4.66.1 to 4.66.3 in /examples/speed_estimation
2024-05-04 01:26:51 +03:00
dependabot[bot] f72d06b05e Bump tqdm from 4.66.1 to 4.66.3 in /examples/speed_estimation
Bumps [tqdm](https://github.com/tqdm/tqdm) from 4.66.1 to 4.66.3.
- [Release notes](https://github.com/tqdm/tqdm/releases)
- [Commits](https://github.com/tqdm/tqdm/compare/v4.66.1...v4.66.3)

---
updated-dependencies:
- dependency-name: tqdm
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-05-03 21:51:32 +00:00
magda skoczen 4a068ff8d7 binary mask to RL encoding 2024-05-03 09:16:13 +02:00
Onuralp SEZER 044a8fac06 Merge pull request #1160 from roboflow/dependabot/pip/mike-2.1.0
⬆️ Bump mike from 2.0.0 to 2.1.0
2024-05-03 04:04:46 +03:00
Onuralp SEZER a88089ced7 Merge pull request #1159 from roboflow/dependabot/pip/tqdm-4.66.4
⬆️ Bump tqdm from 4.66.2 to 4.66.4
2024-05-03 04:03:58 +03:00
dependabot[bot] 29b0c514cf ⬆️ Bump mike from 2.0.0 to 2.1.0
Bumps [mike](https://github.com/jimporter/mike) from 2.0.0 to 2.1.0.
- [Release notes](https://github.com/jimporter/mike/releases)
- [Changelog](https://github.com/jimporter/mike/blob/master/CHANGES.md)
- [Commits](https://github.com/jimporter/mike/compare/v2.0.0...v2.1.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-05-03 00:36:24 +00:00
dependabot[bot] 7d5a0bce45 ⬆️ Bump tqdm from 4.66.2 to 4.66.4
Bumps [tqdm](https://github.com/tqdm/tqdm) from 4.66.2 to 4.66.4.
- [Release notes](https://github.com/tqdm/tqdm/releases)
- [Commits](https://github.com/tqdm/tqdm/compare/v4.66.2...v4.66.4)

---
updated-dependencies:
- dependency-name: tqdm
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-05-03 00:33:20 +00:00
magda skoczen 6913ecf54d 2 annotations with segmentation, one polygon one RLE 2024-05-03 01:19:01 +02:00
magda skoczen 7f114cba4c RLE decoding 2024-05-03 00:24:46 +02:00
magda skoczen cc5e72dd5b test for RLE format 2024-05-02 22:08:08 +02:00
Piotr Skalski 177ab6ad4d Merge pull request #1138 from roboflow/feat/keypoints-from-yolo-nas
Implemented `from_yolo_nas` for keypoints
2024-05-02 16:11:09 +02:00
pre-commit-ci[bot] 7e79fa3d07 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-02 13:34:14 +00:00
Linas Kondrackis 347b75935b Ruff 2024-05-02 16:31:48 +03:00
Linas Kondrackis 079008cd17 from_yolo_nas - None class_id & names if not found 2024-05-02 16:30:01 +03:00
magda skoczen e30d4a9abb add test for generating annotation with mask 2024-05-02 12:49:31 +02:00
pre-commit-ci[bot] aab3ed2ba9 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-05-01 12:23:54 +00:00
Linas Kondrackis ba30244add Remove hardcoding of class_names, class_id.
* Still hardcoded ID to -1 and name to "" if not provided - this lets us
  stick to (n,) shape.
* Found no way to add class_names to pose tracker, so used the response
  of YOLO NAS detection instead, to check what the response looks like.
2024-05-01 15:20:50 +03:00
Onuralp SEZER 55e8f16029 Merge pull request #1158 from roboflow/dependabot/pip/mkdocs-git-revision-date-localized-plugin-1.2.5
⬆️ Bump mkdocs-git-revision-date-localized-plugin from 1.2.4 to 1.2.5
2024-05-01 03:46:57 +03:00
dependabot[bot] 33e69b2da3 ⬆️ Bump mkdocs-git-revision-date-localized-plugin
Bumps [mkdocs-git-revision-date-localized-plugin](https://github.com/timvink/mkdocs-git-revision-date-localized-plugin) from 1.2.4 to 1.2.5.
- [Release notes](https://github.com/timvink/mkdocs-git-revision-date-localized-plugin/releases)
- [Commits](https://github.com/timvink/mkdocs-git-revision-date-localized-plugin/compare/v1.2.4...v1.2.5)

---
updated-dependencies:
- dependency-name: mkdocs-git-revision-date-localized-plugin
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-05-01 00:35:55 +00:00
Piotr Skalski 9fe3170ead Merge pull request #1157 from roboflow/fix/pin_inference_version_in_exampels_to_9.17.0
pin inference version to 0.9.17
2024-04-30 16:09:07 +02:00
SkalskiP ffda94b1e5 pin inference version to 0.9.17 2024-04-30 16:06:02 +02:00
SkalskiP 7fd5d80a3b bump version from 0.21.0rc2 to 0.21.0rc3 2024-04-30 12:30:44 +02:00
Onuralp SEZER b67d9b475f Merge pull request #1155 from roboflow/dependabot/pip/nbconvert-7.16.4
⬆️ Bump nbconvert from 7.16.3 to 7.16.4
2024-04-30 13:24:17 +03:00
Onuralp SEZER d859842fa3 Merge pull request #1156 from roboflow/dependabot/pip/mkdocs-material-9.5.20
⬆️ Bump mkdocs-material from 9.5.19 to 9.5.20
2024-04-30 13:24:03 +03:00
Onuralp SEZER 131c6ffefb Merge pull request #1153 from roboflow/pre-commit-ci-update-config
chore(pre_commit): ⬆ pre_commit autoupdate
2024-04-30 13:23:49 +03:00
dependabot[bot] 71fd3178cc ⬆️ Bump mkdocs-material from 9.5.19 to 9.5.20
Bumps [mkdocs-material](https://github.com/squidfunk/mkdocs-material) from 9.5.19 to 9.5.20.
- [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.19...9.5.20)

---
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-30 00:35:39 +00:00
dependabot[bot] 71919f1d6f ⬆️ Bump nbconvert from 7.16.3 to 7.16.4
Bumps [nbconvert](https://github.com/jupyter/nbconvert) from 7.16.3 to 7.16.4.
- [Release notes](https://github.com/jupyter/nbconvert/releases)
- [Changelog](https://github.com/jupyter/nbconvert/blob/main/CHANGELOG.md)
- [Commits](https://github.com/jupyter/nbconvert/compare/v7.16.3...v7.16.4)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-30 00:33:04 +00:00
SkalskiP 4732b6f1d0 bump version from 0.21.0rc1 to 0.21.0rc2 2024-04-29 22:58:13 +02:00
Piotr Skalski c024b62020 Merge pull request #1154 from roboflow/fix/pin_inference_version_in_examples_to_fix_issues_related_to_braking_changes
pin inference version in examples
2024-04-29 21:50:37 +02:00
SkalskiP d4b1375db7 pin inference version 2024-04-29 21:46:07 +02:00
Piotr Skalski 71200a5942 Merge pull request #1147 from roboflow/feat/keypoints-from-inference
Add `from_inference` to KeyPoints
2024-04-29 20:40:17 +02:00
SkalskiP 66f6a86bbf add Roboflow API KEY to example 2024-04-29 20:37:56 +02:00
SkalskiP a70588284a add Roboflow API example 2024-04-29 20:36:05 +02:00
pre-commit-ci[bot] 67160c96b0 chore(pre_commit): ⬆ pre_commit autoupdate
updates:
- [github.com/astral-sh/ruff-pre-commit: v0.4.1 → v0.4.2](https://github.com/astral-sh/ruff-pre-commit/compare/v0.4.1...v0.4.2)
2024-04-29 17:52:51 +00:00
LinasKo 7331577e69 keypoints, from_inference: removed class_name option 2024-04-29 13:37:37 +03:00
Onuralp SEZER 5f00d8b595 Merge pull request #1151 from roboflow/dependabot/pip/tox-4.15.0
⬆️ Bump tox from 4.14.2 to 4.15.0
2024-04-29 12:03:30 +03:00
Onuralp SEZER 88209f233d Merge pull request #1150 from roboflow/dependabot/pip/mkdocstrings-0.25.0
⬆️ Bump mkdocstrings from 0.24.3 to 0.25.0
2024-04-29 12:03:09 +03:00
Onuralp SEZER d51067164a Merge pull request #1149 from roboflow/dependabot/pip/pytest-8.2.0
⬆️ Bump pytest from 8.1.1 to 8.2.0
2024-04-29 12:02:46 +03:00
pre-commit-ci[bot] 0dd8d7dca8 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-29 06:53:36 +00:00
Linas Kondrackis 7c39d9dc8d Merge branch 'develop' into feat/keypoints-from-inference 2024-04-29 09:53:22 +03:00
Linas Kondrackis d2d69f986e from_infernece: Example suggests users find their own model
* Example incorrectly suggested yolov8s-640
* Replaced with "<POSE_MODEL_ID>" until we have a COCO human pose model
  on prod. I don't think "horse-pose/3" is helpful - the use case is
  uncommon and the training quality is poor.
2024-04-29 09:46:12 +03:00
dependabot[bot] df0b2df2f6 ⬆️ Bump tox from 4.14.2 to 4.15.0
Bumps [tox](https://github.com/tox-dev/tox) from 4.14.2 to 4.15.0.
- [Release notes](https://github.com/tox-dev/tox/releases)
- [Changelog](https://github.com/tox-dev/tox/blob/main/docs/changelog.rst)
- [Commits](https://github.com/tox-dev/tox/compare/4.14.2...4.15.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-29 01:25:37 +00:00
dependabot[bot] 31844c165b ⬆️ Bump mkdocstrings from 0.24.3 to 0.25.0
Bumps [mkdocstrings](https://github.com/mkdocstrings/mkdocstrings) from 0.24.3 to 0.25.0.
- [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.3...0.25.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-29 01:24:07 +00:00
dependabot[bot] c5a2f87bb9 ⬆️ Bump pytest from 8.1.1 to 8.2.0
Bumps [pytest](https://github.com/pytest-dev/pytest) from 8.1.1 to 8.2.0.
- [Release notes](https://github.com/pytest-dev/pytest/releases)
- [Changelog](https://github.com/pytest-dev/pytest/blob/main/CHANGELOG.rst)
- [Commits](https://github.com/pytest-dev/pytest/compare/8.1.1...8.2.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-29 01:20:56 +00:00
Piotr Skalski 6ef9ba7390 Merge pull request #1148 from roboflow/fix/code_examples_after_supervision_0.20.0_release
fix/code examples after supervision 0.20.0 release
2024-04-26 17:59:25 +02:00
SkalskiP a532670611 bump version from 0.20.0 to 0.21.0rc1 2024-04-26 17:55:34 +02:00
SkalskiP ba2d30d110 calculate_dynamic_line_thickness -> calculate_optimal_line_thickness
`calculate_dynamic_text_scale` -> `calculate_optimal_text_scale`
2024-04-26 17:36:50 +02:00
Linas Kondrackis 619da9575a pre-commit tidy-up 2024-04-26 17:55:17 +03:00
LinasKo 25bdb560eb from_inference, support direct inference results 2024-04-26 17:53:19 +03:00
Onuralp SEZER 9b447296bf Merge pull request #1142 from roboflow/dependabot/pip/ruff-0.4.2
⬆️ Bump ruff from 0.4.1 to 0.4.2
2024-04-26 03:42:20 +03:00
Onuralp SEZER 4a16d66bfb Merge pull request #1141 from roboflow/dependabot/pip/mkdocs-material-9.5.19
⬆️ Bump mkdocs-material from 9.5.18 to 9.5.19
2024-04-26 03:41:54 +03:00
dependabot[bot] 8436f52f8a ⬆️ Bump ruff from 0.4.1 to 0.4.2
Bumps [ruff](https://github.com/astral-sh/ruff) from 0.4.1 to 0.4.2.
- [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.1...v0.4.2)

---
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-26 00:33:10 +00:00
dependabot[bot] 059583e2ba ⬆️ Bump mkdocs-material from 9.5.18 to 9.5.19
Bumps [mkdocs-material](https://github.com/squidfunk/mkdocs-material) from 9.5.18 to 9.5.19.
- [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.18...9.5.19)

---
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-26 00:31:25 +00:00
pre-commit-ci[bot] 4bd593fe3c fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-25 12:02:23 +00:00
Linas Kondrackis 399342513a Keypoints: rm NAS skeleton, improve docs examples 2024-04-25 15:00:01 +03:00
Linas Kondrackis c8c2ff5c45 Minor styling 2024-04-25 12:53:09 +03:00
Linas Kondrackis 18b3c17ed4 Styling 2024-04-25 12:42:33 +03:00
Linas Kondrackis cab06f2c2b Implementation of from_yolo_nas for keypoints
* Missing batch image support
2024-04-25 12:29:08 +03:00
Onuralp SEZER 2b53216a0b Merge pull request #1137 from roboflow/dependabot/pip/mypy-1.10.0
⬆️ Bump mypy from 1.9.0 to 1.10.0
2024-04-25 03:51:18 +03:00
dependabot[bot] e253f86e8f ⬆️ Bump mypy from 1.9.0 to 1.10.0
Bumps [mypy](https://github.com/python/mypy) from 1.9.0 to 1.10.0.
- [Changelog](https://github.com/python/mypy/blob/master/CHANGELOG.md)
- [Commits](https://github.com/python/mypy/compare/1.9.0...v1.10.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-25 00:46:24 +00:00
Piotr Skalski df4c546c10 Merge pull request #1076 from rolson24/add-minimum_consecutive_frames-to-bytetrack-better
add minimum_consecutive_frames to bytetrack
2024-04-25 00:25:18 +02:00
Piotr Skalski 25fc1ab6fa Merge pull request #1115 from jeslinpjames/update-examples
Update examples to remove `frame_resloution_wh` in [PolygonZone]
2024-04-24 22:43:47 +02:00
SkalskiP a45341ce63 final cleanup; setting supervision>=0.20.0 in requirements.txt and refactoring stream processing scripts 2024-04-24 22:41:59 +02:00
Piotr Skalski e93ef041d4 Merge pull request #1133 from roboflow/main
Merge pull request #1127 from roboflow/develop
2024-04-24 22:22:42 +02:00
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
Jeslin P James df4a6f857c added docs for RichLabelAnnotator 2024-04-13 18:58:18 +05:30
pre-commit-ci[bot] cb220479eb fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-13 13:16:16 +00:00
Jeslin P James 8bb8ce0316 changed error message and formatted code 2024-04-13 18:03:08 +05:30
Jeslin P James 8255bcb1ca Moved resolve_text_background_xyxy() function into utils.py 2024-04-13 17:43:52 +05:30
Jeslin P James 8329d155e4 Use default font when font_path isnt specified 2024-04-13 17:27:27 +05:30
Jeslin P James a41eea7c45 Merge branch 'develop' of github.com:jeslinpjames/supervision into RichLabelAnnotator 2024-04-13 13:36:26 +05:30
pre-commit-ci[bot] d531c59f85 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-13 05:39:05 +00:00
Jeslin P James 15b1473c2f Updated examples to remove frame_resolution_wh from PolygonZone 2024-04-13 10:28:11 +05:30
Jeslin P James 26c2a7ef9c updated examples 2024-04-13 10:18:30 +05:30
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
pre-commit-ci[bot] 361e444f53 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-11 13:27:43 +00:00
Jeslin P James b7607c6f15 Updated PolyZone class to compute frame_resolution_wh based on polygon coordinates 2024-04-11 18:57:30 +05:30
Raif Olson 07756328db Merge branch 'add-minimum_consecutive_frames-to-bytetrack-better' of https://github.com/rolson24/supervision into add-minimum_consecutive_frames-to-bytetrack-better 2024-04-11 09:27:28 -04:00
Raif Olson f98ded49a2 fix 2024-04-11 09:27:24 -04:00
pre-commit-ci[bot] bcb31f8809 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-11 13:21:51 +00:00
Raif Olson b1d5d4faf0 fix to exactly match existing release version when minimum_consecutive_frames = 1 2024-04-11 09:21:32 -04:00
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
Raif Olson 7924a13dc5 only assign external track_id once 2024-04-11 08:28:08 -04:00
pre-commit-ci[bot] 755f292ed1 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-11 12:21:46 +00:00
Raif Olson 6166d92458 fix reassigning track_id after a track is re-activated. 2024-04-11 08:21:26 -04:00
Piotr Skalski ed225187b2 Update README.md 2024-04-11 14:09:02 +02:00
mario-dg 166a8da9a0 Implement Feedback 2024-04-11 12:22:44 +02:00
pre-commit-ci[bot] 2c9a1f69c5 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-10 17:57:46 -04:00
pre-commit-ci[bot] a2ab113f21 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-04-10 17:57:46 -04:00
Raif Olson eaff97f902 add external and internal track_ids to keep valid track ids sequential 2024-04-10 17:57:45 -04: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
mario-dg 5f0dcc2cb2 Merge branch 'develop' into add_nmm_to_detections to resolve conflicts 2024-04-09 18:50:55 +02:00
Jeslin P James 9e906c78f5 annotate function added in RichLabelAnnotator 2024-04-09 22:14:36 +05:30
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
Jeslin P James 2417b36006 resolve_text_background_xyxy() function added to RichLabelAnnotator 2024-04-09 20:39:53 +05:30
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
Jeslin P James 1a7309e7c9 RichLabelAnnotator class added 2024-04-09 16:51:41 +05:30
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
Raif Olson ad0e6c3b51 Add minimum consecutive frames to ByteTrack 2024-03-29 16:59:29 -04: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
SkalskiP ccc7118bcb bump version from 0.20.0rc1 to 0.20.0rc2 2024-03-28 15:41:16 +01:00
Piotr Skalski 2cccfc5b62 Merge pull request #1067 from roboflow/ci/dev-ci
fix: 🐞 ci trigger error fix
2024-03-28 15:39:00 +01:00
Onuralp SEZER 93584cbb89 fix: 🐞 ci trigger error fix
Signed-off-by: Onuralp SEZER <thunderbirdtr@gmail.com>
2024-03-28 17:29:10 +03:00
Piotr Skalski 5bfc977fac Merge pull request #1065 from roboflow/revert-1064-ci/dev-ci
Revert "fix: 🐞 ci trigger error fix"
2024-03-28 15:21:42 +01:00
Piotr Skalski 16c41d9d5d Revert "fix: 🐞 ci trigger error fix" 2024-03-28 15:19:24 +01:00
SkalskiP 81c2a09430 bump version from 0.19.0 to 0.20.0rc1 2024-03-28 15:09:23 +01:00
Piotr Skalski 16b7222012 Merge pull request #1054 from Griffin-Sullivan/transformers-segmentation
Add segmentation model support to from_transformers
2024-03-28 14:40:08 +01:00
Piotr Skalski 6b2136d57b Merge pull request #1064 from roboflow/ci/dev-ci
fix: 🐞 ci trigger error fix
2024-03-28 14:38:50 +01:00
Piotr Skalski 908a1b4d89 Merge pull request #1049 from rolson24/fix-pr-bug
fix enumerate call
2024-03-28 14:36:40 +01:00
Onuralp SEZER 7e283d4eeb fix: 🐞 ci trigger error fix
Signed-off-by: Onuralp SEZER <thunderbirdtr@gmail.com>
2024-03-28 16:28:21 +03:00
Raif Olson a2aca62ecb merge develop branch and change back to using boolean indexing 2024-03-28 09:27:54 -04:00
Onuralp SEZER 0a5fb7b47e Merge pull request #1060 from roboflow/dependabot/pip/build-1.2.0
⬆️ Bump build from 1.1.1 to 1.2.0
2024-03-28 16:22:50 +03:00
Piotr Skalski 7132c034ab Merge pull request #1063 from roboflow/get_data_item_tests
`get_data_item` unit tests
2024-03-28 14:09:15 +01:00
pre-commit-ci[bot] dc5f841bae fix(pre_commit): 🎨 auto format pre-commit hooks 2024-03-28 13:06:47 +00:00
SkalskiP 64eef66b54 get_data_item unit tests 2024-03-28 14:04:21 +01:00
Raif Olson dc45c0a5e0 Merge remote-tracking branch 'origin/develop' into fix-pr-bug 2024-03-28 08:48:05 -04:00
Piotr Skalski 69563b8bbb Merge pull request #1062 from rolson24/fix-Detections-call-bug
fix Detections.get_data_item() bug (#1061)
2024-03-28 13:40:57 +01:00
pre-commit-ci[bot] 29ba24f89a fix(pre_commit): 🎨 auto format pre-commit hooks 2024-03-28 12:39:14 +00:00
Raif Olson da4404e875 More pythonic version of change 2024-03-28 08:38:50 -04:00
Raif Olson 089594f72d fix Detections.get_data_item() bug 2024-03-27 23:59:40 -04:00
pre-commit-ci[bot] e9edc2fb1d fix(pre_commit): 🎨 auto format pre-commit hooks 2024-03-28 03:39:22 +00:00
Raif Olson ad24d3811b Refactor update_with_detections for simplicity. Credit to @SkalskiP for the code. (had to change a few lines for bug fixes) 2024-03-27 23:38:55 -04:00
dependabot[bot] 8fb3ba70b0 ⬆️ Bump build from 1.1.1 to 1.2.0
Bumps [build](https://github.com/pypa/build) from 1.1.1 to 1.2.0.
- [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.1.1...1.2.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-28 00:56:05 +00:00
SkalskiP 34b80eb3c0 Fix YT videos paths 2024-03-27 09:12:45 +01:00
Piotr Skalski 3276973446 Update README.md 2024-03-27 00:14:19 +01:00
Piotr Skalskiandpre-commit-ci[bot] 725d95c6ce time in zone / dwell time demo (#1026)
* initial commit

* initial stream processing script

* fix(pre_commit): 🎨 auto format pre-commit hooks

* work in progress

* fix(pre_commit): 🎨 auto format pre-commit hooks

* work in progress

* fix(pre_commit): 🎨 auto format pre-commit hooks

* ultralytics file and stream versions ready

* fix(pre_commit): 🎨 auto format pre-commit hooks

* ultralytics file and stream versions ready

* class based filtering

* fix(pre_commit): 🎨 auto format pre-commit hooks

* timer improvements

* inference static file processing script

* fix(pre_commit): 🎨 auto format pre-commit hooks

* inference stream processing script

* fix(pre_commit): 🎨 auto format pre-commit hooks

* all scripts are working

* fix(pre_commit): 🎨 auto format pre-commit hooks

* all video or stream processing scripts refactored

* fix(pre_commit): 🎨 auto format pre-commit hooks

* README.md update

* fix(pre_commit): 🎨 auto format pre-commit hooks

* initial version of draw ones script

* fix(pre_commit): 🎨 auto format pre-commit hooks

* loading image or video, drawing multiple polygons, quiting app, and aborting currently drawn polygon works.

* fix(pre_commit): 🎨 auto format pre-commit hooks

* loading image or video, drawing multiple polygons, quiting app, and aborting currently drawn polygon works.

* fix(pre_commit): 🎨 auto format pre-commit hooks

* Dynamic drawing of currently edited polygon.

* fix(pre_commit): 🎨 auto format pre-commit hooks

* Drawing tool is ready.

* fix(pre_commit): 🎨 auto format pre-commit hooks

* Final touches.

* fix(pre_commit): 🎨 auto format pre-commit hooks

* Update README.md

* fix(pre_commit): 🎨 auto format pre-commit hooks

* Update README.md

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2024-03-27 00:12:12 +01:00
pre-commit-ci[bot] 13f85ae6cc fix(pre_commit): 🎨 auto format pre-commit hooks 2024-03-26 21:05:04 +00:00
Griffin-Sullivan c67078b53c Add segmentation model support to from_transformers 2024-03-26 17:04:43 -04:00
Piotr Skalski 42f9d4b69b Merge pull request #1053 from roboflow/fix/ci-publish-bug
ci: 👷 publish pypi on branch removed
2024-03-26 18:24:36 +01:00
Onuralp SEZER d41caed36f ci: 👷 publish pypi on branch removed
Signed-off-by: Onuralp SEZER <thunderbirdtr@gmail.com>
2024-03-26 18:38:04 +03:00
SkalskiP 5a040969d7 fix how-to links 2024-03-26 09:53:16 +01:00
Raif Olson 3ed4aeffff fix bugs in PR #1035
fix tuple unpacking bug in PR #1035

Fix bug with detections with un-initialized tracker_ids
2024-03-25 23:52:33 -04: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
Onuralp SEZER 97b8312570 Merge pull request #1045 from roboflow/pre-commit-ci-update-config
chore(pre_commit): ⬆ pre_commit autoupdate
2024-03-26 00:26:55 +03:00
Piotr Skalski 94e9719f20 Merge pull request #1048 from roboflow/docs/detect_small_objects_updates
Detect Small Objects documentation 2
2024-03-25 22:12:16 +01:00
SkalskiP 0d16b13e7a Added additional visualization 2024-03-25 22:09:23 +01:00
Piotr Skalski 5c03173c7c Merge pull request #1047 from roboflow/docs/detect_small_objects
Detect Small Objects documentation
2024-03-25 21:25:30 +01:00
pre-commit-ci[bot] cf88cc0384 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-03-25 20:14:17 +00:00
SkalskiP 15e17adef1 Detect Small Objects documentation 2024-03-25 21:11:47 +01:00
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
pre-commit-ci[bot] ca425a628d chore(pre_commit): ⬆ pre_commit autoupdate
updates:
- [github.com/astral-sh/ruff-pre-commit: v0.3.3 → v0.3.4](https://github.com/astral-sh/ruff-pre-commit/compare/v0.3.3...v0.3.4)
2024-03-25 17:44:14 +00:00
Piotr Skalski 09a47bec62 Merge pull request #1037 from xaristeidou/round-edge-label-annotator
Add `corner_radius` to `sv.LabelAnnotator` to handle roundness of label edges.
2024-03-25 17:59:28 +01:00
pre-commit-ci[bot] 90f6893d3d fix(pre_commit): 🎨 auto format pre-commit hooks 2024-03-25 16:29:16 +00:00
SkalskiP b585bb0724 test slightly simplified API 2024-03-25 17:28:59 +01:00
Piotr Skalski 495f9a9003 Merge pull request #1035 from rolson24/redesign-update_with_detections-to-match-Detections-with-tracker_id-v2
Fix issue #754
2024-03-25 16:15:37 +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
Piotr Skalski 4a6a6dbf6b Merge pull request #1041 from roboflow/docs/how_to_detect_and_annotate_improvements
How to Detect and Annotate Tutorial Improvements
2024-03-25 15:10:58 +01:00
Paweł Pęczek 4bb711dcea Add draft of changes to support adding titles 2024-03-25 15:09:21 +01:00
SkalskiP fec251d979 fix LabelAnnotator code snippets 2024-03-25 15:01:59 +01:00
SkalskiP 6d27b8067b mention that VideoSink and ImageSink accept images in BGR color format. 2024-03-25 14:54:34 +01:00
Onuralp SEZER 3da0ca4ffc Merge pull request #1039 from roboflow/dependabot/pip/mkdocs-material-9.5.15
⬆️ Bump mkdocs-material from 9.5.14 to 9.5.15
2024-03-25 16:48:30 +03:00
Onuralp SEZER fc03b0c386 Merge pull request #1040 from roboflow/dependabot/pip/tox-4.14.2
⬆️ Bump tox from 4.14.1 to 4.14.2
2024-03-25 16:48:12 +03:00
pre-commit-ci[bot] 4660dfd0d3 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-03-25 12:55:29 +00:00
SkalskiP e7b4d6ec41 more improvements 2024-03-25 13:55:13 +01:00
pre-commit-ci[bot] bc586562b5 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-03-25 12:14:44 +00:00
SkalskiP 57c6182325 initial changes 2024-03-25 13:11:47 +01:00
dependabot[bot] c3b617d47e ⬆️ Bump tox from 4.14.1 to 4.14.2
Bumps [tox](https://github.com/tox-dev/tox) from 4.14.1 to 4.14.2.
- [Release notes](https://github.com/tox-dev/tox/releases)
- [Changelog](https://github.com/tox-dev/tox/blob/main/docs/changelog.rst)
- [Commits](https://github.com/tox-dev/tox/compare/4.14.1...4.14.2)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-25 01:26:28 +00:00
dependabot[bot] 6458d4454d ⬆️ Bump mkdocs-material from 9.5.14 to 9.5.15
Bumps [mkdocs-material](https://github.com/squidfunk/mkdocs-material) from 9.5.14 to 9.5.15.
- [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.14...9.5.15)

---
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-03-25 01:07:38 +00:00
Christoforos Aristeidou 957ced0614 (pre-commit): align spacing 2024-03-24 11:42:19 +02:00
Christoforos Aristeidou ed3c73eb02 modified to use new custom method for rectangle drawing 2024-03-24 11:36:51 +02:00
Christoforos Aristeidou 3e4ddd5bd9 added new custom method that draws rounded rectangles 2024-03-24 11:36:10 +02:00
Christoforos Aristeidou 1fbdec6046 added corner_radius attribute to LabelAnnotator 2024-03-24 11:35:18 +02:00
Raif Olson 1eb877c4d9 Fix issue #754 2024-03-23 18:53:05 -05:00
Onuralp SEZER 781a064d8a Merge pull request #1030 from roboflow/dependabot/pip/ruff-0.3.4
⬆️ Bump ruff from 0.3.3 to 0.3.4
2024-03-22 04:40:54 +03:00
dependabot[bot] 70218b85e7 ⬆️ Bump ruff from 0.3.3 to 0.3.4
Bumps [ruff](https://github.com/astral-sh/ruff) from 0.3.3 to 0.3.4.
- [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.3...v0.3.4)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-22 01:05:54 +00:00
Onuralp SEZER 37318fafdf Merge pull request #1029 from roboflow/dependabot/pip/nbconvert-7.16.3
⬆️ Bump nbconvert from 7.16.2 to 7.16.3
2024-03-22 03:56:13 +03:00
dependabot[bot] f377a992e1 ⬆️ Bump nbconvert from 7.16.2 to 7.16.3
Bumps [nbconvert](https://github.com/jupyter/nbconvert) from 7.16.2 to 7.16.3.
- [Release notes](https://github.com/jupyter/nbconvert/releases)
- [Changelog](https://github.com/jupyter/nbconvert/blob/main/CHANGELOG.md)
- [Commits](https://github.com/jupyter/nbconvert/compare/v7.16.2...v7.16.3)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-22 00:52:54 +00:00
Paweł Pęczek 7eba338243 Add first draft of implementation for function creating image tiles 2024-03-20 23:08:39 +01:00
Piotr Skalski 6208013dcf Merge pull request #1003 from roboflow/adding-clor-border-to-crop-annotator
adding color border to crop annotator poc
2024-03-20 19:41:13 +01:00
SkalskiP 8a2abe72ae utils refactor 2024-03-20 19:37:03 +01:00
Piotr Skalski d01b636ebe Merge pull request #1024 from roboflow/security/ci/packaging
ci: 👷 publish pypi branch limitations added
2024-03-19 14:32:47 +01:00
Onuralp SEZER 0e3e41287a ci: 👷 publish pypi branch limitations added
Signed-off-by: Onuralp SEZER <thunderbirdtr@gmail.com>
2024-03-19 16:25:38 +03:00
Onuralp SEZER 5f9560afb8 Merge pull request #1020 from roboflow/pre-commit-ci-update-config
chore(pre_commit): ⬆ pre_commit autoupdate
2024-03-19 06:34:06 +03:00
pre-commit-ci[bot] 4abd128af5 chore(pre_commit): ⬆ pre_commit autoupdate
updates:
- [github.com/astral-sh/ruff-pre-commit: v0.3.2 → v0.3.3](https://github.com/astral-sh/ruff-pre-commit/compare/v0.3.2...v0.3.3)
2024-03-18 17:48:56 +00:00
Piotr Skalski 77908fe49b Merge pull request #1012 from roboflow/feat/type-check-improvement
feat: 📝 static type improvement color constants and PolygonZone
2024-03-18 10:56:10 +01:00
Onuralp SEZER fb3a78f762 Merge pull request #1014 from roboflow/dependabot/pip/mkdocs-material-9.5.14
⬆️ Bump mkdocs-material from 9.5.13 to 9.5.14
2024-03-18 12:00:01 +03:00
Onuralp SEZER f43b3536be Merge pull request #1013 from roboflow/dependabot/pip/ruff-0.3.3
⬆️ Bump ruff from 0.3.2 to 0.3.3
2024-03-18 11:59:44 +03:00
dependabot[bot] 345c086916 ⬆️ Bump mkdocs-material from 9.5.13 to 9.5.14
Bumps [mkdocs-material](https://github.com/squidfunk/mkdocs-material) from 9.5.13 to 9.5.14.
- [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.13...9.5.14)

---
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-03-18 01:30:06 +00:00
dependabot[bot] 123a61f2c6 ⬆️ Bump ruff from 0.3.2 to 0.3.3
Bumps [ruff](https://github.com/astral-sh/ruff) from 0.3.2 to 0.3.3.
- [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.2...v0.3.3)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-18 01:21:26 +00:00
Onuralp SEZER 63b338751f feat: 📝 typing improvement for polygone zone
Signed-off-by: Onuralp SEZER <thunderbirdtr@gmail.com>
2024-03-17 18:16:05 +03:00
Onuralp SEZER e8810fe8a2 fix: 🐞 static type fix for color constants to sv.Color
Signed-off-by: Onuralp SEZER <thunderbirdtr@gmail.com>
2024-03-17 14:42:58 +03:00
Piotr Skalski 3d9d45fc07 Merge pull request #1006 from roboflow/ci/doc/concurrency
ci: 👷 develop doc concurrency added for single run and cancel old ones
2024-03-17 12:26:48 +01:00
Onuralp SEZER 4f9e5a590f ci: 👷 develop doc concurrency added for single run and cancel old ones
Signed-off-by: Onuralp SEZER <thunderbirdtr@gmail.com>
2024-03-15 22:20:02 +03:00
pre-commit-ci[bot] 9f5c63b32d fix(pre_commit): 🎨 auto format pre-commit hooks 2024-03-15 11:02:26 +00:00
SkalskiP a5b1079e39 work in progress 2024-03-15 11:57:53 +01:00
Piotr Skalski 88d63473fe Merge pull request #1002 from roboflow/main
Merge pull request #991 from roboflow/develop
2024-03-15 11:18:53 +01:00
Onuralp SEZER d309d74f37 docs(notebooks): 📝 json and csv sink cookbooks are added
Signed-off-by: Onuralp SEZER <thunderbirdtr@gmail.com>
2024-03-05 05:27:58 +03:00
pre-commit-ci[bot] 27b61ab4a3 fix(pre_commit): 🎨 auto format pre-commit hooks 2024-01-22 23:31:31 +00:00
Seongjun Choi bddb72fb28 Modify: from_mmdetection add mask. See #703 2024-01-23 15:26:02 +09:00
Seongjun Choi 823dc56057 Modify: from_mmdetection add mask. See #703 2024-01-23 15:14:56 +09:00
mario-dg 6f4704625b Refactored merging of Detection attributes to better work with np.ndarrays 2023-10-19 00:05:42 +02:00
mario-dg 9f222736e1 Added standard full image inference after sliced inference to increase large object detection accuracy 2023-10-19 00:05:05 +02:00
mario-dg 57b12e6e00 Added __setitem__ to Detections and refactored the object prediction merging 2023-10-19 00:03:36 +02:00
mario-dg c78ae33e43 feat: 🚀 Added Non-Maximum Merging to Detections 2023-10-13 18:24:22 +02:00
140 changed files with 18895 additions and 4616 deletions
@@ -4,12 +4,18 @@ on:
push:
branches:
- develop
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:
deploy:
runs-on: ubuntu-latest
@@ -23,7 +29,7 @@ jobs:
with:
python-version: '3.10'
- name: 📦 Install mkdocs-material
run: pip install "mkdocs-material[all]"
run: pip install "mkdocs-material"
- name: 📦 Install mkdocstrings[python]
run: pip install "mkdocstrings[python]"
- name: 📦 Install mkdocs-material[imaging]
@@ -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
+8 -6
View File
@@ -6,22 +6,24 @@ on:
- '[0-9]+.[0-9]+[0-9]+.[0-9]+b[0-9]'
- '[0-9]+.[0-9]+[0-9]+.[0-9]+rc[0-9]'
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
jobs:
build-n-publish:
name: Build and publish to PyPI
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.10"]
steps:
- name: Checkout source
- name: 🛎️ Checkout
uses: actions/checkout@v4
- name: 🐍 Set up Python 3.8 environment for build
with:
ref: ${{ github.head_ref }}
- name: 🐍 Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: "3.8"
python-version: ${{ matrix.python-version }}
- name: 🏗️ Build source and wheel distributions
run: |
+1 -2
View File
@@ -4,7 +4,6 @@ on:
tags:
- '[0-9]+.[0-9]+[0-9]+.[0-9]'
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
jobs:
@@ -12,7 +11,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: [3.8]
python-version: ["3.10"]
steps:
- name: 🛎️ Checkout
uses: actions/checkout@v4
+3 -4
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,9 +27,8 @@ repos:
- id: mixed-line-ending
- repo: https://github.com/PyCQA/bandit
rev: '1.7.8'
rev: '1.7.9'
hooks:
- id: bandit
args: ["-c", "pyproject.toml"]
@@ -46,7 +45,7 @@ repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.3.2
rev: v0.5.1
hooks:
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
+122 -35
View File
@@ -4,6 +4,25 @@ Thank you for your interest in contributing to Supervision!
We are actively improving this library to reduce the amount of work you need to do to solve common computer vision problems.
## Code of Conduct
Please read and adhere to our [Code of Conduct](CODE_OF_CONDUCT.md). This document outlines the expected behavior for all participants in our project.
## Table of Contents
- [Contribution Guidelines](#contribution-guidelines)
- [Contributing Features](#contributing-features-)
- [How to Contribute Changes](#how-to-contribute-changes)
- [Installation for Contributors](#installation-for-contributors)
- [Code Style and Quality](#-code-style-and-quality)
- [Pre-commit tool](#pre-commit-tool)
- [Docstrings](#docstrings)
- [Type checking](#type-checking)
- [Documentation](#-documentation)
- [Cookbooks](#-cookbooks)
- [Tests](#-tests)
- [License](#-license)
## Contribution Guidelines
We welcome contributions to:
@@ -32,49 +51,49 @@ First, fork this repository to your own GitHub account. Click "fork" in the top
Then, run `git clone` to download the project code to your computer.
You should also set up `roboflow/supervision` as an "upstream" remote (that is, tell git that the reference Supervision repository was the source of your fork of it):
```bash
git remote add upstream https://github.com/roboflow/supervision.git
git fetch upstream
```
Move to a new branch using the `git checkout` command:
```bash
git checkout -b <your_branch_name>
git checkout -b <scope>/<your_branch_name> upstream/develop
```
The name you choose for your branch should describe the change you want to make (i.e. `line-counter-docs`).
The name you choose for your branch should describe the change you want to make and start with an appropriate prefix:
- `feat/`: for new features (e.g., `feat/line-counter`)
- `fix/`: for bug fixes (e.g., `fix/memory-leak`)
- `docs/`: for documentation changes (e.g., `docs/update-readme`)
- `chore/`: for routine tasks, maintenance, or tooling changes (e.g., `chore/update-dependencies`)
- `test/`: for adding or modifying tests (e.g., `test/add-unit-tests`)
- `refactor/`: for code refactoring (e.g., `refactor/simplify-algorithm`)
Make any changes you want to the project code, then run the following commands to commit your changes:
```bash
git add .
git commit -m "Your commit message"
git push -u origin main
git add -A
git commit -m "feat: add line counter functionality"
git push -u origin <your_branch_name>
```
## 🎨 Code quality
Use conventional commit messages to clearly describe your changes. The format is:
### Pre-commit tool
<type>[optional scope]: <description>
This project uses the [pre-commit](https://pre-commit.com/) tool to maintain code quality and consistency. Before submitting a pull request or making any commits, it is important to run the pre-commit tool to ensure that your changes meet the project's guidelines.
Furthermore, we have integrated a pre-commit GitHub Action into our workflow. This means that with every pull request opened, the pre-commit checks will be automatically enforced, streamlining the code review process and ensuring that all contributions adhere to our quality standards.
To run the pre-commit tool, follow these steps:
1. Install pre-commit by running the following command: `poetry install`. It will not only install pre-commit but also install all the deps and dev-deps of project
2. Once pre-commit is installed, navigate to the project's root directory.
3. Run the command `pre-commit run --all-files`. This will execute the pre-commit hooks configured for this project against the modified files. If any issues are found, the pre-commit tool will provide feedback on how to resolve them. Make the necessary changes and re-run the pre-commit command until all issues are resolved.
4. You can also install pre-commit as a git hook by execute `pre-commit install`. Every time you made `git commit` pre-commit run automatically for you.
### Docstrings
All new functions and classes in `supervision` should include docstrings. This is a prerequisite for any new functions and classes to be added to the library.
`supervision` adheres to the [Google Python docstring style](https://google.github.io/styleguide/pyguide.html#383-functions-and-methods). Please refer to the style guide while writing docstrings for your contribution.
### Type checking
So far, **there is no type checking with mypy**. See [issue](https://github.com/roboflow-ai/template-python/issues/4).
Common types include:
- feat: A new feature
- fix: A bug fix
- docs: Documentation only changes
- style: Changes that do not affect the meaning of the code (white-space, formatting, etc)
- refactor: A code change that neither fixes a bug nor adds a feature
- perf: A code change that improves performance
- test: Adding missing tests or correcting existing tests
- chore: Changes to the build process or auxiliary tools and libraries
Then, go back to your fork of the `supervision` repository, click "Pull Requests", and click "New Pull Request".
@@ -104,7 +123,75 @@ All pull requests will be reviewed by the maintainers of the project. We will pr
PRs must pass all tests and linting requirements before they can be merged.
## 📝 documentation
## Installation for Contributors
Before starting your work on the project, set up your development environment:
1. Clone your fork of the project:
```bash
git clone https://github.com/YOUR_USERNAME/supervision.git
cd supervision
```
Replace `YOUR_USERNAME` with your GitHub username.
2. Create and activate a virtual environment:
```bash
python3 -m venv .venv
source .venv/bin/activate
```
3. Install Poetry:
Using pip:
```bash
pip install -U pip setuptools
pip install poetry
```
Or using pipx (recommended for global installation):
```bash
pipx install poetry
```
4. Install project dependencies:
```bash
poetry install
```
5. Run pytest to verify the setup:
```bash
poetry run pytest
```
## 🎨 Code Style and Quality
### Pre-commit tool
This project uses the [pre-commit](https://pre-commit.com/) tool to maintain code quality and consistency. Before submitting a pull request or making any commits, it is important to run the pre-commit tool to ensure that your changes meet the project's guidelines.
Furthermore, we have integrated a pre-commit GitHub Action into our workflow. This means that with every pull request opened, the pre-commit checks will be automatically enforced, streamlining the code review process and ensuring that all contributions adhere to our quality standards.
To run the pre-commit tool, follow these steps:
1. Install pre-commit by running the following command: `poetry install`. It will not only install pre-commit but also install all the deps and dev-deps of project
2. Once pre-commit is installed, navigate to the project's root directory.
3. Run the command `pre-commit run --all-files`. This will execute the pre-commit hooks configured for this project against the modified files. If any issues are found, the pre-commit tool will provide feedback on how to resolve them. Make the necessary changes and re-run the pre-commit command until all issues are resolved.
4. You can also install pre-commit as a git hook by executing `pre-commit install`. Every time you do a `git commit` pre-commit run automatically for you.
### Docstrings
All new functions and classes in `supervision` should include docstrings. This is a prerequisite for any new functions and classes to be added to the library.
`supervision` adheres to the [Google Python docstring style](https://google.github.io/styleguide/pyguide.html#383-functions-and-methods). Please refer to the style guide while writing docstrings for your contribution.
### Type checking
So far, **there is no type checking with mypy**. See [issue](https://github.com/roboflow-ai/template-python/issues/4).
## 📝 Documentation
The `supervision` documentation is stored in a folder called `docs`. The project documentation is built using `mkdocs`.
@@ -112,13 +199,13 @@ To run the documentation, install the project requirements with `poetry install
You can learn more about mkdocs on the [mkdocs website](https://www.mkdocs.org/).
## 🧑‍🍳 cookbooks
## 🧑‍🍳 Cookbooks
We are always looking for new examples and cookbooks to add to the `supervision`
documentation. If you have a use case that you think would be helpful to others, please
submit a PR with your example. Here are some guidelines for submitting a new example:
- Create a new notebook in the [`docs/nodebooks`](https://github.com/roboflow/supervision/tree/develop/docs/notebooks) folder.
- Create a new notebook in the [`docs/notebooks`](https://github.com/roboflow/supervision/tree/develop/docs/notebooks) folder.
- Add a link to the new notebook in [`docs/theme/cookbooks.html`](https://github.com/roboflow/supervision/blob/develop/docs/theme/cookbooks.html). Make sure to add the path to the new notebook, as well as a title, labels, author and supervision version.
- Use the [Count Objects Crossing the Line](https://supervision.roboflow.com/develop/notebooks/count-objects-crossing-the-line/) example as a template for your new example.
- Freeze the version of `supervision` you are using.
@@ -126,10 +213,10 @@ submit a PR with your example. Here are some guidelines for submitting a new exa
- Notebook should be self-contained. If you rely on external data ( videos, images, etc.) or libraries, include download and installation commands in the notebook.
- Annotate the code with appropriate comments, including links to the documentation describing each of the tools you have used.
## 🧪 tests
## 🧪 Tests
[`pytests`](https://docs.pytest.org/en/7.1.x/) is used to run our tests.
## 📄 license
## 📄 License
By contributing, you agree that your contributions will be licensed under an [MIT license](https://github.com/roboflow/supervision/blob/develop/LICENSE.md).
+26 -23
View File
@@ -18,17 +18,17 @@
[![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
**We write your reusable computer vision tools.** Whether you need to load your dataset from your hard drive, draw detections on an image or video, or count how many detections are in a zone. You can count on us! 🤝
[![supervision-hackfest](https://github.com/roboflow/supervision/assets/26109316/c05cc954-b9a6-4ed5-9a52-d0b4b619ff65)](https://github.com/orgs/roboflow/projects/10)
[![supervision-hackfest](https://github.com/roboflow/supervision/assets/26109316/c05cc954-b9a6-4ed5-9a52-d0b4b619ff65)](https://github.com/orgs/roboflow/projects)
## 💻 install
@@ -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,23 +71,22 @@ 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>
### annotators
Supervision offers a wide range of highly customizable [annotators](https://supervision.roboflow.com/latest/annotators/), allowing you to compose the perfect visualization for your use case.
Supervision offers a wide range of highly customizable [annotators](https://supervision.roboflow.com/latest/detection/annotators/), allowing you to compose the perfect visualization for your use case.
```python
import cv2
@@ -96,8 +95,8 @@ import supervision as sv
image = cv2.imread(...)
detections = sv.Detections(...)
bounding_box_annotator = sv.BoundingBoxAnnotator()
annotated_frame = bounding_box_annotator.annotate(
box_annotator = sv.BoxAnnotator()
annotated_frame = box_annotator.annotate(
scene=image.copy(),
detections=detections
)
@@ -107,7 +106,7 @@ https://github.com/roboflow/supervision/assets/26109316/691e219c-0565-4403-9218-
### datasets
Supervision provides a set of [utils](https://supervision.roboflow.com/latest/datasets/) that allow you to load, split, merge, and save datasets in one of the supported formats.
Supervision provides a set of [utils](https://supervision.roboflow.com/latest/datasets/core/) that allow you to load, split, merge, and save datasets in one of the supported formats.
```python
import supervision as sv
@@ -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), [cheatsheet](https://roboflow.github.io/cheatsheet-supervision/), 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
Vendored
+1478 -1342
View File
File diff suppressed because one or more lines are too long
+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
+295 -6
View File
@@ -1,3 +1,297 @@
### 0.22.0 <small>Jul 12, 2024</small>
- Added [#1326](https://github.com/roboflow/supervision/pull/1326): [`sv.DetectionsDataset`](https://supervision.roboflow.com/latest/datasets/core/#supervision.dataset.core.DetectionDataset) and [`sv.ClassificationDataset`](https://supervision.roboflow.com/latest/datasets/core/#supervision.dataset.core.ClassificationDataset) allowing to load the images into memory only when necessary (lazy loading).
!!! failure "Deprecated"
Constructing `DetectionDataset` with parameter `images` as `Dict[str, np.ndarray]` is deprecated and will be removed in `supervision-0.26.0`. Please pass a list of paths `List[str]` instead.
!!! failure "Deprecated"
The `DetectionDataset.images` property is deprecated and will be removed in `supervision-0.26.0`. Please loop over images with `for path, image, annotation in dataset:`, as that does not require loading all images into memory.
```python
import roboflow
from roboflow import Roboflow
import supervision as sv
roboflow.login()
rf = Roboflow()
project = rf.workspace(<WORKSPACE_ID>).project(<PROJECT_ID>)
dataset = project.version(<PROJECT_VERSION>).download("coco")
ds_train = sv.DetectionDataset.from_coco(
images_directory_path=f"{dataset.location}/train",
annotations_path=f"{dataset.location}/train/_annotations.coco.json",
)
path, image, annotation = ds_train[0]
# loads image on demand
for path, image, annotation in ds_train:
# loads image on demand
```
- Added [#1296](https://github.com/roboflow/supervision/pull/1296): [`sv.Detections.from_lmm`](https://supervision.roboflow.com/latest/detection/core/#supervision.detection.core.Detections.from_lmm) now supports parsing results from the [Florence 2](https://huggingface.co/microsoft/Florence-2-large) model, extending the capability to handle outputs from this Large Multimodal Model (LMM). This includes detailed object detection, OCR with region proposals, segmentation, and more. Find out more in our [Colab notebook](https://colab.research.google.com/github/roboflow-ai/notebooks/blob/main/notebooks/how-to-finetune-florence-2-on-detection-dataset.ipynb).
- Added [#1232](https://github.com/roboflow/supervision/pull/1232) to support keypoint detection with Mediapipe. Both [legacy](https://colab.research.google.com/github/googlesamples/mediapipe/blob/main/examples/pose_landmarker/python/%5BMediaPipe_Python_Tasks%5D_Pose_Landmarker.ipynb) and [modern](https://ai.google.dev/edge/mediapipe/solutions/vision/pose_landmarker/python) pipelines are supported. See [`sv.KeyPoints.from_mediapipe`](https://supervision.roboflow.com/latest/keypoint/core/#supervision.keypoint.core.KeyPoints.from_mediapipe) for more.
- Added [#1316](https://github.com/roboflow/supervision/pull/1316): [`sv.KeyPoints.from_mediapipe`](https://supervision.roboflow.com/latest/keypoint/core/#supervision.keypoint.core.KeyPoints.from_mediapipe) extended to support FaceMesh from Mediapipe. This enhancement allows for processing both face landmarks from `FaceLandmarker`, and legacy results from `FaceMesh`.
- Added [#1310](https://github.com/roboflow/supervision/pull/1310): [`sv.KeyPoints.from_detectron2`](https://supervision.roboflow.com/latest/keypoint/core/#supervision.keypoint.core.KeyPoints.from_detectron2) is a new `KeyPoints` method, adding support for extracting keypoints from the popular [Detectron 2](https://github.com/facebookresearch/detectron2) platform.
- Added [#1300](https://github.com/roboflow/supervision/pull/1300): [`sv.Detections.from_detectron2`](https://supervision.roboflow.com/latest/detection/core/#supervision.detection.core.Detections.from_detectron2) now supports segmentation models detectron2. The resulting masks can be used with [`sv.MaskAnnotator`](https://supervision.roboflow.com/latest/annotators/#supervision.annotators.core.MaskAnnotator) for displaying annotations.
```python
import supervision as sv
from detectron2 import model_zoo
from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
import cv2
image = cv2.imread(<SOURCE_IMAGE_PATH>)
cfg = get_cfg()
cfg.merge_from_file(model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml"))
cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml")
predictor = DefaultPredictor(cfg)
result = predictor(image)
detections = sv.Detections.from_detectron2(result)
mask_annotator = sv.MaskAnnotator()
annotated_frame = mask_annotator.annotate(scene=image.copy(), detections=detections)
```
- Added [#1277](https://github.com/roboflow/supervision/pull/1277): if you provide a font that supports symbols of a language, [`sv.RichLabelAnnotator`](https://supervision.roboflow.com/latest/detection/annotators/#supervision.annotators.core.LabelAnnotator.annotate) will draw them on your images.
- Various other annotators have been revised to ensure proper in-place functionality when used with `numpy` arrays. Additionally, we fixed a bug where `sv.ColorAnnotator` was filling boxes with solid color when used in-place.
```python
import cv2
import supervision as sv
import
image = cv2.imread(<SOURCE_IMAGE_PATH>)
model = get_model(model_id="yolov8n-640")
results = model.infer(image)[0]
detections = sv.Detections.from_inference(results)
rich_label_annotator = sv.RichLabelAnnotator(font_path=<TTF_FONT_PATH>)
annotated_image = rich_label_annotator.annotate(scene=image.copy(), detections=detections)
```
- Added [#1227](https://github.com/roboflow/supervision/pull/1227): Added support for loading Oriented Bounding Boxes dataset in YOLO format.
```python
import supervision as sv
train_ds = sv.DetectionDataset.from_yolo(
images_directory_path="/content/dataset/train/images",
annotations_directory_path="/content/dataset/train/labels",
data_yaml_path="/content/dataset/data.yaml",
is_obb=True
)
_, image, detections in train_ds[0]
obb_annotator = OrientedBoxAnnotator()
annotated_image = obb_annotator.annotate(scene=image.copy(), detections=detections)
```
- Fixed [#1312](https://github.com/roboflow/supervision/pull/1312): Fixed [`CropAnnotator`](https://supervision.roboflow.com/latest/detection/annotators/#supervision.annotators.core.TraceAnnotator.annotate).
!!! failure "Removed"
`BoxAnnotator` was removed, however `BoundingBoxAnnotator` has been renamed to `BoxAnnotator`. Use a combination of [`BoxAnnotator`](https://supervision.roboflow.com/latest/detection/annotators/#supervision.annotators.core.BoxAnnotator) and [`LabelAnnotator`](https://supervision.roboflow.com/latest/detection/annotators/#supervision.annotators.core.LabelAnnotator) to simulate old `BoundingBox` behavior.
!!! failure "Deprecated"
The name `BoundingBoxAnnotator` has been deprecated and will be removed in `supervision-0.26.0`. It has been renamed to [`BoxAnnotator`](https://supervision.roboflow.com/latest/detection/annotators/#supervision.annotators.core.BoxAnnotator).
- Added [#975](https://github.com/roboflow/supervision/pull/975) 📝 New Cookbooks: serialize detections into [json](https://github.com/roboflow/supervision/blob/de896189b83a1f9434c0a37dd9192ee00d2a1283/docs/notebooks/serialise-detections-to-json.ipynb) and [csv](https://github.com/roboflow/supervision/blob/de896189b83a1f9434c0a37dd9192ee00d2a1283/docs/notebooks/serialise-detections-to-csv.ipynb).
- Added [#1290](https://github.com/roboflow/supervision/pull/1290): Mostly an internal change, our file utility function now support both `str` and `pathlib` paths.
- Added [#1340](https://github.com/roboflow/supervision/pull/1340): Two new methods for converting between bounding box formats - [`xywh_to_xyxy`](https://supervision.roboflow.com/latest/detection/utils/#supervision.detection.utils.xywh_to_xyxy) and [`xcycwh_to_xyxy`](https://supervision.roboflow.com/latest/detection/utils/#supervision.detection.utils.xcycwh_to_xyxy)
!!! failure "Removed"
`from_roboflow` method has been removed due to deprecation. Use [from_inference](https://supervision.roboflow.com/latest/detection/core/#supervision.detection.core.Detections.from_inference) instead.
!!! failure "Removed"
`Color.white()` has been removed due to deprecation. Use `color.WHITE` instead.
!!! failure "Removed"
`Color.black()` has been removed due to deprecation. Use `color.BLACK` instead.
!!! failure "Removed"
`Color.red()` has been removed due to deprecation. Use `color.RED` instead.
!!! failure "Removed"
`Color.green()` has been removed due to deprecation. Use `color.GREEN` instead.
!!! failure "Removed"
`Color.blue()` has been removed due to deprecation. Use `color.BLUE` instead.
!!! failure "Removed"
`ColorPalette.default()` has been removed due to deprecation. Use [ColorPalette.DEFAULT](https://supervision.roboflow.com/latest/utils/draw/#supervision.draw.color.ColorPalette.DEFAULT) instead.
!!! failure "Removed"
`FPSMonitor.__call__` has been removed due to deprecation. Use the attribute [FPSMonitor.fps](https://supervision.roboflow.com/latest/utils/video/#supervision.utils.video.FPSMonitor.fps) instead.
### 0.21.0 <small>Jun 5, 2024</small>
- Added [#500](https://github.com/roboflow/supervision/pull/500): [`sv.Detections.with_nmm`](https://supervision.roboflow.com/latest/detection/core/#supervision.detection.core.Detections.with_nmm) to perform non-maximum merging on the current set of object detections.
- Added [#1221](https://github.com/roboflow/supervision/pull/1221): [`sv.Detections.from_lmm`](https://supervision.roboflow.com/latest/detection/core/#supervision.detection.core.Detections.from_lmm) allowing to parse Large Multimodal Model (LMM) text result into [`sv.Detections`](https://supervision.roboflow.com/latest/detection/core/) object. For now `from_lmm` supports only [PaliGemma](https://colab.research.google.com/github/roboflow-ai/notebooks/blob/main/notebooks/how-to-finetune-paligemma-on-detection-dataset.ipynb) result parsing.
```python
import supervision as sv
paligemma_result = "<loc0256><loc0256><loc0768><loc0768> cat"
detections = sv.Detections.from_lmm(
sv.LMM.PALIGEMMA,
paligemma_result,
resolution_wh=(1000, 1000),
classes=['cat', 'dog']
)
detections.xyxy
# array([[250., 250., 750., 750.]])
detections.class_id
# array([0])
```
- Added [#1236](https://github.com/roboflow/supervision/pull/1236): [`sv.VertexLabelAnnotator`](https://supervision.roboflow.com/latest/keypoint/annotators/#supervision.keypoint.annotators.EdgeAnnotator.annotate) allowing to annotate every vertex of a keypoint skeleton with custom text and color.
```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
)
```
- Added [#1147](https://github.com/roboflow/supervision/pull/1147): [`sv.KeyPoints.from_inference`](https://supervision.roboflow.com/develop/keypoint/core/#supervision.keypoint.core.KeyPoints.from_inference) allowing to create [`sv.KeyPoints`](https://supervision.roboflow.com/develop/keypoint/core/#supervision.keypoint.core.KeyPoints) from [Inference](https://github.com/roboflow/inference) result.
- Added [#1138](https://github.com/roboflow/supervision/pull/1138): [`sv.KeyPoints.from_yolo_nas`](https://supervision.roboflow.com/develop/keypoint/core/#supervision.keypoint.core.KeyPoints.from_yolo_nas) allowing to create [`sv.KeyPoints`](https://supervision.roboflow.com/develop/keypoint/core/#supervision.keypoint.core.KeyPoints) from [YOLO-NAS](https://github.com/Deci-AI/super-gradients/blob/master/YOLONAS.md) result.
- Added [#1163](https://github.com/roboflow/supervision/pull/1163): [`sv.mask_to_rle`](https://supervision.roboflow.com/develop/datasets/utils/#supervision.dataset.utils.rle_to_mask) and [`sv.rle_to_mask`](https://supervision.roboflow.com/develop/datasets/utils/#supervision.dataset.utils.rle_to_mask) allowing for easy conversion between mask and rle formats.
- Changed [#1236](https://github.com/roboflow/supervision/pull/1236): [`sv.InferenceSlicer`](https://supervision.roboflow.com/develop/detection/tools/inference_slicer/) allowing to select overlap filtering strategy (`NONE`, `NON_MAX_SUPPRESSION` and `NON_MAX_MERGE`).
- Changed [#1178](https://github.com/roboflow/supervision/pull/1178): [`sv.InferenceSlicer`](https://supervision.roboflow.com/develop/detection/tools/inference_slicer/) adding instance segmentation model support.
```python
import cv2
import numpy as np
import supervision as sv
from inference import get_model
model = get_model(model_id="yolov8x-seg-640")
image = cv2.imread(<SOURCE_IMAGE_PATH>)
def callback(image_slice: np.ndarray) -> sv.Detections:
results = model.infer(image_slice)[0]
return sv.Detections.from_inference(results)
slicer = sv.InferenceSlicer(callback = callback)
detections = slicer(image)
mask_annotator = sv.MaskAnnotator()
label_annotator = sv.LabelAnnotator()
annotated_image = mask_annotator.annotate(
scene=image, detections=detections)
annotated_image = label_annotator.annotate(
scene=annotated_image, detections=detections)
```
- Changed [#1228](https://github.com/roboflow/supervision/pull/1228): [`sv.LineZone`](https://supervision.roboflow.com/develop/detection/tools/line_zone/) making it 10-20 times faster, depending on the use case.
- Changed [#1163](https://github.com/roboflow/supervision/pull/1163): [`sv.DetectionDataset.from_coco`](https://supervision.roboflow.com/develop/datasets/core/#supervision.dataset.core.DetectionDataset.from_coco) and [`sv.DetectionDataset.as_coco`](https://supervision.roboflow.com/develop/datasets/core/#supervision.dataset.core.DetectionDataset.as_coco) adding support for run-length encoding (RLE) mask format.
### 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.
@@ -19,8 +313,6 @@ with csv_sink:
- Added [#819](https://github.com/roboflow/supervision/pull/819): [`sv.JSONSink`](/0.19.0/detection/tools/save_detections/#supervision.detection.tools.csv_sink.JSONSink) allowing for the straightforward saving of image, video, or stream inference results in a `.json` file.
```python
```python
import supervision as sv
from ultralytics import YOLO
@@ -140,7 +432,6 @@ ColorPalette(colors=[Color(r=68, g=1, b=84), Color(r=59, g=82, b=139), ...])
`sv.ColorPalette.default()` is deprecated and will be removed in `supervision-0.22.0`. Use `sv.ColorPalette.DEFAULT` instead.
- Changed [#769](https://github.com/roboflow/supervision/pull/769): [`sv.ColorPalette.DEFAULT`](/0.18.0/draw/color/#colorpalette) value, giving users a more extensive set of annotation colors.
- Changed [#677](https://github.com/roboflow/supervision/pull/677): `sv.Detections.from_roboflow` to [`sv.Detections.from_inference`](/0.18.0/detection/core/#supervision.detection.core.Detections.from_inference) streamlining its functionality to be compatible with both the both [inference](https://github.com/roboflow/inference) pip package and the Robloflow [hosted API](https://docs.roboflow.com/deploy/hosted-api).
@@ -149,7 +440,6 @@ ColorPalette(colors=[Color(r=68, g=1, b=84), Color(r=59, g=82, b=139), ...])
`Detections.from_roboflow()` is deprecated and will be removed in `supervision-0.22.0`. Use `Detections.from_inference` instead.
- Fixed [#735](https://github.com/roboflow/supervision/pull/735): [`sv.LineZone`](/0.18.0/detection/tools/line_zone/#linezone) functionality to accurately update the counter when an object crosses a line from any direction, including from the side. This enhancement enables more precise tracking and analytics, such as calculating individual in/out counts for each lane on the road.
### 0.17.0 <small>December 06, 2023</small>
@@ -242,13 +532,12 @@ ColorPalette(colors=[Color(r=68, g=1, b=84), Color(r=59, g=82, b=139), ...])
- Fixed [#477](https://github.com/roboflow/supervision/pull/477): Poetry env definition allowing proper local installation.
- Fixed [#430](https://github.com/roboflow/supervision/pull/430): [`sv.ByteTrack`](/0.16.0/trackers/#supervision.tracker.byte_tracker.core.ByteTrack) to return `np.array([], dtype=int)` when `svDetections` is empty.
- Fixed [#430](https://github.com/roboflow/supervision/pull/430): [`sv.ByteTrack`](/0.16.0/trackers/#supervision.tracker.byte_tracker.core.ByteTrack) to return `np.array([], dtype=int)` when `svDetections` is empty.
!!! failure "Deprecated"
`sv.Detections.from_yolov8` and `sv.Classifications.from_yolov8` as those are now replaced by [`sv.Detections.from_ultralytics`](/0.16.0/detection/core/#supervision.detection.core.Detections.from_ultralytics) and [`sv.Classifications.from_ultralytics`](/0.16.0/classification/core/#supervision.classification.core.Classifications.from_ultralytics).
### 0.15.0 <small>October 5, 2023</small>
- Added [#170](https://github.com/roboflow/supervision/pull/170): [`sv.BoundingBoxAnnotator`](/0.15.0/annotators/#supervision.annotators.core.BoundingBoxAnnotator) allowing to annotate images and videos with bounding boxes.
-1
View File
@@ -1,7 +1,6 @@
---
template: cookbooks.html
comments: true
status: new
hide:
- navigation
- toc
@@ -1,5 +1,6 @@
---
comments: true
status: new
---
# Datasets
+17
View File
@@ -0,0 +1,17 @@
---
comments: true
---
# Datasets Utils
<div class="md-typeset">
<h2><a href="#supervision.dataset.utils.rle_to_mask">rle_to_mask</a></h2>
</div>
:::supervision.dataset.utils.rle_to_mask
<div class="md-typeset">
<h2><a href="#supervision.dataset.utils.mask_to_rle">mask_to_rle</a></h2>
</div>
:::supervision.dataset.utils.mask_to_rle
+20 -11
View File
@@ -3,16 +3,25 @@ comments: true
status: deprecated
---
These features are phased out due to better alternatives or potential issues in future versions. Deprecated functionalities are supported for **three subsequent releases**, providing time for users to transition to updated methods.
# Deprecated
These features are phased out due to better alternatives or potential issues in future versions. Deprecated functionalities are supported for **five subsequent releases**, providing time for users to transition to updated methods.
- [`Detections.from_froboflow`](detection/core.md/#supervision.detection.core.Detections.from_roboflow) is deprecated and will be removed in `supervision-0.22.0`. Use [`Detections.from_inference`](detection/core.md/#supervision.detection.core.Detections.from_inference) instead.
- The method `Color.white()` is deprecated and will be removed in `supervision-0.22.0`. Use the constant `Color.WHITE` instead.
- The method `Color.black()` is deprecated and will be removed in `supervision-0.22.0`. Use the constant `Color.BLACK` instead.
- The method `Color.red()` is deprecated and will be removed in `supervision-0.22.0`. Use the constant `Color.RED` instead.
- 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.
- 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 `triggering_position ` parameter in [`sv.PolygonZone`](detection/tools/polygon_zone.md/#supervision.detection.tools.polygon_zone.PolygonZone) 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) will be removed in `supervision-0.24.0`.
- Constructing `DetectionDataset` and `ClassificationDataset` with parameter `images` as `Dict[str, np.ndarray]` will be removed in `supervision-0.26.0`. Please pass a list of paths `List[str]` instead.
- The `DetectionDataset.images` property will be removed in `supervision-0.26.0`. Please loop over images with `for path, image, annotation in dataset:`, as that does not require loading all images into memory.
- `BoundingBoxAnnotator` has been renamed to `BoxAnnotator` after the old implementation of `BoxAnnotator` has been removed. `BoundingBoxAnnotator` will be removed in `supervision-0.26.0`.
# Removed
- [`Detections.from_froboflow`](detection/core.md/#supervision.detection.core.Detections.from_roboflow) is removed as of `supervision-0.22.0`. Use [`Detections.from_inference`](detection/core.md/#supervision.detection.core.Detections.from_inference) instead.
- The method `Color.white()` was removed as of `supervision-0.22.0`. Use the constant `Color.WHITE` instead.
- The method `Color.black()` was removed as of `supervision-0.22.0`. Use the constant `Color.BLACK` instead.
- The method `Color.red()` was removed as of `supervision-0.22.0`. Use the constant `Color.RED` instead.
- The method `Color.green()` was removed as of `supervision-0.22.0`. Use the constant `Color.GREEN` instead.
- The method `Color.blue()` was removed as of `supervision-0.22.0`. Use the constant `Color.BLUE` instead.
- The method [`ColorPalette.default()`](draw/color.md/#supervision.draw.color.ColorPalette.default) was removed as of `supervision-0.22.0`. Use the constant [`ColorPalette.DEFAULT`](draw/color.md/#supervision.draw.color.ColorPalette.DEFAULT) instead.
- `BoxAnnotator` was removed as of `supervision-0.22.0`, however `BoundingBoxAnnotator` was immediately renamed to `BoxAnnotator`. Use [`BoxAnnotator`](detection/annotators.md/#supervision.annotators.core.BoxAnnotator) and [`LabelAnnotator`](detection/annotators.md/#supervision.annotators.core.LabelAnnotator) instead of the old `BoxAnnotator`.
- The method [`FPSMonitor.__call__`](utils/video.md/#supervision.utils.video.FPSMonitor.__call__) was removed as of `supervision-0.22.0`. Use the attribute [`FPSMonitor.fps`](utils/video.md/#supervision.utils.video.FPSMonitor.fps) instead.
@@ -5,7 +5,7 @@ status: new
# Annotators
=== "BoundingBox"
=== "Box"
```python
import supervision as sv
@@ -13,8 +13,8 @@ status: new
image = ...
detections = sv.Detections(...)
bounding_box_annotator = sv.BoundingBoxAnnotator()
annotated_frame = bounding_box_annotator.annotate(
box_annotator = sv.BoxAnnotator()
annotated_frame = box_annotator.annotate(
scene=image.copy(),
detections=detections
)
@@ -260,15 +260,53 @@ status: new
=== "Label"
```python
import supervision as sv
import supervision as sv
image = ...
detections = sv.Detections(...)
labels = [
f"{class_name} {confidence:.2f}"
for class_name, confidence
in zip(detections['class_name'], detections.confidence)
]
label_annotator = sv.LabelAnnotator(text_position=sv.Position.CENTER)
annotated_frame = label_annotator.annotate(
scene=image.copy(),
detections=detections
detections=detections,
labels=labels
)
```
<div class="result" markdown>
![label-annotator-example](https://media.roboflow.com/supervision-annotator-examples/label-annotator-example-purple.png){ align=center width="800" }
</div>
=== "RichLabel"
```python
import supervision as sv
image = ...
detections = sv.Detections(...)
labels = [
f"{class_name} {confidence:.2f}"
for class_name, confidence
in zip(detections['class_name'], detections.confidence)
]
rich_label_annotator = sv.RichLabelAnnotator(
font_path="<TTF_FONT_PATH>",
text_position=sv.Position.CENTER
)
annotated_frame = label_annotator.annotate(
scene=image.copy(),
detections=detections,
labels=labels
)
```
@@ -281,7 +319,7 @@ status: new
=== "Crop"
```python
import supervision as sv
import supervision as sv
image = ...
detections = sv.Detections(...)
@@ -396,10 +434,10 @@ status: new
</div>
<div class="md-typeset">
<h2><a href="#supervision.annotators.core.BoundingBoxAnnotator">BoundingBoxAnnotator</a></h2>
<h2><a href="#supervision.annotators.core.BoxAnnotator">BoxAnnotator</a></h2>
</div>
:::supervision.annotators.core.BoundingBoxAnnotator
:::supervision.annotators.core.BoxAnnotator
<div class="md-typeset">
<h2><a href="#supervision.annotators.core.RoundBoxAnnotator">RoundBoxAnnotator</a></h2>
@@ -485,6 +523,12 @@ status: new
:::supervision.annotators.core.LabelAnnotator
<div class="md-typeset">
<h2><a href="#supervision.annotators.core.RichLabelAnnotator">RichLabelAnnotator</a></h2>
</div>
:::supervision.annotators.core.RichLabelAnnotator
<div class="md-typeset">
<h2><a href="#supervision.annotators.core.BlurAnnotator">BlurAnnotator</a></h2>
</div>
+29
View File
@@ -0,0 +1,29 @@
---
comments: true
---
# Double Detection Filter
<div class="md-typeset">
<h2><a href="#supervision.detection.overlap_filter.OverlapFilter">OverlapFilter</a></h2>
</div>
:::supervision.detection.overlap_filter.OverlapFilter
<div class="md-typeset">
<h2><a href="#supervision.detection.overlap_filter.box_non_max_suppression">box_non_max_suppression</a></h2>
</div>
:::supervision.detection.overlap_filter.box_non_max_suppression
<div class="md-typeset">
<h2><a href="#supervision.detection.overlap_filter.mask_non_max_suppression">mask_non_max_suppression</a></h2>
</div>
:::supervision.detection.overlap_filter.mask_non_max_suppression
<div class="md-typeset">
<h2><a href="#supervision.detection.overlap_filter.box_non_max_merge">box_non_max_merge</a></h2>
</div>
:::supervision.detection.overlap_filter.box_non_max_merge
+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
-1
View File
@@ -1,6 +1,5 @@
---
comments: true
status: new
---
# Save Detections
+51 -21
View File
@@ -6,67 +6,97 @@ 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>
</div>
:::supervision.detection.utils.box_non_max_suppression
<div class="md-typeset">
<h2>mask_non_max_suppression</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.move_masks">move_masks</a></h2>
</div>
:::supervision.detection.utils.move_masks
<div class="md-typeset">
<h2><a href="#supervision.detection.utils.scale_boxes">scale_boxes</a></h2>
</div>
:::supervision.detection.utils.scale_boxes
<div class="md-typeset">
<h2><a href="#supervision.detection.utils.clip_boxes">clip_boxes</a></h2>
</div>
:::supervision.detection.utils.clip_boxes
<div class="md-typeset">
<h2><a href="#supervision.detection.utils.pad_boxes">pad_boxes</a></h2>
</div>
:::supervision.detection.utils.pad_boxes
<div class="md-typeset">
<h2><a href="#supervision.detection.utils.contains_holes">contains_holes</a></h2>
</div>
:::supervision.detection.utils.xywh_to_xyxy
<div class="md-typeset">
<h2><a href="#supervision.detection.utils.xywh_to_xyxy">xywh_to_xyxy</a></h2>
</div>
:::supervision.detection.utils.xcycwh_to_xyxy
<div class="md-typeset">
<h2><a href="#supervision.detection.utils.xcycwh_to_xyxy">xcycwh_to_xyxy</a></h2>
</div>
:::supervision.detection.utils.contains_holes
<div class="md-typeset">
<h2><a href="#supervision.detection.utils.contains_multiple_segments">contains_multiple_segments</a></h2>
</div>
:::supervision.detection.utils.contains_multiple_segments
-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_dynamic_font_scale</h2>
</div>
:::supervision.draw.utils.calculate_dynamic_text_scale
<div class="md-typeset">
<h2>calculate_dynamic_line_thickness</h2>
</div>
:::supervision.draw.utils.calculate_dynamic_line_thickness
-7
View File
@@ -1,7 +0,0 @@
---
comments: true
---
# Position
:::supervision.geometry.core.Position
+342 -77
View File
@@ -4,17 +4,31 @@ comments: true
# Detect and Annotate
Supervision offers a streamlined solution to effortlessly annotate predictions from a
range of object detection and segmentation models. This guide demonstrates how to
execute inference using the YOLOv8 model with either the
[Inference](https://github.com/roboflow/inference) or
[Ultralytics](https://github.com/ultralytics/ultralytics) packages. Following this,
you'll learn how to import these predictions into Supervision for image annotation
purposes.
Supervision provides a seamless process for annotating predictions generated by various
object detection and segmentation models. This guide shows how to perform inference
with the [Inference](https://github.com/roboflow/inference),
[Ultralytics](https://github.com/ultralytics/ultralytics) or
[Transformers](https://github.com/huggingface/transformers) packages. Following this,
you'll learn how to import these predictions into Supervision and use them to annotate
source image.
## Run Inference
![basic-annotation](https://media.roboflow.com/supervision_detect_and_annotate_example_1.png)
First, you'll need to obtain predictions from your object detection or segmentation model.
## Run Detection
First, you'll need to obtain predictions from your object detection or segmentation
model.
=== "Inference"
```python
import cv2
from inference import get_model
model = get_model(model_id="yolov8n-640")
image = cv2.imread(<SOURCE_IMAGE_PATH>)
results = model.infer(image)[0]
```
=== "Ultralytics"
@@ -23,123 +37,374 @@ First, you'll need to obtain predictions from your object detection or segmentat
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
image = cv2.imread(<PATH TO IMAGE>)
image = cv2.imread(<SOURCE_IMAGE_PATH>)
results = model(image)[0]
```
=== "Inference"
=== "Transformers"
```python
import cv2
from inference.models.utils import get_roboflow_model
import torch
from PIL import Image
from transformers import DetrImageProcessor, DetrForObjectDetection
model = get_roboflow_model(model_id="yolov8n-640", api_key=<ROBOFLOW API KEY>)
image = cv2.imread(<PATH TO IMAGE>)
results = model.infer(image)[0]
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]
```
## Load Predictions into Supervision
Now that we have predictions from a model, we can load them into Supervision.
=== "Ultralytics"
We can do so using the [`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(<PATH TO IMAGE>)
results = model(image)[0]
detections = sv.Detections.from_ultralytics(results)
```
=== "Inference"
We can do so using the [`sv.Detections.from_inference`](detection/core/#supervision.detection.core.Detections.from_inference) method, which accepts model results from both detection and segmentation models.
```python
```{ .py hl_lines="2 8" }
import cv2
import supervision as sv
from inference.models.utils import get_roboflow_model
from inference import get_model
model = get_roboflow_model(model_id="yolov8n-640", api_key=<ROBOFLOW API KEY>
image = cv2.imread(<PATH TO IMAGE>)
model = get_model(model_id="yolov8n-640")
image = cv2.imread(<SOURCE_IMAGE_PATH>)
results = model.infer(image)[0]
detections = sv.Detections.from_inference(results)
```
You can conveniently load predictions from other computer vision frameworks and libraries using:
- [`from_deepsparse`](detection/core/#supervision.detection.core.Detections.from_deepsparse) ([Deepsparse](https://github.com/neuralmagic/deepsparse))
- [`from_detectron2`](detection/core/#supervision.detection.core.Detections.from_detectron2) ([Detectron2](https://github.com/facebookresearch/detectron2))
- [`from_mmdetection`](detection/core/#supervision.detection.core.Detections.from_mmdetection) ([MMDetection](https://github.com/open-mmlab/mmdetection))
- [`from_inference`](detection/core/#supervision.detection.core.Detections.from_inference) ([Roboflow Inference](https://github.com/roboflow/inference))
- [`from_sam`](detection/core/#supervision.detection.core.Detections.from_sam) ([Segment Anything Model](https://github.com/facebookresearch/segment-anything))
- [`from_transformers`](detection/core/#supervision.detection.core.Detections.from_transformers) ([HuggingFace Transformers](https://github.com/huggingface/transformers))
- [`from_yolo_nas`](detection/core/#supervision.detection.core.Detections.from_yolo_nas) ([YOLO-NAS](https://github.com/Deci-AI/super-gradients/blob/master/YOLONAS.md))
## Annotate Image
Finally, we can annotate the image with the predictions. Since we are working with an object detection model, we will use the [`sv.BoundingBoxAnnotator`](annotators/#supervision.annotators.core.BoundingBoxAnnotator) and [`sv.LabelAnnotator`](annotators/#supervision.annotators.core.LabelAnnotator) classes. If you are running the segmentation model [`sv.MaskAnnotator`](annotators/#supervision.annotators.core.MaskAnnotator) is a drop-in replacement for [`sv.BoundingBoxAnnotator`](annotators/#supervision.annotators.core.BoundingBoxAnnotator) that will allow you to draw masks instead of boxes.
=== "Ultralytics"
```python
We can do so using the [`sv.Detections.from_ultralytics`](detection/core/#supervision.detection.core.Detections.from_ultralytics) method, which accepts model results from both detection and segmentation models.
```{ .py hl_lines="2 8" }
import cv2
import supervision as sv
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)
bounding_box_annotator = sv.BoundingBoxAnnotator()
label_annotator = sv.LabelAnnotator()
labels = [
model.model.names[class_id]
for class_id
in detections.class_id
]
annotated_image = bounding_box_annotator.annotate(
scene=image, detections=detections)
annotated_image = label_annotator.annotate(
scene=annotated_image, detections=detections, labels=labels)
```
=== "Transformers"
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-21" }
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)
```
You can load predictions from other computer vision frameworks and libraries using:
- [`from_deepsparse`](/latest/detection/core/#supervision.detection.core.Detections.from_deepsparse) ([Deepsparse](https://github.com/neuralmagic/deepsparse))
- [`from_detectron2`](/latest/detection/core/#supervision.detection.core.Detections.from_detectron2) ([Detectron2](https://github.com/facebookresearch/detectron2))
- [`from_mmdetection`](/latest/detection/core/#supervision.detection.core.Detections.from_mmdetection) ([MMDetection](https://github.com/open-mmlab/mmdetection))
- [`from_sam`](/latest/detection/core/#supervision.detection.core.Detections.from_sam) ([Segment Anything Model](https://github.com/facebookresearch/segment-anything))
- [`from_yolo_nas`](/latest/detection/core/#supervision.detection.core.Detections.from_yolo_nas) ([YOLO-NAS](https://github.com/Deci-AI/super-gradients/blob/master/YOLONAS.md))
## Annotate Image with Detections
Finally, we can annotate the image with the predictions. Since we are working with an object detection model, we will use the [`sv.BoxAnnotator`](/latest/annotators/#supervision.annotators.core.BoxAnnotator) and [`sv.LabelAnnotator`](/latest/annotators/#supervision.annotators.core.LabelAnnotator) classes.
=== "Inference"
```python
```{ .py hl_lines="10-16" }
import cv2
import supervision as sv
from inference.models.utils import get_roboflow_model
from inference import get_model
model = get_roboflow_model(model_id="yolov8n-640", api_key=<ROBOFLOW API KEY>
image = cv2.imread(<PATH TO IMAGE>)
model = get_model(model_id="yolov8n-640")
image = cv2.imread(<SOURCE_IMAGE_PATH>)
results = model.infer(image)[0]
detections = sv.Detections.from_inference(results)
bounding_box_annotator = sv.BoundingBoxAnnotator()
box_annotator = sv.BoxAnnotator()
label_annotator = sv.LabelAnnotator()
annotated_image = bounding_box_annotator.annotate(
annotated_image = box_annotator.annotate(
scene=image, detections=detections)
annotated_image = label_annotator.annotate(
scene=annotated_image, detections=detections)
```
![Predictions plotted on an image](https://media.roboflow.com/supervision_annotate_example.png)
=== "Ultralytics"
## Display Annotated Image
```{ .py hl_lines="10-16" }
import cv2
import supervision as sv
from ultralytics import YOLO
To display the annotated image in Jupyter Notebook or Google Colab, use the [`sv.plot_image`](utils/notebook/#supervision.utils.notebook.plot_image) function.
model = YOLO("yolov8n.pt")
image = cv2.imread(<SOURCE_IMAGE_PATH>)
results = model(image)[0]
detections = sv.Detections.from_ultralytics(results)
```python
sv.plot_image(annotated_image)
```
box_annotator = sv.BoxAnnotator()
label_annotator = sv.LabelAnnotator()
annotated_image = box_annotator.annotate(
scene=image, detections=detections)
annotated_image = label_annotator.annotate(
scene=annotated_image, detections=detections)
```
=== "Transformers"
```{ .py hl_lines="23-30" }
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)
box_annotator = sv.BoxAnnotator()
label_annotator = sv.LabelAnnotator()
annotated_image = box_annotator.annotate(
scene=image, detections=detections)
annotated_image = label_annotator.annotate(
scene=annotated_image, detections=detections)
```
![basic-annotation](https://media.roboflow.com/supervision_detect_and_annotate_example_1.png)
## Display Custom Labels
By default, [`sv.LabelAnnotator`](/latest/annotators/#supervision.annotators.core.LabelAnnotator)
will label each detection with its `class_name` (if possible) or `class_id`. You can
override this behavior by passing a list of custom `labels` to the `annotate` method.
=== "Inference"
```{ .py hl_lines="13-17 22" }
import cv2
import supervision as sv
from inference import get_model
model = get_model(model_id="yolov8n-640")
image = cv2.imread(<SOURCE_IMAGE_PATH>)
results = model.infer(image)[0]
detections = sv.Detections.from_inference(results)
box_annotator = sv.BoxAnnotator()
label_annotator = sv.LabelAnnotator()
labels = [
f"{class_name} {confidence:.2f}"
for class_name, confidence
in zip(detections['class_name'], detections.confidence)
]
annotated_image = box_annotator.annotate(
scene=image, detections=detections)
annotated_image = label_annotator.annotate(
scene=annotated_image, detections=detections, labels=labels)
```
=== "Ultralytics"
```{ .py hl_lines="13-17 22" }
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)
box_annotator = sv.BoxAnnotator()
label_annotator = sv.LabelAnnotator()
labels = [
f"{class_name} {confidence:.2f}"
for class_name, confidence
in zip(detections['class_name'], detections.confidence)
]
annotated_image = box_annotator.annotate(
scene=image, detections=detections)
annotated_image = label_annotator.annotate(
scene=annotated_image, detections=detections, labels=labels)
```
=== "Transformers"
```{ .py hl_lines="26-30 35" }
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)
box_annotator = sv.BoxAnnotator()
label_annotator = sv.LabelAnnotator()
labels = [
f"{class_name} {confidence:.2f}"
for class_name, confidence
in zip(detections['class_name'], detections.confidence)
]
annotated_image = box_annotator.annotate(
scene=image, detections=detections)
annotated_image = label_annotator.annotate(
scene=annotated_image, detections=detections, labels=labels)
```
![custom-label-annotation](https://media.roboflow.com/supervision_detect_and_annotate_example_2.png)
## Annotate Image with Segmentations
If you are running the segmentation model
[`sv.MaskAnnotator`](/latest/annotators/#supervision.annotators.core.MaskAnnotator)
is a drop-in replacement for
[`sv.BoxAnnotator`](/latest/annotators/#supervision.annotators.core.BoxAnnotator)
that will allow you to draw masks instead of boxes.
=== "Inference"
```python
import cv2
import supervision as sv
from inference import get_model
model = get_model(model_id="yolov8n-seg-640")
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_OF_MASS)
annotated_image = mask_annotator.annotate(
scene=image, detections=detections)
annotated_image = label_annotator.annotate(
scene=annotated_image, detections=detections)
```
=== "Ultralytics"
```python
import cv2
import supervision as sv
from ultralytics import YOLO
model = YOLO("yolov8n-seg.pt")
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_OF_MASS)
annotated_image = mask_annotator.annotate(
scene=image, detections=detections)
annotated_image = label_annotator.annotate(
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)
+325
View File
@@ -0,0 +1,325 @@
---
comments: true
---
# Detect Small Objects
This guide shows how to detect small objects
with the [Inference](https://github.com/roboflow/inference),
[Ultralytics](https://github.com/ultralytics/ultralytics) or
[Transformers](https://github.com/huggingface/transformers) packages using
[`InferenceSlicer`](/latest/detection/tools/inference_slicer/#supervision.detection.tools.inference_slicer.InferenceSlicer).
<video controls>
<source src="https://media.roboflow.com/supervision_detect_small_objects_example.mp4" type="video/mp4">
</video>
## Baseline Detection
Small object detection in high-resolution images presents challenges due to the objects'
size relative to the image resolution.
=== "Inference"
```python
import cv2
import supervision as sv
from inference import get_model
model = get_model(model_id="yolov8x-640")
image = cv2.imread(<SOURCE_IMAGE_PATH>)
results = model.infer(image)[0]
detections = sv.Detections.from_inference(results)
box_annotator = sv.BoxAnnotator()
label_annotator = sv.LabelAnnotator()
annotated_image = box_annotator.annotate(
scene=image, detections=detections)
annotated_image = label_annotator.annotate(
scene=annotated_image, detections=detections)
```
=== "Ultralytics"
```python
import cv2
import supervision as sv
from ultralytics import YOLO
model = YOLO("yolov8x.pt")
image = cv2.imread(<SOURCE_IMAGE_PATH>)
results = model(image)[0]
detections = sv.Detections.from_ultralytics(results)
box_annotator = sv.BoxAnnotator()
label_annotator = sv.LabelAnnotator()
annotated_image = box_annotator.annotate(
scene=image, detections=detections)
annotated_image = label_annotator.annotate(
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")
model = DetrForSegmentation.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_slice.size
target_size = torch.tensor([[width, height]])
results = processor.post_process_object_detection(
outputs=outputs, target_sizes=target_size)[0]
detections = sv.Detections.from_transformers(results)
box_annotator = sv.BoxAnnotator()
label_annotator = sv.LabelAnnotator()
labels = [
model.config.id2label[class_id]
for class_id
in detections.class_id
]
annotated_image = box_annotator.annotate(
scene=image, detections=detections)
annotated_image = label_annotator.annotate(
scene=annotated_image, detections=detections, labels=labels)
```
![basic-detection](https://media.roboflow.com/supervision_detect_small_objects_example_1.png)
## Input Resolution
Modifying the input resolution of images before detection can enhance small object
identification at the cost of processing speed and increased memory usage. This method
is less effective for ultra-high-resolution images (4K and above).
=== "Inference"
```{ .py hl_lines="5" }
import cv2
import supervision as sv
from inference import get_model
model = get_model(model_id="yolov8x-1280")
image = cv2.imread(<SOURCE_IMAGE_PATH>)
results = model.infer(image)[0]
detections = sv.Detections.from_inference(results)
box_annotator = sv.BoxAnnotator()
label_annotator = sv.LabelAnnotator()
annotated_image = box_annotator.annotate(
scene=image, detections=detections)
annotated_image = label_annotator.annotate(
scene=annotated_image, detections=detections)
```
=== "Ultralytics"
```{ .py hl_lines="7" }
import cv2
import supervision as sv
from ultralytics import YOLO
model = YOLO("yolov8x.pt")
image = cv2.imread(<SOURCE_IMAGE_PATH>)
results = model(image, imgsz=1280)[0]
detections = sv.Detections.from_ultralytics(results)
box_annotator = sv.BoxAnnotator()
label_annotator = sv.LabelAnnotator()
annotated_image = box_annotator.annotate(
scene=image, detections=detections)
annotated_image = label_annotator.annotate(
scene=annotated_image, detections=detections)
```
![detection-with-high-input-resolution](https://media.roboflow.com/supervision_detect_small_objects_example_2.png)
## Inference Slicer
[`InferenceSlicer`](/latest/detection/tools/inference_slicer/#supervision.detection.tools.inference_slicer.InferenceSlicer)
processes high-resolution images by dividing them into smaller segments, detecting
objects within each, and aggregating the results.
<video controls>
<source src="https://media.roboflow.com/supervision_detect_small_objects_example_2.mp4" type="video/mp4">
</video>
=== "Inference"
```{ .py hl_lines="9-14" }
import cv2
import numpy as np
import supervision as sv
from inference import get_model
model = get_model(model_id="yolov8x-640")
image = cv2.imread(<SOURCE_IMAGE_PATH>)
def callback(image_slice: np.ndarray) -> sv.Detections:
results = model.infer(image_slice)[0]
return sv.Detections.from_inference(results)
slicer = sv.InferenceSlicer(callback = callback)
detections = slicer(image)
box_annotator = sv.BoxAnnotator()
label_annotator = sv.LabelAnnotator()
annotated_image = box_annotator.annotate(
scene=image, detections=detections)
annotated_image = label_annotator.annotate(
scene=annotated_image, detections=detections)
```
=== "Ultralytics"
```{ .py hl_lines="9-14" }
import cv2
import numpy as np
import supervision as sv
from ultralytics import YOLO
model = YOLO("yolov8x.pt")
image = cv2.imread(<SOURCE_IMAGE_PATH>)
def callback(image_slice: np.ndarray) -> sv.Detections:
result = model(image_slice)[0]
return sv.Detections.from_ultralytics(result)
slicer = sv.InferenceSlicer(callback = callback)
detections = slicer(image)
box_annotator = sv.BoxAnnotator()
label_annotator = sv.LabelAnnotator()
annotated_image = box_annotator.annotate(
scene=image, detections=detections)
annotated_image = label_annotator.annotate(
scene=annotated_image, detections=detections)
```
=== "Transformers"
```{ .py hl_lines="13-28" }
import cv2
import torch
import numpy as np
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 = cv2.imread(<SOURCE_IMAGE_PATH>)
def callback(image_slice: np.ndarray) -> sv.Detections:
image_slice = cv2.cvtColor(image_slice, cv2.COLOR_BGR2RGB)
image_slice = Image.fromarray(image_slice)
inputs = processor(images=image_slice, return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
width, height = image_slice.size
target_size = torch.tensor([[width, height]])
results = processor.post_process_object_detection(
outputs=outputs, target_sizes=target_size)[0]
return sv.Detections.from_transformers(results)
slicer = sv.InferenceSlicer(callback = callback)
detections = slicer(image)
box_annotator = sv.BoxAnnotator()
label_annotator = sv.LabelAnnotator()
labels = [
model.config.id2label[class_id]
for class_id
in detections.class_id
]
annotated_image = box_annotator.annotate(
scene=image, detections=detections)
annotated_image = label_annotator.annotate(
scene=annotated_image, detections=detections, labels=labels)
```
![detection-with-inference-slicer](https://media.roboflow.com/supervision_detect_small_objects_example_3.png)
## Small Object Segmentation
[`InferenceSlicer`](/latest/detection/tools/inference_slicer/#supervision.detection.tools.inference_slicer.InferenceSlicer) can perform segmentation tasks too.
=== "Inference"
```{ .py hl_lines="6 16 19-20" }
import cv2
import numpy as np
import supervision as sv
from inference import get_model
model = get_model(model_id="yolov8x-seg-640")
image = cv2.imread(<SOURCE_IMAGE_PATH>)
def callback(image_slice: np.ndarray) -> sv.Detections:
results = model.infer(image_slice)[0]
return sv.Detections.from_inference(results)
slicer = sv.InferenceSlicer(callback = callback)
detections = slicer(image)
mask_annotator = sv.MaskAnnotator()
label_annotator = sv.LabelAnnotator()
annotated_image = mask_annotator.annotate(
scene=image, detections=detections)
annotated_image = label_annotator.annotate(
scene=annotated_image, detections=detections)
```
=== "Ultralytics"
```{ .py hl_lines="6 16 19-20" }
import cv2
import numpy as np
import supervision as sv
from ultralytics import YOLO
model = YOLO("yolov8x-seg.pt")
image = cv2.imread(<SOURCE_IMAGE_PATH>)
def callback(image_slice: np.ndarray) -> sv.Detections:
result = model(image_slice)[0]
return sv.Detections.from_ultralytics(result)
slicer = sv.InferenceSlicer(callback = callback)
detections = slicer(image)
mask_annotator = sv.MaskAnnotator()
label_annotator = sv.LabelAnnotator()
annotated_image = mask_annotator.annotate(
scene=image, detections=detections)
annotated_image = label_annotator.annotate(
scene=annotated_image, detections=detections)
```
![detection-with-inference-slicer](https://media.roboflow.com/supervision-docs/inference-slicer-segmentation-example.png)
+298
View File
@@ -0,0 +1,298 @@
---
comments: true
---
# 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})
```
+36 -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>
@@ -109,6 +126,14 @@ You can install `supervision` with pip in a
[:octicons-arrow-right-24: Tutorial](how_to/track_objects.md)
- __Detect Small Objects__
---
Learn how to detect small objects in images
[:octicons-arrow-right-24: Tutorial](how_to/detect_small_objects.md)
- > __Count Objects Crossing Line__
---
@@ -121,4 +146,13 @@ You can install `supervision` with pip in a
Master the techniques to selectively filter and focus on objects within a specific zone
- **Cheatsheet**
***
Access a quick reference guide to the most common `supervision` functions
[:octicons-arrow-right-24: Cheatsheet](https://roboflow.github.io/cheatsheet-supervision/)
</div>
+96
View File
@@ -0,0 +1,96 @@
---
comments: true
---
# 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>
=== "VertexLabelAnnotator"
```python
import supervision as sv
image = ...
key_points = sv.KeyPoints(...)
vertex_label_annotator = sv.VertexLabelAnnotator(
color=sv.Color.GREEN,
text_color=sv.Color.BLACK,
border_radius=5
)
annotated_frame = vertex_label_annotator.annotate(
scene=image.copy(),
key_points=key_points
)
```
<div class="result" markdown>
![vertex-label-annotator-example](https://media.roboflow.com/supervision-annotator-examples/vertex-label-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
<div class="md-typeset">
<h2><a href="#supervision.keypoint.annotators.VertexLabelAnnotator">VertexLabelAnnotator</a></h2>
</div>
:::supervision.keypoint.annotators.VertexLabelAnnotator
+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
+333 -193
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+3
View File
@@ -19,6 +19,9 @@
<p class="card repo-card" data-url="/develop/notebooks/object-tracking" data-name="Object Tracking" data-labels="TRACKING, ANNOTATOR" data-version="v0.18.0" data-author="nickherrig"></p>
<p class="card repo-card" data-url="/develop/notebooks/occupancy_analytics" data-name="Analyzing Zone Occupancy" data-labels="ANNOTATOR,DETECTION,ZONES" data-version="v0.19.0" data-author="stellasphere"></p>
<p class="card repo-card" data-url="/develop/notebooks/evaluating-alignment-of-text-to-image-diffusion-models" data-name="Evaluating Alignment of Text-to-image Diffusion Models" data-labels="ANNOTATORS,YOLO WORLD" data-version="v0.19.0rc5" data-author="iamhatesz"></p>
<p class="card repo-card" data-url="/develop/notebooks/serialise-detections-to-csv" data-name="Serialise Detections to a CSV File" data-labels="DETECTIONS,CSV SINK,INFERENCE" data-version="v0.21.0" data-author="onuralpszr"></p>
<p class="card repo-card" data-url="/develop/notebooks/serialise-detections-to-json" data-name="Serialise Detections to a JSON File" data-labels="DETECTIONS,JSON SINK,INFERENCE" data-version="v0.21.0" data-author="onuralpszr"></p>
</div>
</div>
</section>
-1
View File
@@ -1,6 +1,5 @@
---
comments: true
status: new
---
# ByteTrack
+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_text_scale">calculate_optimal_text_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
+2 -1
View File
@@ -1,11 +1,12 @@
---
comments: true
status: new
---
# 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 -11
View File
@@ -1,30 +1,41 @@
---
comments: true
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">scale_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
+17
View File
@@ -0,0 +1,17 @@
---
comments: true
---
# 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
+4 -23
View File
@@ -1,31 +1,12 @@
# 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)
- [traffic analysis](./traffic_analysis) by [@SkalskiP](https://github.com/SkalskiP)
- [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
@@ -11,7 +11,7 @@ from tqdm import tqdm
import supervision as sv
COLORS = sv.ColorPalette.default()
COLORS = sv.ColorPalette.DEFAULT
def load_zones_config(file_path: str) -> List[np.ndarray]:
@@ -38,15 +38,15 @@ def initiate_annotators(
) -> Tuple[
List[sv.PolygonZone], List[sv.PolygonZoneAnnotator], List[sv.BoundingBoxAnnotator]
]:
line_thickness = sv.calculate_dynamic_line_thickness(resolution_wh=resolution_wh)
text_scale = sv.calculate_dynamic_text_scale(resolution_wh=resolution_wh)
line_thickness = sv.calculate_optimal_line_thickness(resolution_wh=resolution_wh)
text_scale = sv.calculate_optimal_text_scale(resolution_wh=resolution_wh)
zones = []
zone_annotators = []
box_annotators = []
for index, polygon in enumerate(polygons):
zone = sv.PolygonZone(polygon=polygon, frame_resolution_wh=resolution_wh)
zone = sv.PolygonZone(polygon=polygon)
zone_annotator = sv.PolygonZoneAnnotator(
zone=zone,
color=COLORS.by_idx(index),
@@ -1,5 +1,5 @@
gdown
inference
supervision
inference==0.9.17
supervision>=0.20.0
tqdm
ultralytics
@@ -9,7 +9,7 @@ from ultralytics import YOLO
import supervision as sv
COLORS = sv.ColorPalette.default()
COLORS = sv.ColorPalette.DEFAULT
def load_zones_config(file_path: str) -> List[np.ndarray]:
@@ -36,15 +36,15 @@ def initiate_annotators(
) -> Tuple[
List[sv.PolygonZone], List[sv.PolygonZoneAnnotator], List[sv.BoundingBoxAnnotator]
]:
line_thickness = sv.calculate_dynamic_line_thickness(resolution_wh=resolution_wh)
text_scale = sv.calculate_dynamic_text_scale(resolution_wh=resolution_wh)
line_thickness = sv.calculate_optimal_line_thickness(resolution_wh=resolution_wh)
text_scale = sv.calculate_optimal_text_scale(resolution_wh=resolution_wh)
zones = []
zone_annotators = []
box_annotators = []
for index, polygon in enumerate(polygons):
zone = sv.PolygonZone(polygon=polygon, frame_resolution_wh=resolution_wh)
zone = sv.PolygonZone(polygon=polygon)
zone_annotator = sv.PolygonZoneAnnotator(
zone=zone,
color=COLORS.by_idx(index),
+1 -1
View File
@@ -1,2 +1,2 @@
supervision[assets]
supervision[assets]==0.19.0
ultralytics
@@ -98,11 +98,11 @@ if __name__ == "__main__":
frame_rate=video_info.fps, track_thresh=args.confidence_threshold
)
thickness = sv.calculate_dynamic_line_thickness(
thickness = sv.calculate_optimal_line_thickness(
resolution_wh=video_info.resolution_wh
)
text_scale = sv.calculate_dynamic_text_scale(resolution_wh=video_info.resolution_wh)
bounding_box_annotator = sv.BoundingBoxAnnotator(thickness=thickness)
text_scale = sv.calculate_optimal_text_scale(resolution_wh=video_info.resolution_wh)
box_annotator = sv.BoxAnnotator(thickness=thickness)
label_annotator = sv.LabelAnnotator(
text_scale=text_scale,
text_thickness=thickness,
@@ -116,9 +116,7 @@ if __name__ == "__main__":
frame_generator = sv.get_video_frames_generator(source_path=args.source_video_path)
polygon_zone = sv.PolygonZone(
polygon=SOURCE, frame_resolution_wh=video_info.resolution_wh
)
polygon_zone = sv.PolygonZone(polygon=SOURCE)
view_transformer = ViewTransformer(source=SOURCE, target=TARGET)
coordinates = defaultdict(lambda: deque(maxlen=video_info.fps))
@@ -156,7 +154,7 @@ if __name__ == "__main__":
annotated_frame = trace_annotator.annotate(
scene=annotated_frame, detections=detections
)
annotated_frame = bounding_box_annotator.annotate(
annotated_frame = box_annotator.annotate(
scene=annotated_frame, detections=detections
)
annotated_frame = label_annotator.annotate(
+3 -3
View File
@@ -1,6 +1,6 @@
supervision==0.18.0rc1
tqdm==4.66.1
supervision>=0.20.0
tqdm==4.66.3
requests
ultralytics==8.0.237
super-gradients==3.5.0
inference==0.9.8
inference==0.9.17
@@ -76,11 +76,11 @@ if __name__ == "__main__":
frame_rate=video_info.fps, track_thresh=args.confidence_threshold
)
thickness = sv.calculate_dynamic_line_thickness(
thickness = sv.calculate_optimal_line_thickness(
resolution_wh=video_info.resolution_wh
)
text_scale = sv.calculate_dynamic_text_scale(resolution_wh=video_info.resolution_wh)
bounding_box_annotator = sv.BoundingBoxAnnotator(thickness=thickness)
text_scale = sv.calculate_optimal_text_scale(resolution_wh=video_info.resolution_wh)
box_annotator = sv.BoxAnnotator(thickness=thickness)
label_annotator = sv.LabelAnnotator(
text_scale=text_scale,
text_thickness=thickness,
@@ -94,9 +94,7 @@ if __name__ == "__main__":
frame_generator = sv.get_video_frames_generator(source_path=args.source_video_path)
polygon_zone = sv.PolygonZone(
polygon=SOURCE, frame_resolution_wh=video_info.resolution_wh
)
polygon_zone = sv.PolygonZone(polygon=SOURCE)
view_transformer = ViewTransformer(source=SOURCE, target=TARGET)
coordinates = defaultdict(lambda: deque(maxlen=video_info.fps))
@@ -134,7 +132,7 @@ if __name__ == "__main__":
annotated_frame = trace_annotator.annotate(
scene=annotated_frame, detections=detections
)
annotated_frame = bounding_box_annotator.annotate(
annotated_frame = box_annotator.annotate(
scene=annotated_frame, detections=detections
)
annotated_frame = label_annotator.annotate(
@@ -77,11 +77,11 @@ if __name__ == "__main__":
frame_rate=video_info.fps, track_thresh=args.confidence_threshold
)
thickness = sv.calculate_dynamic_line_thickness(
thickness = sv.calculate_optimal_line_thickness(
resolution_wh=video_info.resolution_wh
)
text_scale = sv.calculate_dynamic_text_scale(resolution_wh=video_info.resolution_wh)
bounding_box_annotator = sv.BoundingBoxAnnotator(thickness=thickness)
text_scale = sv.calculate_optimal_text_scale(resolution_wh=video_info.resolution_wh)
box_annotator = sv.BoxAnnotator(thickness=thickness)
label_annotator = sv.LabelAnnotator(
text_scale=text_scale,
text_thickness=thickness,
@@ -95,9 +95,7 @@ if __name__ == "__main__":
frame_generator = sv.get_video_frames_generator(source_path=args.source_video_path)
polygon_zone = sv.PolygonZone(
polygon=SOURCE, frame_resolution_wh=video_info.resolution_wh
)
polygon_zone = sv.PolygonZone(polygon=SOURCE)
view_transformer = ViewTransformer(source=SOURCE, target=TARGET)
coordinates = defaultdict(lambda: deque(maxlen=video_info.fps))
@@ -134,7 +132,7 @@ if __name__ == "__main__":
annotated_frame = trace_annotator.annotate(
scene=annotated_frame, detections=detections
)
annotated_frame = bounding_box_annotator.annotate(
annotated_frame = box_annotator.annotate(
scene=annotated_frame, detections=detections
)
annotated_frame = label_annotator.annotate(
+9
View File
@@ -0,0 +1,9 @@
data/
venv*/
*.pt
*.pth
*.mp4
*.mov
*.png
*.jpg
*.jpeg
+264
View File
@@ -0,0 +1,264 @@
# 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
monitoring the duration that objects or individuals spend in predefined areas of video
frames. This example project, perfect for retail analytics or traffic management
applications.
https://github.com/roboflow/supervision/assets/26109316/d051cc8a-dd15-41d4-aa36-d38b86334c39
## 💻 install
- clone repository and navigate to example directory
```bash
git clone https://github.com/roboflow/supervision.git
cd supervision/examples/time_in_zone
```
- setup python environment and activate it [optional]
```bash
python3 -m venv venv
source venv/bin/activate
```
- install required dependencies
```bash
pip install -r requirements.txt
```
## 🛠 scripts
### `download_from_youtube`
This script allows you to download a video from YouTube.
- `--url`: The full URL of the YouTube video you wish to download.
- `--output_path` (optional): Specifies the directory where the video will be saved.
- `--file_name` (optional): Sets the name of the saved video file.
```bash
python scripts/download_from_youtube.py \
--url "https://www.youtube.com/watch?v=-8zyEwAa50Q" \
--output_path "data/checkout" \
--file_name "video.mp4"
```
```bash
python scripts/download_from_youtube.py \
--url "https://www.youtube.com/watch?v=MNn9qKG2UFI" \
--output_path "data/traffic" \
--file_name "video.mp4"
```
### `stream_from_file`
This script allows you to stream video files from a directory. It's an awesome way to
mock a live video stream for local testing. Video will be streamed in a loop under
`rtsp://localhost:8554/live0.stream` URL. This script requires docker to be installed.
- `--video_directory`: Directory containing video files to stream.
- `--number_of_streams`: Number of video files to stream.
```bash
python scripts/stream_from_file.py \
--video_directory "data/checkout" \
--number_of_streams 1
```
```bash
python scripts/stream_from_file.py \
--video_directory "data/traffic" \
--number_of_streams 1
```
### `draw_zones`
If you want to test zone time in zone analysis on your own video, you can use this
script to design custom zones and save results as a JSON file. The script will open a
window where you can draw polygons on the source image or video file. The polygons will
be saved as a JSON file.
- `--source_path`: Path to the source image or video file for drawing polygons.
- `--zone_configuration_path`: Path where the polygon annotations will be saved as a JSON file.
- `enter` - finish drawing the current polygon.
- `escape` - cancel drawing the current polygon.
- `q` - quit the drawing window.
- `s` - save zone configuration to a JSON file.
```bash
python scripts/draw_zones.py \
--source_path "data/checkout/video.mp4" \
--zone_configuration_path "data/checkout/config.json"
```
```bash
python scripts/draw_zones.py \
--source_path "data/traffic/video.mp4" \
--zone_configuration_path "data/traffic/config.json"
```
https://github.com/roboflow/supervision/assets/26109316/9d514c9e-2a61-418b-ae49-6ac1ad6ae5ac
## 🎬 video & stream processing
### `inference_file_example`
Script to run object detection on a video file using the Roboflow Inference model.
- `--zone_configuration_path`: Path to the zone configuration JSON file.
- `--source_video_path`: Path to the source video file.
- `--model_id`: Roboflow model ID.
- `--classes`: List of class IDs to track. If empty, all classes are tracked.
- `--confidence_threshold`: Confidence level for detections (`0` to `1`). Default is `0.3`.
- `--iou_threshold`: IOU threshold for non-max suppression. Default is `0.7`.
```bash
python inference_file_example.py \
--zone_configuration_path "data/checkout/config.json" \
--source_video_path "data/checkout/video.mp4" \
--model_id "yolov8x-640" \
--classes 0 \
--confidence_threshold 0.3 \
--iou_threshold 0.7
```
https://github.com/roboflow/supervision/assets/26109316/d051cc8a-dd15-41d4-aa36-d38b86334c39
```bash
python inference_file_example.py \
--zone_configuration_path "data/traffic/config.json" \
--source_video_path "data/traffic/video.mp4" \
--model_id "yolov8x-640" \
--classes 2 5 6 7 \
--confidence_threshold 0.3 \
--iou_threshold 0.7
```
https://github.com/roboflow/supervision/assets/26109316/5ec896d7-4b39-4426-8979-11e71666878b
### `inference_stream_example`
Script to run object detection on a video stream using the Roboflow Inference model.
- `--zone_configuration_path`: Path to the zone configuration JSON file.
- `--rtsp_url`: Complete RTSP URL for the video stream.
- `--model_id`: Roboflow model ID.
- `--classes`: List of class IDs to track. If empty, all classes are tracked.
- `--confidence_threshold`: Confidence level for detections (`0` to `1`). Default is `0.3`.
- `--iou_threshold`: IOU threshold for non-max suppression. Default is `0.7`.
```bash
python inference_stream_example.py \
--zone_configuration_path "data/checkout/config.json" \
--rtsp_url "rtsp://localhost:8554/live0.stream" \
--model_id "yolov8x-640" \
--classes 0 \
--confidence_threshold 0.3 \
--iou_threshold 0.7
```
```bash
python inference_stream_example.py \
--zone_configuration_path "data/traffic/config.json" \
--rtsp_url "rtsp://localhost:8554/live0.stream" \
--model_id "yolov8x-640" \
--classes 2 5 6 7 \
--confidence_threshold 0.3 \
--iou_threshold 0.7
```
<details>
<summary>👉 show ultralytics examples</summary>
### `ultralytics_file_example`
Script to run object detection on a video file using the Ultralytics YOLOv8 model.
- `--zone_configuration_path`: Path to the zone configuration JSON file.
- `--source_video_path`: Path to the source video file.
- `--weights`: Path to the model weights file. Default is `'yolov8s.pt'`.
- `--device`: Computation device (`'cpu'`, `'mps'` or `'cuda'`). Default is `'cpu'`.
- `--classes`: List of class IDs to track. If empty, all classes are tracked.
- `--confidence_threshold`: Confidence level for detections (`0` to `1`). Default is `0.3`.
- `--iou_threshold`: IOU threshold for non-max suppression. Default is `0.7`.
```bash
python ultralytics_file_example.py \
--zone_configuration_path "data/checkout/config.json" \
--source_video_path "data/checkout/video.mp4" \
--weights "yolov8x.pt" \
--device "cpu" \
--classes 0 \
--confidence_threshold 0.3 \
--iou_threshold 0.7
```
```bash
python ultralytics_file_example.py \
--zone_configuration_path "data/traffic/config.json" \
--source_video_path "data/traffic/video.mp4" \
--weights "yolov8x.pt" \
--device "cpu" \
--classes 2 5 6 7 \
--confidence_threshold 0.3 \
--iou_threshold 0.7
```
### `ultralytics_stream_example`
Script to run object detection on a video stream using the Ultralytics YOLOv8 model.
- `--zone_configuration_path`: Path to the zone configuration JSON file.
- `--rtsp_url`: Complete RTSP URL for the video stream.
- `--weights`: Path to the model weights file. Default is `'yolov8s.pt'`.
- `--device`: Computation device (`'cpu'`, `'mps'` or `'cuda'`). Default is `'cpu'`.
- `--classes`: List of class IDs to track. If empty, all classes are tracked.
- `--confidence_threshold`: Confidence level for detections (`0` to `1`). Default is `0.3`.
- `--iou_threshold`: IOU threshold for non-max suppression. Default is `0.7`.
```bash
python ultralytics_stream_example.py \
--zone_configuration_path "data/checkout/config.json" \
--rtsp_url "rtsp://localhost:8554/live0.stream" \
--weights "yolov8x.pt" \
--device "cpu" \
--classes 0 \
--confidence_threshold 0.3 \
--iou_threshold 0.7
```
```bash
python ultralytics_stream_example.py \
--zone_configuration_path "data/traffic/config.json" \
--rtsp_url "rtsp://localhost:8554/live0.stream" \
--weights "yolov8x.pt" \
--device "cpu" \
--classes 2 5 6 7 \
--confidence_threshold 0.3 \
--iou_threshold 0.7
```
</details>
## © license
This demo integrates two main components, each with its own licensing:
- ultralytics: The object detection model used in this demo, YOLOv8, is distributed
under the [AGPL-3.0 license](https://github.com/ultralytics/ultralytics/blob/main/LICENSE).
You can find more details about this license here.
- supervision: The analytics code that powers the zone-based analysis in this demo is
based on the Supervision library, which is licensed under the
[MIT license](https://github.com/roboflow/supervision/blob/develop/LICENSE.md). This
makes the Supervision part of the code fully open source and freely usable in your
projects.
@@ -0,0 +1,128 @@
import argparse
from typing import List
import cv2
import numpy as np
from inference import get_model
from utils.general import find_in_list, load_zones_config
from utils.timers import FPSBasedTimer
import supervision as sv
COLORS = sv.ColorPalette.from_hex(["#E6194B", "#3CB44B", "#FFE119", "#3C76D1"])
COLOR_ANNOTATOR = sv.ColorAnnotator(color=COLORS)
LABEL_ANNOTATOR = sv.LabelAnnotator(
color=COLORS, text_color=sv.Color.from_hex("#000000")
)
def main(
source_video_path: str,
zone_configuration_path: str,
model_id: str,
confidence: float,
iou: float,
classes: List[int],
) -> None:
model = get_model(model_id=model_id)
tracker = sv.ByteTrack(minimum_matching_threshold=0.5)
video_info = sv.VideoInfo.from_video_path(video_path=source_video_path)
frames_generator = sv.get_video_frames_generator(source_video_path)
polygons = load_zones_config(file_path=zone_configuration_path)
zones = [
sv.PolygonZone(
polygon=polygon,
triggering_anchors=(sv.Position.CENTER,),
)
for polygon in polygons
]
timers = [FPSBasedTimer(video_info.fps) for _ in zones]
for frame in frames_generator:
results = model.infer(frame, confidence=confidence, iou_threshold=iou)[0]
detections = sv.Detections.from_inference(results)
detections = detections[find_in_list(detections.class_id, classes)]
detections = tracker.update_with_detections(detections)
annotated_frame = frame.copy()
for idx, zone in enumerate(zones):
annotated_frame = sv.draw_polygon(
scene=annotated_frame, polygon=zone.polygon, color=COLORS.by_idx(idx)
)
detections_in_zone = detections[zone.trigger(detections)]
time_in_zone = timers[idx].tick(detections_in_zone)
custom_color_lookup = np.full(detections_in_zone.class_id.shape, idx)
annotated_frame = COLOR_ANNOTATOR.annotate(
scene=annotated_frame,
detections=detections_in_zone,
custom_color_lookup=custom_color_lookup,
)
labels = [
f"#{tracker_id} {int(time // 60):02d}:{int(time % 60):02d}"
for tracker_id, time in zip(detections_in_zone.tracker_id, time_in_zone)
]
annotated_frame = LABEL_ANNOTATOR.annotate(
scene=annotated_frame,
detections=detections_in_zone,
labels=labels,
custom_color_lookup=custom_color_lookup,
)
cv2.imshow("Processed Video", annotated_frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
cv2.destroyAllWindows()
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Calculating detections dwell time in zones, using video file."
)
parser.add_argument(
"--zone_configuration_path",
type=str,
required=True,
help="Path to the zone configuration JSON file.",
)
parser.add_argument(
"--source_video_path",
type=str,
required=True,
help="Path to the source video file.",
)
parser.add_argument(
"--model_id", type=str, default="yolov8s-640", help="Roboflow model ID."
)
parser.add_argument(
"--confidence_threshold",
type=float,
default=0.3,
help="Confidence level for detections (0 to 1). Default is 0.3.",
)
parser.add_argument(
"--iou_threshold",
default=0.7,
type=float,
help="IOU threshold for non-max suppression. Default is 0.7.",
)
parser.add_argument(
"--classes",
nargs="*",
type=int,
default=[],
help="List of class IDs to track. If empty, all classes are tracked.",
)
args = parser.parse_args()
main(
source_video_path=args.source_video_path,
zone_configuration_path=args.zone_configuration_path,
model_id=args.model_id,
confidence=args.confidence_threshold,
iou=args.iou_threshold,
classes=args.classes,
)
@@ -0,0 +1,138 @@
import argparse
from typing import List
import cv2
import numpy as np
from inference import get_model
from utils.general import find_in_list, get_stream_frames_generator, load_zones_config
from utils.timers import ClockBasedTimer
import supervision as sv
COLORS = sv.ColorPalette.from_hex(["#E6194B", "#3CB44B", "#FFE119", "#3C76D1"])
COLOR_ANNOTATOR = sv.ColorAnnotator(color=COLORS)
LABEL_ANNOTATOR = sv.LabelAnnotator(
color=COLORS, text_color=sv.Color.from_hex("#000000")
)
def main(
rtsp_url: str,
zone_configuration_path: str,
model_id: str,
confidence: float,
iou: float,
classes: List[int],
) -> None:
model = get_model(model_id=model_id)
tracker = sv.ByteTrack(minimum_matching_threshold=0.5)
frames_generator = get_stream_frames_generator(rtsp_url=rtsp_url)
fps_monitor = sv.FPSMonitor()
polygons = load_zones_config(file_path=zone_configuration_path)
zones = [
sv.PolygonZone(
polygon=polygon,
triggering_anchors=(sv.Position.CENTER,),
)
for polygon in polygons
]
timers = [ClockBasedTimer() for _ in zones]
for frame in frames_generator:
fps_monitor.tick()
fps = fps_monitor.fps
results = model.infer(frame, confidence=confidence, iou_threshold=iou)[0]
detections = sv.Detections.from_inference(results)
detections = detections[find_in_list(detections.class_id, classes)]
detections = tracker.update_with_detections(detections)
annotated_frame = frame.copy()
annotated_frame = sv.draw_text(
scene=annotated_frame,
text=f"{fps:.1f}",
text_anchor=sv.Point(40, 30),
background_color=sv.Color.from_hex("#A351FB"),
text_color=sv.Color.from_hex("#000000"),
)
for idx, zone in enumerate(zones):
annotated_frame = sv.draw_polygon(
scene=annotated_frame, polygon=zone.polygon, color=COLORS.by_idx(idx)
)
detections_in_zone = detections[zone.trigger(detections)]
time_in_zone = timers[idx].tick(detections_in_zone)
custom_color_lookup = np.full(detections_in_zone.class_id.shape, idx)
annotated_frame = COLOR_ANNOTATOR.annotate(
scene=annotated_frame,
detections=detections_in_zone,
custom_color_lookup=custom_color_lookup,
)
labels = [
f"#{tracker_id} {int(time // 60):02d}:{int(time % 60):02d}"
for tracker_id, time in zip(detections_in_zone.tracker_id, time_in_zone)
]
annotated_frame = LABEL_ANNOTATOR.annotate(
scene=annotated_frame,
detections=detections_in_zone,
labels=labels,
custom_color_lookup=custom_color_lookup,
)
cv2.imshow("Processed Video", annotated_frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
cv2.destroyAllWindows()
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Calculating detections dwell time in zones, using RTSP stream."
)
parser.add_argument(
"--zone_configuration_path",
type=str,
required=True,
help="Path to the zone configuration JSON file.",
)
parser.add_argument(
"--rtsp_url",
type=str,
required=True,
help="Complete RTSP URL for the video stream.",
)
parser.add_argument(
"--model_id", type=str, default="yolov8s-640", help="Roboflow model ID."
)
parser.add_argument(
"--confidence_threshold",
type=float,
default=0.3,
help="Confidence level for detections (0 to 1). Default is 0.3.",
)
parser.add_argument(
"--iou_threshold",
default=0.7,
type=float,
help="IOU threshold for non-max suppression. Default is 0.7.",
)
parser.add_argument(
"--classes",
nargs="*",
type=int,
default=[],
help="List of class IDs to track. If empty, all classes are tracked.",
)
args = parser.parse_args()
main(
rtsp_url=args.rtsp_url,
zone_configuration_path=args.zone_configuration_path,
model_id=args.model_id,
confidence=args.confidence_threshold,
iou=args.iou_threshold,
classes=args.classes,
)
@@ -0,0 +1,153 @@
import argparse
from typing import List
import cv2
import numpy as np
from inference import InferencePipeline
from inference.core.interfaces.camera.entities import VideoFrame
from utils.general import find_in_list, load_zones_config
from utils.timers import ClockBasedTimer
import supervision as sv
COLORS = sv.ColorPalette.from_hex(["#E6194B", "#3CB44B", "#FFE119", "#3C76D1"])
COLOR_ANNOTATOR = sv.ColorAnnotator(color=COLORS)
LABEL_ANNOTATOR = sv.LabelAnnotator(
color=COLORS, text_color=sv.Color.from_hex("#000000")
)
class CustomSink:
def __init__(self, zone_configuration_path: str, classes: List[int]):
self.classes = classes
self.tracker = sv.ByteTrack(minimum_matching_threshold=0.5)
self.fps_monitor = sv.FPSMonitor()
self.polygons = load_zones_config(file_path=zone_configuration_path)
self.timers = [ClockBasedTimer() for _ in self.polygons]
self.zones = [
sv.PolygonZone(
polygon=polygon,
triggering_anchors=(sv.Position.CENTER,),
)
for polygon in self.polygons
]
def on_prediction(self, result: dict, frame: VideoFrame) -> None:
self.fps_monitor.tick()
fps = self.fps_monitor.fps
detections = sv.Detections.from_inference(result)
detections = detections[find_in_list(detections.class_id, self.classes)]
detections = self.tracker.update_with_detections(detections)
annotated_frame = frame.image.copy()
annotated_frame = sv.draw_text(
scene=annotated_frame,
text=f"{fps:.1f}",
text_anchor=sv.Point(40, 30),
background_color=sv.Color.from_hex("#A351FB"),
text_color=sv.Color.from_hex("#000000"),
)
for idx, zone in enumerate(self.zones):
annotated_frame = sv.draw_polygon(
scene=annotated_frame, polygon=zone.polygon, color=COLORS.by_idx(idx)
)
detections_in_zone = detections[zone.trigger(detections)]
time_in_zone = self.timers[idx].tick(detections_in_zone)
custom_color_lookup = np.full(detections_in_zone.class_id.shape, idx)
annotated_frame = COLOR_ANNOTATOR.annotate(
scene=annotated_frame,
detections=detections_in_zone,
custom_color_lookup=custom_color_lookup,
)
labels = [
f"#{tracker_id} {int(time // 60):02d}:{int(time % 60):02d}"
for tracker_id, time in zip(detections_in_zone.tracker_id, time_in_zone)
]
annotated_frame = LABEL_ANNOTATOR.annotate(
scene=annotated_frame,
detections=detections_in_zone,
labels=labels,
custom_color_lookup=custom_color_lookup,
)
cv2.imshow("Processed Video", annotated_frame)
cv2.waitKey(1)
def main(
rtsp_url: str,
zone_configuration_path: str,
model_id: str,
confidence: float,
iou: float,
classes: List[int],
) -> None:
sink = CustomSink(zone_configuration_path=zone_configuration_path, classes=classes)
pipeline = InferencePipeline.init(
model_id=model_id,
video_reference=rtsp_url,
on_prediction=sink.on_prediction,
confidence=confidence,
iou_threshold=iou,
)
pipeline.start()
try:
pipeline.join()
except KeyboardInterrupt:
pipeline.terminate()
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Calculating detections dwell time in zones, using RTSP stream."
)
parser.add_argument(
"--zone_configuration_path",
type=str,
required=True,
help="Path to the zone configuration JSON file.",
)
parser.add_argument(
"--rtsp_url",
type=str,
required=True,
help="Complete RTSP URL for the video stream.",
)
parser.add_argument(
"--model_id", type=str, default="yolov8s-640", help="Roboflow model ID."
)
parser.add_argument(
"--confidence_threshold",
type=float,
default=0.3,
help="Confidence level for detections (0 to 1). Default is 0.3.",
)
parser.add_argument(
"--iou_threshold",
default=0.7,
type=float,
help="IOU threshold for non-max suppression. Default is 0.7.",
)
parser.add_argument(
"--classes",
nargs="*",
type=int,
default=[],
help="List of class IDs to track. If empty, all classes are tracked.",
)
args = parser.parse_args()
main(
rtsp_url=args.rtsp_url,
zone_configuration_path=args.zone_configuration_path,
model_id=args.model_id,
confidence=args.confidence_threshold,
iou=args.iou_threshold,
classes=args.classes,
)
+5
View File
@@ -0,0 +1,5 @@
opencv-python
supervision>=0.20.0
ultralytics
inference==0.9.17
pytube
@@ -0,0 +1,46 @@
import argparse
import os
from typing import Optional
from pytube import YouTube
def main(url: str, output_path: Optional[str], file_name: Optional[str]) -> None:
yt = YouTube(url)
stream = yt.streams.get_highest_resolution()
if not os.path.exists(output_path):
os.makedirs(output_path)
stream.download(output_path=output_path, filename=file_name)
final_name = file_name if file_name else yt.title
final_path = output_path if output_path else "current directory"
print(f"Download completed! Video saved as '{final_name}' in '{final_path}'.")
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Download a specific YouTube video by providing its URL."
)
parser.add_argument(
"--url",
type=str,
required=True,
help="The full URL of the YouTube video you wish to download.",
)
parser.add_argument(
"--output_path",
type=str,
default="data/source",
required=False,
help="Optional. Specifies the directory where the video will be saved.",
)
parser.add_argument(
"--file_name",
type=str,
default="video.mp4",
required=False,
help="Optional. Sets the name of the saved video file.",
)
args = parser.parse_args()
main(url=args.url, output_path=args.output_path, file_name=args.file_name)
+176
View File
@@ -0,0 +1,176 @@
import argparse
import json
import os
from typing import Any, Optional, Tuple
import cv2
import numpy as np
import supervision as sv
KEY_ENTER = 13
KEY_NEWLINE = 10
KEY_ESCAPE = 27
KEY_QUIT = ord("q")
KEY_SAVE = ord("s")
THICKNESS = 2
COLORS = sv.ColorPalette.DEFAULT
WINDOW_NAME = "Draw Zones"
POLYGONS = [[]]
current_mouse_position: Optional[Tuple[int, int]] = None
def resolve_source(source_path: str) -> Optional[np.ndarray]:
if not os.path.exists(source_path):
return None
image = cv2.imread(source_path)
if image is not None:
return image
frame_generator = sv.get_video_frames_generator(source_path=source_path)
frame = next(frame_generator)
return frame
def mouse_event(event: int, x: int, y: int, flags: int, param: Any) -> None:
global current_mouse_position
if event == cv2.EVENT_MOUSEMOVE:
current_mouse_position = (x, y)
elif event == cv2.EVENT_LBUTTONDOWN:
POLYGONS[-1].append((x, y))
def redraw(image: np.ndarray, original_image: np.ndarray) -> None:
global POLYGONS, current_mouse_position
image[:] = original_image.copy()
for idx, polygon in enumerate(POLYGONS):
color = (
COLORS.by_idx(idx).as_bgr()
if idx < len(POLYGONS) - 1
else sv.Color.WHITE.as_bgr()
)
if len(polygon) > 1:
for i in range(1, len(polygon)):
cv2.line(
img=image,
pt1=polygon[i - 1],
pt2=polygon[i],
color=color,
thickness=THICKNESS,
)
if idx < len(POLYGONS) - 1:
cv2.line(
img=image,
pt1=polygon[-1],
pt2=polygon[0],
color=color,
thickness=THICKNESS,
)
if idx == len(POLYGONS) - 1 and current_mouse_position is not None and polygon:
cv2.line(
img=image,
pt1=polygon[-1],
pt2=current_mouse_position,
color=color,
thickness=THICKNESS,
)
cv2.imshow(WINDOW_NAME, image)
def close_and_finalize_polygon(image: np.ndarray, original_image: np.ndarray) -> None:
if len(POLYGONS[-1]) > 2:
cv2.line(
img=image,
pt1=POLYGONS[-1][-1],
pt2=POLYGONS[-1][0],
color=COLORS.by_idx(0).as_bgr(),
thickness=THICKNESS,
)
POLYGONS.append([])
image[:] = original_image.copy()
redraw_polygons(image)
cv2.imshow(WINDOW_NAME, image)
def redraw_polygons(image: np.ndarray) -> None:
for idx, polygon in enumerate(POLYGONS[:-1]):
if len(polygon) > 1:
color = COLORS.by_idx(idx).as_bgr()
for i in range(len(polygon) - 1):
cv2.line(
img=image,
pt1=polygon[i],
pt2=polygon[i + 1],
color=color,
thickness=THICKNESS,
)
cv2.line(
img=image,
pt1=polygon[-1],
pt2=polygon[0],
color=color,
thickness=THICKNESS,
)
def save_polygons_to_json(polygons, target_path):
data_to_save = polygons if polygons[-1] else polygons[:-1]
with open(target_path, "w") as f:
json.dump(data_to_save, f)
def main(source_path: str, zone_configuration_path: str) -> None:
global current_mouse_position
original_image = resolve_source(source_path=source_path)
if original_image is None:
print("Failed to load source image.")
return
image = original_image.copy()
cv2.imshow(WINDOW_NAME, image)
cv2.setMouseCallback(WINDOW_NAME, mouse_event, image)
while True:
key = cv2.waitKey(1) & 0xFF
if key == KEY_ENTER or key == KEY_NEWLINE:
close_and_finalize_polygon(image, original_image)
elif key == KEY_ESCAPE:
POLYGONS[-1] = []
current_mouse_position = None
elif key == KEY_SAVE:
save_polygons_to_json(POLYGONS, zone_configuration_path)
print(f"Polygons saved to {zone_configuration_path}")
break
redraw(image, original_image)
if key == KEY_QUIT:
break
cv2.destroyAllWindows()
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Interactively draw polygons on images or video frames and save "
"the annotations."
)
parser.add_argument(
"--source_path",
type=str,
required=True,
help="Path to the source image or video file for drawing polygons.",
)
parser.add_argument(
"--zone_configuration_path",
type=str,
required=True,
help="Path where the polygon annotations will be saved as a JSON file.",
)
arguments = parser.parse_args()
main(
source_path=arguments.source_path,
zone_configuration_path=arguments.zone_configuration_path,
)
@@ -0,0 +1,104 @@
import argparse
import os
import subprocess
import tempfile
from glob import glob
from threading import Thread
import yaml
SERVER_CONFIG = {"protocols": ["tcp"], "paths": {"all": {"source": "publisher"}}}
BASE_STREAM_URL = "rtsp://localhost:8554/live"
def main(video_directory: str, number_of_streams: int) -> None:
video_files = find_video_files_in_directory(video_directory, number_of_streams)
try:
with tempfile.TemporaryDirectory() as temporary_directory:
config_file_path = create_server_config_file(temporary_directory)
run_rtsp_server(config_path=config_file_path)
stream_videos(video_files)
finally:
stop_rtsp_server()
def find_video_files_in_directory(directory: str, limit: int) -> list:
video_formats = ["*.mp4", "*.webm"]
video_paths = []
for video_format in video_formats:
video_paths.extend(glob(os.path.join(directory, video_format)))
return video_paths[:limit]
def create_server_config_file(directory: str) -> str:
config_path = os.path.join(directory, "rtsp-simple-server.yml")
with open(config_path, "w") as config_file:
yaml.dump(SERVER_CONFIG, config_file)
return config_path
def run_rtsp_server(config_path: str) -> None:
command = (
"docker run --rm --name rtsp_server -d -v "
f"{config_path}:/rtsp-simple-server.yml -p 8554:8554 "
"aler9/rtsp-simple-server:v1.3.0"
)
if run_command(command.split()) != 0:
raise RuntimeError("Could not start the RTSP server!")
def stop_rtsp_server() -> None:
run_command("docker kill rtsp_server".split())
def stream_videos(video_files: list) -> None:
threads = []
for index, video_file in enumerate(video_files):
stream_url = f"{BASE_STREAM_URL}{index}.stream"
print(f"Streaming {video_file} under {stream_url}")
thread = stream_video_to_url(video_file, stream_url)
threads.append(thread)
for thread in threads:
thread.join()
def stream_video_to_url(video_path: str, stream_url: str) -> Thread:
command = (
f"ffmpeg -re -stream_loop -1 -i {video_path} "
f"-f rtsp -rtsp_transport tcp {stream_url}"
)
return run_command_in_thread(command.split())
def run_command_in_thread(command: list) -> Thread:
thread = Thread(target=run_command, args=(command,))
thread.start()
return thread
def run_command(command: list) -> int:
process = subprocess.run(command)
return process.returncode
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Script to stream videos using RTSP protocol."
)
parser.add_argument(
"--video_directory",
type=str,
required=True,
help="Directory containing video files to stream.",
)
parser.add_argument(
"--number_of_streams",
type=int,
default=6,
help="Number of video files to stream.",
)
arguments = parser.parse_args()
main(
video_directory=arguments.video_directory,
number_of_streams=arguments.number_of_streams,
)
@@ -0,0 +1,140 @@
import argparse
from typing import List
import cv2
import numpy as np
from ultralytics import YOLO
from utils.general import find_in_list, load_zones_config
from utils.timers import FPSBasedTimer
import supervision as sv
COLORS = sv.ColorPalette.from_hex(["#E6194B", "#3CB44B", "#FFE119", "#3C76D1"])
COLOR_ANNOTATOR = sv.ColorAnnotator(color=COLORS)
LABEL_ANNOTATOR = sv.LabelAnnotator(
color=COLORS, text_color=sv.Color.from_hex("#000000")
)
def main(
source_video_path: str,
zone_configuration_path: str,
weights: str,
device: str,
confidence: float,
iou: float,
classes: List[int],
) -> None:
model = YOLO(weights)
tracker = sv.ByteTrack(minimum_matching_threshold=0.5)
video_info = sv.VideoInfo.from_video_path(video_path=source_video_path)
frames_generator = sv.get_video_frames_generator(source_video_path)
polygons = load_zones_config(file_path=zone_configuration_path)
zones = [
sv.PolygonZone(
polygon=polygon,
triggering_anchors=(sv.Position.CENTER,),
)
for polygon in polygons
]
timers = [FPSBasedTimer(video_info.fps) for _ in zones]
for frame in frames_generator:
results = model(frame, verbose=False, device=device, conf=confidence)[0]
detections = sv.Detections.from_ultralytics(results)
detections = detections[find_in_list(detections.class_id, classes)]
detections = detections.with_nms(threshold=iou)
detections = tracker.update_with_detections(detections)
annotated_frame = frame.copy()
for idx, zone in enumerate(zones):
annotated_frame = sv.draw_polygon(
scene=annotated_frame, polygon=zone.polygon, color=COLORS.by_idx(idx)
)
detections_in_zone = detections[zone.trigger(detections)]
time_in_zone = timers[idx].tick(detections_in_zone)
custom_color_lookup = np.full(detections_in_zone.class_id.shape, idx)
annotated_frame = COLOR_ANNOTATOR.annotate(
scene=annotated_frame,
detections=detections_in_zone,
custom_color_lookup=custom_color_lookup,
)
labels = [
f"#{tracker_id} {int(time // 60):02d}:{int(time % 60):02d}"
for tracker_id, time in zip(detections_in_zone.tracker_id, time_in_zone)
]
annotated_frame = LABEL_ANNOTATOR.annotate(
scene=annotated_frame,
detections=detections_in_zone,
labels=labels,
custom_color_lookup=custom_color_lookup,
)
cv2.imshow("Processed Video", annotated_frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
cv2.destroyAllWindows()
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Calculating detections dwell time in zones, using video file."
)
parser.add_argument(
"--zone_configuration_path",
type=str,
required=True,
help="Path to the zone configuration JSON file.",
)
parser.add_argument(
"--source_video_path",
type=str,
required=True,
help="Path to the source video file.",
)
parser.add_argument(
"--weights",
type=str,
default="yolov8s.pt",
help="Path to the model weights file. Default is 'yolov8s.pt'.",
)
parser.add_argument(
"--device",
type=str,
default="cpu",
help="Computation device ('cpu', 'mps' or 'cuda'). Default is 'cpu'.",
)
parser.add_argument(
"--confidence_threshold",
type=float,
default=0.3,
help="Confidence level for detections (0 to 1). Default is 0.3.",
)
parser.add_argument(
"--iou_threshold",
default=0.7,
type=float,
help="IOU threshold for non-max suppression. Default is 0.7.",
)
parser.add_argument(
"--classes",
nargs="*",
type=int,
default=[],
help="List of class IDs to track. If empty, all classes are tracked.",
)
args = parser.parse_args()
main(
source_video_path=args.source_video_path,
zone_configuration_path=args.zone_configuration_path,
weights=args.weights,
device=args.device,
confidence=args.confidence_threshold,
iou=args.iou_threshold,
classes=args.classes,
)
@@ -0,0 +1,150 @@
import argparse
from typing import List
import cv2
import numpy as np
from ultralytics import YOLO
from utils.general import find_in_list, get_stream_frames_generator, load_zones_config
from utils.timers import ClockBasedTimer
import supervision as sv
COLORS = sv.ColorPalette.from_hex(["#E6194B", "#3CB44B", "#FFE119", "#3C76D1"])
COLOR_ANNOTATOR = sv.ColorAnnotator(color=COLORS)
LABEL_ANNOTATOR = sv.LabelAnnotator(
color=COLORS, text_color=sv.Color.from_hex("#000000")
)
def main(
rtsp_url: str,
zone_configuration_path: str,
weights: str,
device: str,
confidence: float,
iou: float,
classes: List[int],
) -> None:
model = YOLO(weights)
tracker = sv.ByteTrack(minimum_matching_threshold=0.5)
frames_generator = get_stream_frames_generator(rtsp_url=rtsp_url)
fps_monitor = sv.FPSMonitor()
polygons = load_zones_config(file_path=zone_configuration_path)
zones = [
sv.PolygonZone(
polygon=polygon,
triggering_anchors=(sv.Position.CENTER,),
)
for polygon in polygons
]
timers = [ClockBasedTimer() for _ in zones]
for frame in frames_generator:
fps_monitor.tick()
fps = fps_monitor.fps
results = model(frame, verbose=False, device=device, conf=confidence)[0]
detections = sv.Detections.from_ultralytics(results)
detections = detections[find_in_list(detections.class_id, classes)]
detections = detections.with_nms(threshold=iou)
detections = tracker.update_with_detections(detections)
annotated_frame = frame.copy()
annotated_frame = sv.draw_text(
scene=annotated_frame,
text=f"{fps:.1f}",
text_anchor=sv.Point(40, 30),
background_color=sv.Color.from_hex("#A351FB"),
text_color=sv.Color.from_hex("#000000"),
)
for idx, zone in enumerate(zones):
annotated_frame = sv.draw_polygon(
scene=annotated_frame, polygon=zone.polygon, color=COLORS.by_idx(idx)
)
detections_in_zone = detections[zone.trigger(detections)]
time_in_zone = timers[idx].tick(detections_in_zone)
custom_color_lookup = np.full(detections_in_zone.class_id.shape, idx)
annotated_frame = COLOR_ANNOTATOR.annotate(
scene=annotated_frame,
detections=detections_in_zone,
custom_color_lookup=custom_color_lookup,
)
labels = [
f"#{tracker_id} {int(time // 60):02d}:{int(time % 60):02d}"
for tracker_id, time in zip(detections_in_zone.tracker_id, time_in_zone)
]
annotated_frame = LABEL_ANNOTATOR.annotate(
scene=annotated_frame,
detections=detections_in_zone,
labels=labels,
custom_color_lookup=custom_color_lookup,
)
cv2.imshow("Processed Video", annotated_frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
cv2.destroyAllWindows()
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Calculating detections dwell time in zones, using RTSP stream."
)
parser.add_argument(
"--zone_configuration_path",
type=str,
required=True,
help="Path to the zone configuration JSON file.",
)
parser.add_argument(
"--rtsp_url",
type=str,
required=True,
help="Complete RTSP URL for the video stream.",
)
parser.add_argument(
"--weights",
type=str,
default="yolov8s.pt",
help="Path to the model weights file. Default is 'yolov8s.pt'.",
)
parser.add_argument(
"--device",
type=str,
default="cpu",
help="Computation device ('cpu', 'mps' or 'cuda'). Default is 'cpu'.",
)
parser.add_argument(
"--confidence_threshold",
type=float,
default=0.3,
help="Confidence level for detections (0 to 1). Default is 0.3.",
)
parser.add_argument(
"--iou_threshold",
default=0.7,
type=float,
help="IOU threshold for non-max suppression. Default is 0.7.",
)
parser.add_argument(
"--classes",
nargs="*",
type=int,
default=[],
help="List of class IDs to track. If empty, all classes are tracked.",
)
args = parser.parse_args()
main(
rtsp_url=args.rtsp_url,
zone_configuration_path=args.zone_configuration_path,
weights=args.weights,
device=args.device,
confidence=args.confidence_threshold,
iou=args.iou_threshold,
classes=args.classes,
)
@@ -0,0 +1,168 @@
import argparse
from typing import List
import cv2
import numpy as np
from inference import InferencePipeline
from inference.core.interfaces.camera.entities import VideoFrame
from ultralytics import YOLO
from utils.general import find_in_list, load_zones_config
from utils.timers import ClockBasedTimer
import supervision as sv
COLORS = sv.ColorPalette.from_hex(["#E6194B", "#3CB44B", "#FFE119", "#3C76D1"])
COLOR_ANNOTATOR = sv.ColorAnnotator(color=COLORS)
LABEL_ANNOTATOR = sv.LabelAnnotator(
color=COLORS, text_color=sv.Color.from_hex("#000000")
)
class CustomSink:
def __init__(self, zone_configuration_path: str, classes: List[int]):
self.classes = classes
self.tracker = sv.ByteTrack(minimum_matching_threshold=0.8)
self.fps_monitor = sv.FPSMonitor()
self.polygons = load_zones_config(file_path=zone_configuration_path)
self.timers = [ClockBasedTimer() for _ in self.polygons]
self.zones = [
sv.PolygonZone(
polygon=polygon,
triggering_anchors=(sv.Position.CENTER,),
)
for polygon in self.polygons
]
def on_prediction(self, detections: sv.Detections, frame: VideoFrame) -> None:
self.fps_monitor.tick()
fps = self.fps_monitor.fps
detections = detections[find_in_list(detections.class_id, self.classes)]
detections = self.tracker.update_with_detections(detections)
annotated_frame = frame.image.copy()
annotated_frame = sv.draw_text(
scene=annotated_frame,
text=f"{fps:.1f}",
text_anchor=sv.Point(40, 30),
background_color=sv.Color.from_hex("#A351FB"),
text_color=sv.Color.from_hex("#000000"),
)
for idx, zone in enumerate(self.zones):
annotated_frame = sv.draw_polygon(
scene=annotated_frame, polygon=zone.polygon, color=COLORS.by_idx(idx)
)
detections_in_zone = detections[zone.trigger(detections)]
time_in_zone = self.timers[idx].tick(detections_in_zone)
custom_color_lookup = np.full(detections_in_zone.class_id.shape, idx)
annotated_frame = COLOR_ANNOTATOR.annotate(
scene=annotated_frame,
detections=detections_in_zone,
custom_color_lookup=custom_color_lookup,
)
labels = [
f"#{tracker_id} {int(time // 60):02d}:{int(time % 60):02d}"
for tracker_id, time in zip(detections_in_zone.tracker_id, time_in_zone)
]
annotated_frame = LABEL_ANNOTATOR.annotate(
scene=annotated_frame,
detections=detections_in_zone,
labels=labels,
custom_color_lookup=custom_color_lookup,
)
cv2.imshow("Processed Video", annotated_frame)
cv2.waitKey(1)
def main(
rtsp_url: str,
zone_configuration_path: str,
weights: str,
device: str,
confidence: float,
iou: float,
classes: List[int],
) -> None:
model = YOLO(weights)
def inference_callback(frame: VideoFrame) -> sv.Detections:
results = model(frame.image, verbose=False, conf=confidence, device=device)[0]
return sv.Detections.from_ultralytics(results).with_nms(threshold=iou)
sink = CustomSink(zone_configuration_path=zone_configuration_path, classes=classes)
pipeline = InferencePipeline.init_with_custom_logic(
video_reference=rtsp_url,
on_video_frame=inference_callback,
on_prediction=sink.on_prediction,
)
pipeline.start()
try:
pipeline.join()
except KeyboardInterrupt:
pipeline.terminate()
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Calculating detections dwell time in zones, using RTSP stream."
)
parser.add_argument(
"--zone_configuration_path",
type=str,
required=True,
help="Path to the zone configuration JSON file.",
)
parser.add_argument(
"--rtsp_url",
type=str,
required=True,
help="Complete RTSP URL for the video stream.",
)
parser.add_argument(
"--weights",
type=str,
default="yolov8s.pt",
help="Path to the model weights file. Default is 'yolov8s.pt'.",
)
parser.add_argument(
"--device",
type=str,
default="cpu",
help="Computation device ('cpu', 'mps' or 'cuda'). Default is 'cpu'.",
)
parser.add_argument(
"--confidence_threshold",
type=float,
default=0.3,
help="Confidence level for detections (0 to 1). Default is 0.3.",
)
parser.add_argument(
"--iou_threshold",
default=0.7,
type=float,
help="IOU threshold for non-max suppression. Default is 0.7.",
)
parser.add_argument(
"--classes",
nargs="*",
type=int,
default=[],
help="List of class IDs to track. If empty, all classes are tracked.",
)
args = parser.parse_args()
main(
rtsp_url=args.rtsp_url,
zone_configuration_path=args.zone_configuration_path,
weights=args.weights,
device=args.device,
confidence=args.confidence_threshold,
iou=args.iou_threshold,
classes=args.classes,
)
+66
View File
@@ -0,0 +1,66 @@
import json
from typing import Generator, List
import cv2
import numpy as np
def load_zones_config(file_path: str) -> List[np.ndarray]:
"""
Load polygon zone configurations from a JSON file.
This function reads a JSON file which contains polygon coordinates, and
converts them into a list of NumPy arrays. Each polygon is represented as
a NumPy array of coordinates.
Args:
file_path (str): The path to the JSON configuration file.
Returns:
List[np.ndarray]: A list of polygons, each represented as a NumPy array.
"""
with open(file_path, "r") as file:
data = json.load(file)
return [np.array(polygon, np.int32) for polygon in data]
def find_in_list(array: np.ndarray, search_list: List[int]) -> np.ndarray:
"""Determines if elements of a numpy array are present in a list.
Args:
array (np.ndarray): The numpy array of integers to check.
search_list (List[int]): The list of integers to search within.
Returns:
np.ndarray: A numpy array of booleans, where each boolean indicates whether
the corresponding element in `array` is found in `search_list`.
"""
if not search_list:
return np.ones(array.shape, dtype=bool)
else:
return np.isin(array, search_list)
def get_stream_frames_generator(rtsp_url: str) -> Generator[np.ndarray, None, None]:
"""
Generator function to yield frames from an RTSP stream.
Args:
rtsp_url (str): URL of the RTSP video stream.
Yields:
np.ndarray: The next frame from the video stream.
"""
cap = cv2.VideoCapture(rtsp_url)
if not cap.isOpened():
raise Exception("Error: Could not open video stream.")
try:
while True:
ret, frame = cap.read()
if not ret:
print("End of stream or error reading frame.")
break
yield frame
finally:
cap.release()
+88
View File
@@ -0,0 +1,88 @@
from datetime import datetime
from typing import Dict
import numpy as np
import supervision as sv
class FPSBasedTimer:
"""
A timer that calculates the duration each object has been detected based on frames
per second (FPS).
Attributes:
fps (int): The frame rate of the video stream, used to calculate time durations.
frame_id (int): The current frame number in the sequence.
tracker_id2frame_id (Dict[int, int]): Maps each tracker's ID to the frame number
at which it was first detected.
"""
def __init__(self, fps: int = 30) -> None:
"""Initializes the FPSBasedTimer with the specified frames per second rate.
Args:
fps (int, optional): The frame rate of the video stream. Defaults to 30.
"""
self.fps = fps
self.frame_id = 0
self.tracker_id2frame_id: Dict[int, int] = {}
def tick(self, detections: sv.Detections) -> np.ndarray:
"""Processes the current frame, updating time durations for each tracker.
Args:
detections: The detections for the current frame, including tracker IDs.
Returns:
np.ndarray: Time durations (in seconds) for each detected tracker, since
their first detection.
"""
self.frame_id += 1
times = []
for tracker_id in detections.tracker_id:
self.tracker_id2frame_id.setdefault(tracker_id, self.frame_id)
start_frame_id = self.tracker_id2frame_id[tracker_id]
time_duration = (self.frame_id - start_frame_id) / self.fps
times.append(time_duration)
return np.array(times)
class ClockBasedTimer:
"""
A timer that calculates the duration each object has been detected based on the
system clock.
Attributes:
tracker_id2start_time (Dict[int, datetime]): Maps each tracker's ID to the
datetime when it was first detected.
"""
def __init__(self) -> None:
"""Initializes the ClockBasedTimer."""
self.tracker_id2start_time: Dict[int, datetime] = {}
def tick(self, detections: sv.Detections) -> np.ndarray:
"""Processes the current frame, updating time durations for each tracker.
Args:
detections: The detections for the current frame, including tracker IDs.
Returns:
np.ndarray: Time durations (in seconds) for each detected tracker, since
their first detection.
"""
current_time = datetime.now()
times = []
for tracker_id in detections.tracker_id:
self.tracker_id2start_time.setdefault(tracker_id, current_time)
start_time = self.tracker_id2start_time[tracker_id]
time_duration = (current_time - start_time).total_seconds()
times.append(time_duration)
return np.array(times)
+2 -2
View File
@@ -1,4 +1,4 @@
inference
supervision
inference==0.9.17
supervision==0.19.0
tqdm
ultralytics
+5 -13
View File
@@ -1,6 +1,6 @@
import argparse
import os
from typing import Dict, Iterable, List, Set, Tuple
from typing import Dict, Iterable, List, Set
import cv2
import numpy as np
@@ -60,13 +60,11 @@ class DetectionsManager:
def initiate_polygon_zones(
polygons: List[np.ndarray],
frame_resolution_wh: Tuple[int, int],
triggering_anchors: Iterable[sv.Position] = [sv.Position.CENTER],
) -> List[sv.PolygonZone]:
return [
sv.PolygonZone(
polygon=polygon,
frame_resolution_wh=frame_resolution_wh,
triggering_anchors=triggering_anchors,
)
for polygon in polygons
@@ -92,14 +90,10 @@ class VideoProcessor:
self.tracker = sv.ByteTrack()
self.video_info = sv.VideoInfo.from_video_path(source_video_path)
self.zones_in = initiate_polygon_zones(
ZONE_IN_POLYGONS, self.video_info.resolution_wh, [sv.Position.CENTER]
)
self.zones_out = initiate_polygon_zones(
ZONE_OUT_POLYGONS, self.video_info.resolution_wh, [sv.Position.CENTER]
)
self.zones_in = initiate_polygon_zones(ZONE_IN_POLYGONS, [sv.Position.CENTER])
self.zones_out = initiate_polygon_zones(ZONE_OUT_POLYGONS, [sv.Position.CENTER])
self.bounding_box_annotator = sv.BoundingBoxAnnotator(color=COLORS)
self.box_annotator = sv.BoxAnnotator(color=COLORS)
self.label_annotator = sv.LabelAnnotator(
color=COLORS, text_color=sv.Color.BLACK
)
@@ -140,9 +134,7 @@ class VideoProcessor:
labels = [f"#{tracker_id}" for tracker_id in detections.tracker_id]
annotated_frame = self.trace_annotator.annotate(annotated_frame, detections)
annotated_frame = self.bounding_box_annotator.annotate(
annotated_frame, detections
)
annotated_frame = self.box_annotator.annotate(annotated_frame, detections)
annotated_frame = self.label_annotator.annotate(
annotated_frame, detections, labels
)
+2 -2
View File
@@ -1,5 +1,5 @@
gdown
inference
supervision>=0.19.0rc5
inference==0.9.17
supervision>=0.20.0
tqdm
ultralytics
@@ -1,5 +1,5 @@
import argparse
from typing import Dict, Iterable, List, Set, Tuple
from typing import Dict, Iterable, List, Set
import cv2
import numpy as np
@@ -58,13 +58,11 @@ class DetectionsManager:
def initiate_polygon_zones(
polygons: List[np.ndarray],
frame_resolution_wh: Tuple[int, int],
triggering_anchors: Iterable[sv.Position] = [sv.Position.CENTER],
) -> List[sv.PolygonZone]:
return [
sv.PolygonZone(
polygon=polygon,
frame_resolution_wh=frame_resolution_wh,
triggering_anchors=triggering_anchors,
)
for polygon in polygons
@@ -89,14 +87,10 @@ class VideoProcessor:
self.tracker = sv.ByteTrack()
self.video_info = sv.VideoInfo.from_video_path(source_video_path)
self.zones_in = initiate_polygon_zones(
ZONE_IN_POLYGONS, self.video_info.resolution_wh, [sv.Position.CENTER]
)
self.zones_out = initiate_polygon_zones(
ZONE_OUT_POLYGONS, self.video_info.resolution_wh, [sv.Position.CENTER]
)
self.zones_in = initiate_polygon_zones(ZONE_IN_POLYGONS, [sv.Position.CENTER])
self.zones_out = initiate_polygon_zones(ZONE_OUT_POLYGONS, [sv.Position.CENTER])
self.bounding_box_annotator = sv.BoundingBoxAnnotator(color=COLORS)
self.box_annotator = sv.BoxAnnotator(color=COLORS)
self.label_annotator = sv.LabelAnnotator(
color=COLORS, text_color=sv.Color.BLACK
)
@@ -137,9 +131,7 @@ class VideoProcessor:
labels = [f"#{tracker_id}" for tracker_id in detections.tracker_id]
annotated_frame = self.trace_annotator.annotate(annotated_frame, detections)
annotated_frame = self.bounding_box_annotator.annotate(
annotated_frame, detections
)
annotated_frame = self.box_annotator.annotate(annotated_frame, detections)
annotated_frame = self.label_annotator.annotate(
annotated_frame, detections, labels
)
+33 -17
View File
@@ -35,18 +35,26 @@ extra_css:
nav:
- Home: index.md
- How to:
- Supervision: index.md
- Learn:
- Detect and Annotate: how_to/detect_and_annotate.md
- Track Objects: how_to/track_objects.md
- Save Detections: how_to/save_detections.md
- Filter Detections: how_to/filter_detections.md
- API:
- Annotators: annotators.md
- Classifications:
- Core: classification/core.md
- Detections:
- Detect Small Objects: how_to/detect_small_objects.md
- Track Objects on Video: how_to/track_objects.md
- Reference - Code API:
- Detection and Segmentation:
- Core: detection/core.md
- Annotators: detection/annotators.md
- Metrics: detection/metrics.md
- Double Detection Filter: detection/double_detection_filter.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
@@ -54,26 +62,25 @@ nav:
- Detection Smoother: detection/tools/smoother.md
- 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
- Datasets:
- Core: datasets/core.md
- Utils: datasets/utils.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
- Cheatsheet: https://roboflow.github.io/cheatsheet-supervision/
- Contribute:
- Contributing: contributing.md
- Code of Conduct: code_of_conduct.md
- License: license.md
- Changelog:
- Release Notes:
- Changelog: changelog.md
- Deprecated: deprecated.md
@@ -172,3 +179,12 @@ extra_javascript:
- "javascripts/init_kapa_widget.js"
- "javascripts/cookbooks-card.js"
- "https://cdnjs.cloudflare.com/ajax/libs/dompurify/3.0.8/purify.min.js"
# Messages shown during document build
# Reference: https://www.mkdocs.org/user-guide/configuration/#validation
# Values: [warn, info, ignore]
validation:
nav:
absolute_links: ignore
links:
absolute_links: ignore
Generated
+1053 -992
View File
File diff suppressed because it is too large Load Diff
+73 -19
View File
@@ -1,18 +1,26 @@
[tool.poetry]
name = "supervision"
version = "0.19.0"
version = "0.22.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>"]
readme = "README.md"
license = "MIT"
packages = [{include = "supervision"}]
packages = [{ include = "supervision" }]
homepage = "https://github.com/roboflow/supervision"
repository = "https://github.com/roboflow/supervision"
documentation = "https://github.com/roboflow/supervision/blob/main/README.md"
keywords = ["machine-learning", "deep-learning", "vision", "ML", "DL", "AI", "Roboflow"]
keywords = [
"machine-learning",
"deep-learning",
"vision",
"ML",
"DL",
"AI",
"Roboflow",
]
classifiers=[
classifiers = [
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: Education',
@@ -27,7 +35,7 @@ classifiers=[
'Typing :: Typed',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX :: Linux',
'Operating System :: MacOS'
'Operating System :: MacOS',
]
[tool.poetry.dependencies]
@@ -35,26 +43,26 @@ python = "^3.8"
numpy = ">=1.21.2"
scipy = [
{ version = "1.10.0", python = "<3.9" },
{ version = "^1.10.0", python = ">=3.9" }
{ version = "^1.10.0", python = ">=3.9" },
]
matplotlib = ">=3.6.0"
pyyaml = ">=5.3"
defusedxml = "^0.7.1"
opencv-python = { version = ">=4.5.5.64", optional = true }
opencv-python-headless = ">=4.5.5.64"
requests = { version = ">=2.26.0,<=2.31.0", optional = true }
tqdm = { version = ">=4.62.3,<=4.66.2", optional = true }
requests = { version = ">=2.26.0,<=2.32.3", optional = true }
tqdm = { version = ">=4.62.3,<=4.66.4", optional = true }
pillow = ">=9.4"
[tool.poetry.extras]
desktop = ["opencv-python"]
assets = ["requests","tqdm"]
assets = ["requests", "tqdm"]
[tool.poetry.group.dev.dependencies]
twine = ">=4.0.2,<6.0.0"
twine = "^5.1.1"
pytest = ">=7.2.2,<9.0.0"
wheel = ">=0.40,<0.44"
build = ">=0.10,<1.2"
build = ">=0.10,<1.3"
ruff = ">=0.1.0"
mypy = "^1.4.1"
pre-commit = "^3.3.3"
@@ -63,11 +71,15 @@ notebook = ">=6.5.3,<8.0.0"
ipywidgets = "^8.1.1"
jupytext = "^1.16.1"
nbconvert = "^7.14.2"
docutils = [
{ version = "^0.20.1", python = "<3.9" },
{ version = "^0.21.1", python = ">=3.9" },
]
[tool.poetry.group.docs.dependencies]
mkdocs-material = {extras = ["imaging"], version = "^9.5.5"}
mkdocstrings = {extras = ["python"], version = ">=0.20,<0.25"}
mkdocs-material = { extras = ["imaging"], version = "^9.5.5" }
mkdocstrings = { extras = ["python"], version = ">=0.20,<0.26" }
mike = "^2.0.0"
# For Documentation Development use Python 3.10 or above
# Use Latest mkdocs-jupyter min 0.24.6 for Jupyter Notebook Theme support
@@ -75,8 +87,6 @@ mkdocs-jupyter = "^0.24.3"
mkdocs-git-committers-plugin-2 = "^2.2.3"
mkdocs-git-revision-date-localized-plugin = "^1.2.4"
[tool.isort]
line_length = 88
profile = "black"
@@ -89,7 +99,6 @@ tests = ["B201", "B301", "B318", "B314", "B303", "B413", "B412", "B410"]
check = true
imports = ["cv2", "supervision"]
[tool.black]
target-version = ["py38"]
line-length = 88
@@ -148,7 +157,52 @@ indent-width = 4
select = ["E", "F"]
ignore = []
# Allow autofix for all enabled rules (when `--fix`) is provided.
fixable = ["A", "B", "C", "D", "E", "F", "G", "I", "N", "Q", "S", "T", "W", "ANN", "ARG", "BLE", "COM", "DJ", "DTZ", "EM", "ERA", "EXE", "FBT", "ICN", "INP", "ISC", "NPY", "PD", "PGH", "PIE", "PL", "PT", "PTH", "PYI", "RET", "RSE", "RUF", "SIM", "SLF", "TCH", "TID", "TRY", "UP", "YTT"]
fixable = [
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"I",
"N",
"Q",
"S",
"T",
"W",
"ANN",
"ARG",
"BLE",
"COM",
"DJ",
"DTZ",
"EM",
"ERA",
"EXE",
"FBT",
"ICN",
"INP",
"ISC",
"NPY",
"PD",
"PGH",
"PIE",
"PL",
"PT",
"PTH",
"PYI",
"RET",
"RSE",
"RUF",
"SIM",
"SLF",
"TCH",
"TID",
"TRY",
"UP",
"YTT",
]
unfixable = []
# Allow unused variables when underscore-prefixed.
dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
@@ -163,7 +217,7 @@ docstring-quotes = "double"
convention = "google"
[tool.ruff.lint.per-file-ignores]
"__init__.py" = ["E402","F401"]
"__init__.py" = ["E402", "F401"]
[tool.ruff.lint.mccabe]
# Flag errors (`C901`) whenever the complexity level exceeds 5.
@@ -186,7 +240,7 @@ line-ending = "auto"
include-package-data = false
[tool.setuptools.packages.find]
exclude = ["docs*", "test*","examples*"]
exclude = ["docs*", "test*", "examples*"]
[build-system]
requires = ["poetry-core"]
+19
View File
@@ -0,0 +1,19 @@
# Release Process
This doc outlines how supervision is released into production.
It assumes you already have the code changes, as well as a draft of the release notes.
1. Make sure you have all required changes were merged into `develop`.
2. Create and merge a PR, merging `develop` into `main`, containing:
- A commit that updates the project version in `pyproject.toml`.
- All changes made during the release.
3. Tag the commit with the new supervision version.
- Upon pushing the tag, the [PyPi](https://pypi.org/project/supervision/) should update to the new version. Check this!
4. Open and merge a PR, merging `main` into `develop`.
5. Update the docs by running the [Supervision Release Documentation Workflow 📚](https://github.com/roboflow/supervision/actions/workflows/publish-release-docs.yml) workflow from GitHub.
- Select the `main` branch from the dropdown.
6. Create a release on GitHub.
- Go to releases
- Assign the release notes to the tag created in step 3.
- Publish the release.
+35 -6
View File
@@ -9,6 +9,7 @@ except importlib_metadata.PackageNotFoundError:
from supervision.annotators.core import (
BlurAnnotator,
BoundingBoxAnnotator,
BoxAnnotator,
BoxCornerAnnotator,
CircleAnnotator,
ColorAnnotator,
@@ -23,6 +24,7 @@ from supervision.annotators.core import (
PercentageBarAnnotator,
PixelateAnnotator,
PolygonAnnotator,
RichLabelAnnotator,
RoundBoxAnnotator,
TraceAnnotator,
TriangleAnnotator,
@@ -34,9 +36,16 @@ from supervision.dataset.core import (
ClassificationDataset,
DetectionDataset,
)
from supervision.detection.annotate import BoxAnnotator
from supervision.dataset.utils import mask_to_rle, rle_to_mask
from supervision.detection.core import Detections
from supervision.detection.line_zone import LineZone, LineZoneAnnotator
from supervision.detection.lmm import LMM
from supervision.detection.overlap_filter import (
OverlapFilter,
box_non_max_merge,
box_non_max_suppression,
mask_non_max_suppression,
)
from supervision.detection.tools.csv_sink import CSVSink
from supervision.detection.tools.inference_slicer import InferenceSlicer
from supervision.detection.tools.json_sink import JSONSink
@@ -44,22 +53,27 @@ from supervision.detection.tools.polygon_zone import PolygonZone, PolygonZoneAnn
from supervision.detection.tools.smoother import DetectionsSmoother
from supervision.detection.utils import (
box_iou_batch,
box_non_max_suppression,
calculate_masks_centroids,
clip_boxes,
contains_holes,
contains_multiple_segments,
filter_polygons_by_area,
mask_iou_batch,
mask_non_max_suppression,
mask_to_polygons,
mask_to_xyxy,
move_boxes,
move_masks,
pad_boxes,
polygon_to_mask,
polygon_to_xyxy,
scale_boxes,
xcycwh_to_xyxy,
xywh_to_xyxy,
)
from supervision.draw.color import Color, ColorPalette
from supervision.draw.utils import (
calculate_dynamic_line_thickness,
calculate_dynamic_text_scale,
calculate_optimal_line_thickness,
calculate_optimal_text_scale,
draw_filled_rectangle,
draw_image,
draw_line,
@@ -69,10 +83,25 @@ 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,
VertexLabelAnnotator,
)
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,
+446 -122
View File
@@ -3,13 +3,14 @@ from typing import List, Optional, Tuple, Union
import cv2
import numpy as np
from PIL import ImageDraw, ImageFont
from supervision.annotators.base import BaseAnnotator, ImageType
from supervision.annotators.utils import (
ColorLookup,
Trace,
resolve_color,
scene_to_annotator_img_type,
resolve_text_background_xyxy,
)
from supervision.config import CLASS_NAME_DATA_FIELD, ORIENTED_BOX_COORDINATES
from supervision.detection.core import Detections
@@ -17,9 +18,99 @@ 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 (
ensure_cv2_image_for_annotation,
ensure_pil_image_for_annotation,
)
from supervision.utils.image import crop_image, overlay_image, scale_image
from supervision.utils.internal import deprecated
class BoxAnnotator(BaseAnnotator):
"""
A class for drawing bounding boxes on an image using provided detections.
"""
def __init__(
self,
color: Union[Color, ColorPalette] = ColorPalette.DEFAULT,
thickness: int = 2,
color_lookup: ColorLookup = ColorLookup.CLASS,
):
"""
Args:
color (Union[Color, ColorPalette]): The color or color palette to use for
annotating detections.
thickness (int): Thickness of the bounding box lines.
color_lookup (str): Strategy for mapping colors to annotations.
Options are `INDEX`, `CLASS`, `TRACK`.
"""
self.color: Union[Color, ColorPalette] = color
self.thickness: int = thickness
self.color_lookup: ColorLookup = color_lookup
@ensure_cv2_image_for_annotation
def annotate(
self,
scene: ImageType,
detections: Detections,
custom_color_lookup: Optional[np.ndarray] = None,
) -> ImageType:
"""
Annotates the given scene with bounding boxes based on the provided detections.
Args:
scene (ImageType): The image where bounding boxes will be drawn. `ImageType`
is a flexible type, accepting either `numpy.ndarray` or `PIL.Image.Image`.
detections (Detections): Object detections to annotate.
custom_color_lookup (Optional[np.ndarray]): Custom color lookup array.
Allows to override the default color mapping strategy.
Returns:
The annotated image, matching the type of `scene` (`numpy.ndarray`
or `PIL.Image.Image`)
Example:
```python
import supervision as sv
image = ...
detections = sv.Detections(...)
box_annotator = sv.BoxAnnotator()
annotated_frame = box_annotator.annotate(
scene=image.copy(),
detections=detections
)
```
![bounding-box-annotator-example](https://media.roboflow.com/
supervision-annotator-examples/bounding-box-annotator-example-purple.png)
"""
for detection_idx in range(len(detections)):
x1, y1, x2, y2 = detections.xyxy[detection_idx].astype(int)
color = resolve_color(
color=self.color,
detections=detections,
detection_idx=detection_idx,
color_lookup=self.color_lookup
if custom_color_lookup is None
else custom_color_lookup,
)
cv2.rectangle(
img=scene,
pt1=(x1, y1),
pt2=(x2, y2),
color=color.as_bgr(),
thickness=self.thickness,
)
return scene
@deprecated(
"`BoundingBoxAnnotator` is deprecated and has been renamed to `BoxAnnotator`."
" `BoundingBoxAnnotator` will be removed in supervision-0.26.0."
)
class BoundingBoxAnnotator(BaseAnnotator):
"""
A class for drawing bounding boxes on an image using provided detections.
@@ -43,7 +134,7 @@ class BoundingBoxAnnotator(BaseAnnotator):
self.thickness: int = thickness
self.color_lookup: ColorLookup = color_lookup
@scene_to_annotator_img_type
@ensure_cv2_image_for_annotation
def annotate(
self,
scene: ImageType,
@@ -124,7 +215,7 @@ class OrientedBoxAnnotator(BaseAnnotator):
self.thickness: int = thickness
self.color_lookup: ColorLookup = color_lookup
@scene_to_annotator_img_type
@ensure_cv2_image_for_annotation
def annotate(
self,
scene: ImageType,
@@ -170,7 +261,7 @@ class OrientedBoxAnnotator(BaseAnnotator):
return scene
for detection_idx in range(len(detections)):
bbox = np.int0(detections.data.get(ORIENTED_BOX_COORDINATES)[detection_idx])
bbox = np.intp(detections.data.get(ORIENTED_BOX_COORDINATES)[detection_idx])
color = resolve_color(
color=self.color,
detections=detections,
@@ -212,7 +303,7 @@ class MaskAnnotator(BaseAnnotator):
self.opacity = opacity
self.color_lookup: ColorLookup = color_lookup
@scene_to_annotator_img_type
@ensure_cv2_image_for_annotation
def annotate(
self,
scene: ImageType,
@@ -268,8 +359,10 @@ class MaskAnnotator(BaseAnnotator):
mask = detections.mask[detection_idx]
colored_mask[mask] = color.as_bgr()
scene = cv2.addWeighted(colored_mask, self.opacity, scene, 1 - self.opacity, 0)
return scene.astype(np.uint8)
cv2.addWeighted(
colored_mask, self.opacity, scene, 1 - self.opacity, 0, dst=scene
)
return scene
class PolygonAnnotator(BaseAnnotator):
@@ -299,7 +392,7 @@ class PolygonAnnotator(BaseAnnotator):
self.thickness: int = thickness
self.color_lookup: ColorLookup = color_lookup
@scene_to_annotator_img_type
@ensure_cv2_image_for_annotation
def annotate(
self,
scene: ImageType,
@@ -385,7 +478,7 @@ class ColorAnnotator(BaseAnnotator):
self.color_lookup: ColorLookup = color_lookup
self.opacity = opacity
@scene_to_annotator_img_type
@ensure_cv2_image_for_annotation
def annotate(
self,
scene: ImageType,
@@ -424,7 +517,7 @@ class ColorAnnotator(BaseAnnotator):
![box-mask-annotator-example](https://media.roboflow.com/
supervision-annotator-examples/box-mask-annotator-example-purple.png)
"""
mask_image = scene.copy()
scene_with_boxes = scene.copy()
for detection_idx in range(len(detections)):
x1, y1, x2, y2 = detections.xyxy[detection_idx].astype(int)
color = resolve_color(
@@ -436,14 +529,15 @@ class ColorAnnotator(BaseAnnotator):
else custom_color_lookup,
)
cv2.rectangle(
img=scene,
img=scene_with_boxes,
pt1=(x1, y1),
pt2=(x2, y2),
color=color.as_bgr(),
thickness=-1,
)
scene = cv2.addWeighted(
scene, self.opacity, mask_image, 1 - self.opacity, gamma=0
cv2.addWeighted(
scene_with_boxes, self.opacity, scene, 1 - self.opacity, gamma=0, dst=scene
)
return scene
@@ -479,7 +573,7 @@ class HaloAnnotator(BaseAnnotator):
self.color_lookup: ColorLookup = color_lookup
self.kernel_size: int = kernel_size
@scene_to_annotator_img_type
@ensure_cv2_image_for_annotation
def annotate(
self,
scene: ImageType,
@@ -544,7 +638,8 @@ class HaloAnnotator(BaseAnnotator):
gray = cv2.cvtColor(colored_mask, cv2.COLOR_BGR2GRAY)
alpha = self.opacity * gray / gray.max()
alpha_mask = alpha[:, :, np.newaxis]
scene = np.uint8(scene * (1 - alpha_mask) + colored_mask * self.opacity)
blended_scene = np.uint8(scene * (1 - alpha_mask) + colored_mask * self.opacity)
np.copyto(scene, blended_scene)
return scene
@@ -577,7 +672,7 @@ class EllipseAnnotator(BaseAnnotator):
self.end_angle: int = end_angle
self.color_lookup: ColorLookup = color_lookup
@scene_to_annotator_img_type
@ensure_cv2_image_for_annotation
def annotate(
self,
scene: ImageType,
@@ -668,7 +763,7 @@ class BoxCornerAnnotator(BaseAnnotator):
self.corner_length: int = corner_length
self.color_lookup: ColorLookup = color_lookup
@scene_to_annotator_img_type
@ensure_cv2_image_for_annotation
def annotate(
self,
scene: ImageType,
@@ -756,7 +851,7 @@ class CircleAnnotator(BaseAnnotator):
self.thickness: int = thickness
self.color_lookup: ColorLookup = color_lookup
@scene_to_annotator_img_type
@ensure_cv2_image_for_annotation
def annotate(
self,
scene: ImageType,
@@ -831,6 +926,7 @@ class DotAnnotator(BaseAnnotator):
radius: int = 4,
position: Position = Position.CENTER,
color_lookup: ColorLookup = ColorLookup.CLASS,
outline_thickness: int = 0,
):
"""
Args:
@@ -840,13 +936,15 @@ class DotAnnotator(BaseAnnotator):
position (Position): The anchor position for placing the dot.
color_lookup (ColorLookup): Strategy for mapping colors to annotations.
Options are `INDEX`, `CLASS`, `TRACK`.
outline_thickness (int): Thickness of the outline of the dot.
"""
self.color: Union[Color, ColorPalette] = color
self.radius: int = radius
self.position: Position = position
self.color_lookup: ColorLookup = color_lookup
self.outline_thickness = outline_thickness
@scene_to_annotator_img_type
@ensure_cv2_image_for_annotation
def annotate(
self,
scene: ImageType,
@@ -896,11 +994,16 @@ class DotAnnotator(BaseAnnotator):
else custom_color_lookup,
)
center = (int(xy[detection_idx, 0]), int(xy[detection_idx, 1]))
cv2.circle(scene, center, self.radius, color.as_bgr(), -1)
if self.outline_thickness:
cv2.circle(
scene, center, self.radius, (0, 0, 0), self.outline_thickness
)
return scene
class LabelAnnotator:
class LabelAnnotator(BaseAnnotator):
"""
A class for annotating labels on an image using provided detections.
"""
@@ -914,6 +1017,7 @@ class LabelAnnotator:
text_padding: int = 10,
text_position: Position = Position.TOP_LEFT,
color_lookup: ColorLookup = ColorLookup.CLASS,
border_radius: int = 0,
):
"""
Args:
@@ -927,7 +1031,10 @@ class LabelAnnotator:
Possible values are defined in the `Position` enum.
color_lookup (str): Strategy for mapping colors to annotations.
Options are `INDEX`, `CLASS`, `TRACK`.
border_radius (int): The radius to apply round edges. If the selected
value is higher than the lower dimension, width or height, is clipped.
"""
self.border_radius: int = border_radius
self.color: Union[Color, ColorPalette] = color
self.text_color: Color = text_color
self.text_scale: float = text_scale
@@ -936,65 +1043,12 @@ class LabelAnnotator:
self.text_anchor: Position = text_position
self.color_lookup: ColorLookup = color_lookup
@staticmethod
def resolve_text_background_xyxy(
center_coordinates: Tuple[int, int],
text_wh: Tuple[int, int],
position: Position,
) -> Tuple[int, int, int, int]:
center_x, center_y = center_coordinates
text_w, text_h = text_wh
if position == Position.TOP_LEFT:
return center_x, center_y - text_h, center_x + text_w, center_y
elif position == Position.TOP_RIGHT:
return center_x - text_w, center_y - text_h, center_x, center_y
elif position == Position.TOP_CENTER:
return (
center_x - text_w // 2,
center_y - text_h,
center_x + text_w // 2,
center_y,
)
elif position == Position.CENTER or position == Position.CENTER_OF_MASS:
return (
center_x - text_w // 2,
center_y - text_h // 2,
center_x + text_w // 2,
center_y + text_h // 2,
)
elif position == Position.BOTTOM_LEFT:
return center_x, center_y, center_x + text_w, center_y + text_h
elif position == Position.BOTTOM_RIGHT:
return center_x - text_w, center_y, center_x, center_y + text_h
elif position == Position.BOTTOM_CENTER:
return (
center_x - text_w // 2,
center_y,
center_x + text_w // 2,
center_y + text_h,
)
elif position == Position.CENTER_LEFT:
return (
center_x - text_w,
center_y - text_h // 2,
center_x,
center_y + text_h // 2,
)
elif position == Position.CENTER_RIGHT:
return (
center_x,
center_y - text_h // 2,
center_x + text_w,
center_y + text_h // 2,
)
@scene_to_annotator_img_type
@ensure_cv2_image_for_annotation
def annotate(
self,
scene: ImageType,
detections: Detections,
labels: List[str] = None,
labels: Optional[List[str]] = None,
custom_color_lookup: Optional[np.ndarray] = None,
) -> ImageType:
"""
@@ -1005,7 +1059,7 @@ class LabelAnnotator:
`ImageType` is a flexible type, accepting either `numpy.ndarray`
or `PIL.Image.Image`.
detections (Detections): Object detections to annotate.
labels (List[str]): Optional. Custom labels for each detection.
labels (Optional[List[str]]): Custom labels for each detection.
custom_color_lookup (Optional[np.ndarray]): Custom color lookup array.
Allows to override the default color mapping strategy.
@@ -1020,10 +1074,17 @@ class LabelAnnotator:
image = ...
detections = sv.Detections(...)
labels = [
f"{class_name} {confidence:.2f}"
for class_name, confidence
in zip(detections['class_name'], detections.confidence)
]
label_annotator = sv.LabelAnnotator(text_position=sv.Position.CENTER)
annotated_frame = label_annotator.annotate(
scene=image.copy(),
detections=detections
detections=detections,
labels=labels
)
```
@@ -1036,12 +1097,9 @@ class LabelAnnotator:
).astype(int)
if labels is not None and len(labels) != len(detections):
raise ValueError(
f"The number of labels provided ({len(labels)}) does not match the "
f"number of detections ({len(detections)}). Each detection should have "
f"a corresponding label. This discrepancy can occur if the labels and "
f"detections are not aligned or if an incorrect number of labels has "
f"been provided. Please ensure that the labels array has the same "
f"length as the Detections object."
f"The number of labels ({len(labels)}) does not match the "
f"number of detections ({len(detections)}). Each detection "
f"should have exactly 1 label."
)
for detection_idx, center_coordinates in enumerate(anchors_coordinates):
@@ -1049,9 +1107,11 @@ class LabelAnnotator:
color=self.color,
detections=detections,
detection_idx=detection_idx,
color_lookup=self.color_lookup
if custom_color_lookup is None
else custom_color_lookup,
color_lookup=(
self.color_lookup
if custom_color_lookup is None
else custom_color_lookup
),
)
if labels is not None:
@@ -1071,7 +1131,7 @@ class LabelAnnotator:
)[0]
text_w_padded = text_w + 2 * self.text_padding
text_h_padded = text_h + 2 * self.text_padding
text_background_xyxy = self.resolve_text_background_xyxy(
text_background_xyxy = resolve_text_background_xyxy(
center_coordinates=tuple(center_coordinates),
text_wh=(text_w_padded, text_h_padded),
position=self.text_anchor,
@@ -1080,12 +1140,11 @@ class LabelAnnotator:
text_x = text_background_xyxy[0] + self.text_padding
text_y = text_background_xyxy[1] + self.text_padding + text_h
cv2.rectangle(
img=scene,
pt1=(text_background_xyxy[0], text_background_xyxy[1]),
pt2=(text_background_xyxy[2], text_background_xyxy[3]),
self.draw_rounded_rectangle(
scene=scene,
xyxy=text_background_xyxy,
color=color.as_bgr(),
thickness=cv2.FILLED,
border_radius=self.border_radius,
)
cv2.putText(
img=scene,
@@ -1099,6 +1158,215 @@ class LabelAnnotator:
)
return scene
@staticmethod
def draw_rounded_rectangle(
scene: np.ndarray,
xyxy: Tuple[int, int, int, int],
color: Tuple[int, int, int],
border_radius: int,
) -> np.ndarray:
x1, y1, x2, y2 = xyxy
width = x2 - x1
height = y2 - y1
border_radius = min(border_radius, min(width, height) // 2)
rectangle_coordinates = [
((x1 + border_radius, y1), (x2 - border_radius, y2)),
((x1, y1 + border_radius), (x2, y2 - border_radius)),
]
circle_centers = [
(x1 + border_radius, y1 + border_radius),
(x2 - border_radius, y1 + border_radius),
(x1 + border_radius, y2 - border_radius),
(x2 - border_radius, y2 - border_radius),
]
for coordinates in rectangle_coordinates:
cv2.rectangle(
img=scene,
pt1=coordinates[0],
pt2=coordinates[1],
color=color,
thickness=-1,
)
for center in circle_centers:
cv2.circle(
img=scene,
center=center,
radius=border_radius,
color=color,
thickness=-1,
)
return scene
class RichLabelAnnotator(BaseAnnotator):
"""
A class for annotating labels on an image using provided detections,
with support for Unicode characters by using a custom font.
"""
def __init__(
self,
color: Union[Color, ColorPalette] = ColorPalette.DEFAULT,
text_color: Color = Color.WHITE,
font_path: Optional[str] = None,
font_size: int = 10,
text_padding: int = 10,
text_position: Position = Position.TOP_LEFT,
color_lookup: ColorLookup = ColorLookup.CLASS,
border_radius: int = 0,
):
"""
Args:
color (Union[Color, ColorPalette]): The color or color palette to use for
annotating the text background.
text_color (Color): The color to use for the text.
font_path (Optional[str]): Path to the font file (e.g., ".ttf" or ".otf")
to use for rendering text. If `None`, the default PIL font will be used.
font_size (int): Font size for the text.
text_padding (int): Padding around the text within its background box.
text_position (Position): Position of the text relative to the detection.
Possible values are defined in the `Position` enum.
color_lookup (ColorLookup): Strategy for mapping colors to annotations.
Options are `INDEX`, `CLASS`, `TRACK`.
border_radius (int): The radius to apply round edges. If the selected
value is higher than the lower dimension, width or height, is clipped.
"""
self.color = color
self.text_color = text_color
self.text_padding = text_padding
self.text_anchor = text_position
self.color_lookup = color_lookup
self.border_radius = border_radius
if font_path is not None:
try:
self.font = ImageFont.truetype(font_path, font_size)
except OSError:
print(f"Font path '{font_path}' not found. Using PIL's default font.")
self.font = self._load_default_font(font_size)
else:
self.font = self._load_default_font(font_size)
@ensure_pil_image_for_annotation
def annotate(
self,
scene: ImageType,
detections: Detections,
labels: Optional[List[str]] = None,
custom_color_lookup: Optional[np.ndarray] = None,
) -> ImageType:
"""
Annotates the given scene with labels based on the provided
detections, with support for Unicode characters.
Args:
scene (ImageType): The image where labels will be drawn.
`ImageType` is a flexible type, accepting either `numpy.ndarray`
or `PIL.Image.Image`.
detections (Detections): Object detections to annotate.
labels (Optional[List[str]]): Custom labels for each detection.
custom_color_lookup (Optional[np.ndarray]): Custom color lookup array.
Allows to override the default color mapping strategy.
Returns:
The annotated image, matching the type of `scene` (`numpy.ndarray`
or `PIL.Image.Image`)
Example:
```python
import supervision as sv
image = ...
detections = sv.Detections(...)
labels = [
f"{class_name} {confidence:.2f}"
for class_name, confidence
in zip(detections['class_name'], detections.confidence)
]
rich_label_annotator = sv.RichLabelAnnotator(font_path="path/to/font.ttf")
annotated_frame = label_annotator.annotate(
scene=image.copy(),
detections=detections,
labels=labels
)
```
"""
draw = ImageDraw.Draw(scene)
anchors_coordinates = detections.get_anchors_coordinates(
anchor=self.text_anchor
).astype(int)
if labels is not None and len(labels) != len(detections):
raise ValueError(
f"The number of labels provided ({len(labels)}) does not match the "
f"number of detections ({len(detections)}). Each detection should have "
f"a corresponding label."
)
for detection_idx, center_coordinates in enumerate(anchors_coordinates):
color = resolve_color(
color=self.color,
detections=detections,
detection_idx=detection_idx,
color_lookup=(
self.color_lookup
if custom_color_lookup is None
else custom_color_lookup
),
)
if labels is not None:
text = labels[detection_idx]
elif detections[CLASS_NAME_DATA_FIELD] is not None:
text = detections[CLASS_NAME_DATA_FIELD][detection_idx]
elif detections.class_id is not None:
text = str(detections.class_id[detection_idx])
else:
text = str(detection_idx)
left, top, right, bottom = draw.textbbox((0, 0), text, font=self.font)
text_width = right - left
text_height = bottom - top
text_w_padded = text_width + 2 * self.text_padding
text_h_padded = text_height + 2 * self.text_padding
text_background_xyxy = resolve_text_background_xyxy(
center_coordinates=tuple(center_coordinates),
text_wh=(text_w_padded, text_h_padded),
position=self.text_anchor,
)
text_x = text_background_xyxy[0] + self.text_padding - left
text_y = text_background_xyxy[1] + self.text_padding - top
draw.rounded_rectangle(
text_background_xyxy,
radius=self.border_radius,
fill=color.as_rgb(),
outline=None,
)
draw.text(
xy=(text_x, text_y),
text=text,
font=self.font,
fill=self.text_color.as_rgb(),
)
return scene
@staticmethod
def _load_default_font(size):
"""
PIL either loads a font that accepts a size (e.g. on my machine)
or raises an error saying `load_default` does not accept arguments
(e.g. in Colab).
"""
try:
font = ImageFont.load_default(size)
except TypeError:
font = ImageFont.load_default()
return font
class BlurAnnotator(BaseAnnotator):
"""
@@ -1112,7 +1380,7 @@ class BlurAnnotator(BaseAnnotator):
"""
self.kernel_size: int = kernel_size
@scene_to_annotator_img_type
@ensure_cv2_image_for_annotation
def annotate(
self,
scene: ImageType,
@@ -1161,7 +1429,7 @@ class BlurAnnotator(BaseAnnotator):
return scene
class TraceAnnotator:
class TraceAnnotator(BaseAnnotator):
"""
A class for drawing trace paths on an image based on detection coordinates.
@@ -1197,7 +1465,7 @@ class TraceAnnotator:
self.thickness = thickness
self.color_lookup: ColorLookup = color_lookup
@scene_to_annotator_img_type
@ensure_cv2_image_for_annotation
def annotate(
self,
scene: ImageType,
@@ -1270,7 +1538,7 @@ class TraceAnnotator:
return scene
class HeatMapAnnotator:
class HeatMapAnnotator(BaseAnnotator):
"""
A class for drawing heatmaps on an image based on provided detections.
Heat accumulates over time and is drawn as a semi-transparent overlay
@@ -1304,7 +1572,7 @@ class HeatMapAnnotator:
self.top_hue = top_hue
self.low_hue = low_hue
@scene_to_annotator_img_type
@ensure_cv2_image_for_annotation
def annotate(self, scene: ImageType, detections: Detections) -> ImageType:
"""
Annotates the scene with a heatmap based on the provided detections.
@@ -1380,7 +1648,7 @@ class PixelateAnnotator(BaseAnnotator):
"""
self.pixel_size: int = pixel_size
@scene_to_annotator_img_type
@ensure_cv2_image_for_annotation
def annotate(
self,
scene: ImageType,
@@ -1451,6 +1719,7 @@ class TriangleAnnotator(BaseAnnotator):
height: int = 10,
position: Position = Position.TOP_CENTER,
color_lookup: ColorLookup = ColorLookup.CLASS,
outline_thickness: int = 0,
):
"""
Args:
@@ -1461,14 +1730,16 @@ class TriangleAnnotator(BaseAnnotator):
position (Position): The anchor position for placing the triangle.
color_lookup (ColorLookup): Strategy for mapping colors to annotations.
Options are `INDEX`, `CLASS`, `TRACK`.
outline_thickness (int): Thickness of the outline of the triangle.
"""
self.color: Union[Color, ColorPalette] = color
self.base: int = base
self.height: int = height
self.position: Position = position
self.color_lookup: ColorLookup = color_lookup
self.outline_thickness: int = outline_thickness
@scene_to_annotator_img_type
@ensure_cv2_image_for_annotation
def annotate(
self,
scene: ImageType,
@@ -1528,7 +1799,10 @@ class TriangleAnnotator(BaseAnnotator):
)
cv2.fillPoly(scene, [vertices], color.as_bgr())
if self.outline_thickness:
cv2.polylines(
scene, [vertices], True, (0, 0, 0), thickness=self.outline_thickness
)
return scene
@@ -1564,7 +1838,7 @@ class RoundBoxAnnotator(BaseAnnotator):
raise ValueError("roundness attribute must be float between (0, 1.0]")
self.roundness: float = roundness
@scene_to_annotator_img_type
@ensure_cv2_image_for_annotation
def annotate(
self,
scene: ImageType,
@@ -1701,7 +1975,7 @@ class PercentageBarAnnotator(BaseAnnotator):
if border_thickness is None:
self.border_thickness = int(0.15 * self.height)
@scene_to_annotator_img_type
@ensure_cv2_image_for_annotation
def annotate(
self,
scene: ImageType,
@@ -1847,7 +2121,14 @@ class CropAnnotator(BaseAnnotator):
A class for drawing scaled up crops of detections on the scene.
"""
def __init__(self, position: Position = Position.TOP_CENTER, scale_factor: int = 2):
def __init__(
self,
position: Position = Position.TOP_CENTER,
scale_factor: int = 2,
border_color: Union[Color, ColorPalette] = ColorPalette.DEFAULT,
border_thickness: int = 2,
border_color_lookup: ColorLookup = ColorLookup.CLASS,
):
"""
Args:
position (Position): The anchor position for placing the cropped and scaled
@@ -1855,16 +2136,25 @@ class CropAnnotator(BaseAnnotator):
scale_factor (int): The factor by which to scale the cropped image part. A
factor of 2, for example, would double the size of the cropped area,
allowing for a closer view of the detection.
border_color (Union[Color, ColorPalette]): The color or color palette to
use for annotating border around the cropped area.
border_thickness (int): The thickness of the border around the cropped area.
border_color_lookup (ColorLookup): Strategy for mapping colors to
annotations. Options are `INDEX`, `CLASS`, `TRACK`.
"""
self.position: Position = position
self.scale_factor: int = scale_factor
self.border_color: Union[Color, ColorPalette] = border_color
self.border_thickness: int = border_thickness
self.border_color_lookup: ColorLookup = border_color_lookup
@scene_to_annotator_img_type
@ensure_cv2_image_for_annotation
def annotate(
self,
scene: np.ndarray,
scene: ImageType,
detections: Detections,
) -> np.ndarray:
custom_color_lookup: Optional[np.ndarray] = None,
) -> ImageType:
"""
Annotates the provided scene with scaled and cropped parts of the image based
on the provided detections. Each detection is cropped from the original scene
@@ -1873,8 +2163,12 @@ class CropAnnotator(BaseAnnotator):
Args:
scene (np.ndarray): The image where cropped detection will be placed.
scene (ImageType): The image where cropped detection will be placed.
`ImageType` is a flexible type, accepting either `numpy.ndarray`
or `PIL.Image.Image`.
detections (Detections): Object detections to annotate.
custom_color_lookup (Optional[np.ndarray]): Custom color lookup array.
Allows to override the default color mapping strategy.
Returns:
The annotated image.
@@ -1897,41 +2191,71 @@ 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)
for resized_crop, anchor in zip(resized_crops, anchors):
for idx, (resized_crop, anchor) in enumerate(zip(resized_crops, anchors)):
crop_wh = resized_crop.shape[1], resized_crop.shape[0]
crop_anchor = self.calculate_crop_coordinates(
(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=crop_anchor)
scene = overlay_image(image=scene, overlay=resized_crop, anchor=(x1, y1))
color = resolve_color(
color=self.border_color,
detections=detections,
detection_idx=idx,
color_lookup=self.border_color_lookup
if custom_color_lookup is None
else custom_color_lookup,
)
cv2.rectangle(
img=scene,
pt1=(x1, y1),
pt2=(x2, y2),
color=color.as_bgr(),
thickness=self.border_thickness,
)
return scene
@staticmethod
def calculate_crop_coordinates(
anchor: Tuple[int, int], crop_wh: Tuple[int, int], position: Position
) -> Tuple[int, int]:
) -> Tuple[Tuple[int, int], Tuple[int, int]]:
anchor_x, anchor_y = anchor
width, height = crop_wh
if position == Position.TOP_LEFT:
return anchor_x - width, anchor_y - height
return (anchor_x - width, anchor_y - height), (anchor_x, anchor_y)
elif position == Position.TOP_CENTER:
return anchor_x - width // 2, anchor_y - height
return (
(anchor_x - width // 2, anchor_y - height),
(anchor_x + width // 2, anchor_y),
)
elif position == Position.TOP_RIGHT:
return anchor_x, anchor_y - height
return (anchor_x, anchor_y - height), (anchor_x + width, anchor_y)
elif position == Position.CENTER_LEFT:
return anchor_x - width, anchor_y - height // 2
return (
(anchor_x - width, anchor_y - height // 2),
(anchor_x, anchor_y + height // 2),
)
elif position == Position.CENTER or position == Position.CENTER_OF_MASS:
return anchor_x - width // 2, anchor_y - height // 2
return (
(anchor_x - width // 2, anchor_y - height // 2),
(anchor_x + width // 2, anchor_y + height // 2),
)
elif position == Position.CENTER_RIGHT:
return anchor_x, anchor_y - height // 2
return (
(anchor_x, anchor_y - height // 2),
(anchor_x + width, anchor_y + height // 2),
)
elif position == Position.BOTTOM_LEFT:
return anchor_x - width, anchor_y
return (anchor_x - width, anchor_y), (anchor_x, anchor_y + height)
elif position == Position.BOTTOM_CENTER:
return anchor_x - width // 2, anchor_y
return (
(anchor_x - width // 2, anchor_y),
(anchor_x + width // 2, anchor_y + height),
)
elif position == Position.BOTTOM_RIGHT:
return anchor_x, anchor_y
return (anchor_x, anchor_y), (anchor_x + width, anchor_y + height)
+58 -39
View File
@@ -1,12 +1,8 @@
from enum import Enum
from functools import wraps
from typing import Optional, Union
from typing import Optional, Tuple, 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
@@ -38,14 +34,14 @@ def resolve_color_idx(
) -> int:
if detection_idx >= len(detections):
raise ValueError(
f"Detection index {detection_idx}"
f"Detection index {detection_idx} "
f"is out of bounds for detections of length {len(detections)}"
)
if isinstance(color_lookup, np.ndarray):
if len(color_lookup) != len(detections):
raise ValueError(
f"Length of color lookup {len(color_lookup)}"
f"Length of color lookup {len(color_lookup)} "
f"does not match length of detections {len(detections)}"
)
return color_lookup[detection_idx]
@@ -54,19 +50,72 @@ def resolve_color_idx(
elif color_lookup == ColorLookup.CLASS:
if detections.class_id is None:
raise ValueError(
"Could not resolve color by class because"
"Could not resolve color by class because "
"Detections do not have class_id"
)
return detections.class_id[detection_idx]
elif color_lookup == ColorLookup.TRACK:
if detections.tracker_id is None:
raise ValueError(
"Could not resolve color by track because"
"Could not resolve color by track because "
"Detections do not have tracker_id"
)
return detections.tracker_id[detection_idx]
def resolve_text_background_xyxy(
center_coordinates: Tuple[int, int],
text_wh: Tuple[int, int],
position: Position,
) -> Tuple[int, int, int, int]:
center_x, center_y = center_coordinates
text_w, text_h = text_wh
if position == Position.TOP_LEFT:
return center_x, center_y - text_h, center_x + text_w, center_y
elif position == Position.TOP_RIGHT:
return center_x - text_w, center_y - text_h, center_x, center_y
elif position == Position.TOP_CENTER:
return (
center_x - text_w // 2,
center_y - text_h,
center_x + text_w // 2,
center_y,
)
elif position == Position.CENTER or position == Position.CENTER_OF_MASS:
return (
center_x - text_w // 2,
center_y - text_h // 2,
center_x + text_w // 2,
center_y + text_h // 2,
)
elif position == Position.BOTTOM_LEFT:
return center_x, center_y, center_x + text_w, center_y + text_h
elif position == Position.BOTTOM_RIGHT:
return center_x - text_w, center_y, center_x, center_y + text_h
elif position == Position.BOTTOM_CENTER:
return (
center_x - text_w // 2,
center_y,
center_x + text_w // 2,
center_y + text_h,
)
elif position == Position.CENTER_LEFT:
return (
center_x - text_w,
center_y - text_h // 2,
center_x,
center_y + text_h // 2,
)
elif position == Position.CENTER_RIGHT:
return (
center_x,
center_y - text_h // 2,
center_x + text_w,
center_y + text_h // 2,
)
def get_color_by_index(color: Union[Color, ColorPalette], idx: int) -> Color:
if isinstance(color, ColorPalette):
return color.by_idx(idx)
@@ -123,33 +172,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",
),
}
+384 -149
View File
@@ -3,8 +3,9 @@ from __future__ import annotations
import os
from abc import ABC, abstractmethod
from dataclasses import dataclass
from itertools import chain
from pathlib import Path
from typing import Dict, Iterator, List, Optional, Tuple
from typing import Dict, Iterator, List, Optional, Tuple, Union
import cv2
import numpy as np
@@ -31,9 +32,10 @@ from supervision.dataset.utils import (
train_test_split,
)
from supervision.detection.core import Detections
from supervision.utils.internal import deprecated, warn_deprecated
from supervision.utils.iterables import find_duplicates
@dataclass
class BaseDataset(ABC):
@abstractmethod
def __len__(self) -> int:
@@ -46,30 +48,95 @@ class BaseDataset(ABC):
pass
@dataclass
class DetectionDataset(BaseDataset):
"""
Dataclass containing information about object detection dataset.
Contains information about a detection dataset. Handles lazy image loading
and annotation retrieval, dataset splitting, conversions into multiple
formats.
Attributes:
classes (List[str]): List containing dataset class names.
images (Dict[str, np.ndarray]): Dictionary mapping image name to image.
images (Union[List[str], Dict[str, np.ndarray]]):
Accepts a list of image paths, or dictionaries of loaded cv2 images
with paths as keys. If you pass a list of paths, the dataset will
lazily load images on demand, which is much more memory-efficient.
annotations (Dict[str, Detections]): Dictionary mapping
image name to annotations.
image path to annotations. The dictionary keys match
match the keys in `images` or entries in the list of
image paths.
"""
classes: List[str]
images: Dict[str, np.ndarray]
annotations: Dict[str, Detections]
def __init__(
self,
classes: List[str],
images: Union[List[str], Dict[str, np.ndarray]],
annotations: Dict[str, Detections],
) -> None:
self.classes = classes
if set(images) != set(annotations):
raise ValueError(
"The keys of the images and annotations dictionaries must match."
)
self.annotations = annotations
# Eliminate duplicates while preserving order
self.image_paths = list(dict.fromkeys(images))
self._images_in_memory: Dict[str, np.ndarray] = {}
if isinstance(images, dict):
self._images_in_memory = images
warn_deprecated(
"Passing a `Dict[str, np.ndarray]` into `DetectionDataset` is "
"deprecated and will be removed in `supervision-0.26.0`. Use "
"a list of paths `List[str]` instead."
)
# TODO: when supervision-0.26.0 is released, and Dict[str, np.ndarray]
# for images is no longer supported, also simplify the rest of
# the code. E.g. list(images) is no longer needed, and merge can
# be simplified.
@property
@deprecated(
"`DetectionDataset.images` property is deprecated and will be removed in "
"`supervision-0.26.0`. Iterate with `for path, image, annotation in dataset:` "
"instead."
)
def images(self) -> Dict[str, np.ndarray]:
"""
Load all images to memory and return them as a dictionary.
!!! warning
Only use this when you need all images at once.
It is much more memory-efficient to initialize dataset with
image paths and use `for path, image, annotation in dataset:`.
"""
if self._images_in_memory:
return self._images_in_memory
images = {image_path: cv2.imread(image_path) for image_path in self.image_paths}
return images
def _get_image(self, image_path: str) -> np.ndarray:
"""Assumes that image is in dataset"""
if self._images_in_memory:
return self._images_in_memory[image_path]
return cv2.imread(image_path)
def __len__(self) -> int:
"""
Return the number of images in the dataset.
return len(self._images_in_memory) or len(self.image_paths)
Returns:
int: The number of images.
def __getitem__(self, i: int) -> Tuple[str, np.ndarray, Detections]:
"""
return len(self.images)
Returns:
Tuple[str, np.ndarray, Detections]: The image path, image data,
and its corresponding annotation at index i.
"""
image_path = self.image_paths[i]
image = self._get_image(image_path)
annotation = self.annotations[image_path]
return image_path, image, annotation
def __iter__(self) -> Iterator[Tuple[str, np.ndarray, Detections]]:
"""
@@ -77,25 +144,33 @@ class DetectionDataset(BaseDataset):
Yields:
Iterator[Tuple[str, np.ndarray, Detections]]:
An iterator that yields tuples containing the image name,
An iterator that yields tuples containing the image path,
the image data, and its corresponding annotation.
"""
for image_name, image in self.images.items():
yield image_name, image, self.annotations.get(image_name, None)
for i in range(len(self)):
image_path, image, annotation = self[i]
yield image_path, image, annotation
def __eq__(self, other):
def __eq__(self, other) -> bool:
if not isinstance(other, DetectionDataset):
return False
if set(self.classes) != set(other.classes):
return False
for key in self.images:
if not np.array_equal(self.images[key], other.images[key]):
return False
if not self.annotations[key] == other.annotations[key]:
if self.image_paths != other.image_paths:
return False
if self._images_in_memory or other._images_in_memory:
if not np.array_equal(
list(self._images_in_memory.values()),
list(other._images_in_memory.values()),
):
return False
if self.annotations != other.annotations:
return False
return True
def split(
@@ -116,38 +191,140 @@ class DetectionDataset(BaseDataset):
Tuple[DetectionDataset, DetectionDataset]: A tuple containing
the training and testing datasets.
Example:
Examples:
```python
import supervision as sv
ds = sv.DetectionDataset(...)
train_ds, test_ds = ds.split(split_ratio=0.7,
random_state=42, shuffle=True)
train_ds, test_ds = ds.split(split_ratio=0.7, random_state=42, shuffle=True)
len(train_ds), len(test_ds)
# (700, 300)
```
"""
image_names = list(self.images.keys())
train_names, test_names = train_test_split(
data=image_names,
train_paths, test_paths = train_test_split(
data=self.image_paths,
train_ratio=split_ratio,
random_state=random_state,
shuffle=shuffle,
)
train_input: Union[List[str], Dict[str, np.ndarray]]
test_input: Union[List[str], Dict[str, np.ndarray]]
if self._images_in_memory:
train_input = {path: self._images_in_memory[path] for path in train_paths}
test_input = {path: self._images_in_memory[path] for path in test_paths}
else:
train_input = train_paths
test_input = test_paths
train_annotations = {path: self.annotations[path] for path in train_paths}
test_annotations = {path: self.annotations[path] for path in test_paths}
train_dataset = DetectionDataset(
classes=self.classes,
images={name: self.images[name] for name in train_names},
annotations={name: self.annotations[name] for name in train_names},
images=train_input,
annotations=train_annotations,
)
test_dataset = DetectionDataset(
classes=self.classes,
images={name: self.images[name] for name in test_names},
annotations={name: self.annotations[name] for name in test_names},
images=test_input,
annotations=test_annotations,
)
return train_dataset, test_dataset
@classmethod
def merge(cls, dataset_list: List[DetectionDataset]) -> DetectionDataset:
"""
Merge a list of `DetectionDataset` objects into a single
`DetectionDataset` object.
This method takes a list of `DetectionDataset` objects and combines
their respective fields (`classes`, `images`,
`annotations`) into a single `DetectionDataset` object.
Args:
dataset_list (List[DetectionDataset]): A list of `DetectionDataset`
objects to merge.
Returns:
(DetectionDataset): A single `DetectionDataset` object containing
the merged data from the input list.
Examples:
```python
import supervision as sv
ds_1 = sv.DetectionDataset(...)
len(ds_1)
# 100
ds_1.classes
# ['dog', 'person']
ds_2 = sv.DetectionDataset(...)
len(ds_2)
# 200
ds_2.classes
# ['cat']
ds_merged = sv.DetectionDataset.merge([ds_1, ds_2])
len(ds_merged)
# 300
ds_merged.classes
# ['cat', 'dog', 'person']
```
"""
def is_in_memory(dataset: DetectionDataset) -> bool:
return len(dataset._images_in_memory) > 0 or len(dataset.image_paths) == 0
def is_lazy(dataset: DetectionDataset) -> bool:
return len(dataset._images_in_memory) == 0
all_in_memory = all([is_in_memory(dataset) for dataset in dataset_list])
all_lazy = all([is_lazy(dataset) for dataset in dataset_list])
if not all_in_memory and not all_lazy:
raise ValueError(
"Merging lazy and in-memory DetectionDatasets is not supported."
)
images_in_memory = {}
for dataset in dataset_list:
images_in_memory.update(dataset._images_in_memory)
image_paths = list(
chain.from_iterable(dataset.image_paths for dataset in dataset_list)
)
image_paths_unique = list(dict.fromkeys(image_paths))
if len(image_paths) != len(image_paths_unique):
duplicates = find_duplicates(image_paths)
raise ValueError(
f"Image paths {duplicates} are not unique across datasets."
)
image_paths = image_paths_unique
classes = merge_class_lists(
class_lists=[dataset.classes for dataset in dataset_list]
)
annotations = {}
for dataset in dataset_list:
annotations.update(dataset.annotations)
for dataset in dataset_list:
class_index_mapping = build_class_index_mapping(
source_classes=dataset.classes, target_classes=classes
)
for image_path in dataset.image_paths:
annotations[image_path] = map_detections_class_id(
source_to_target_mapping=class_index_mapping,
detections=annotations[image_path],
)
return cls(
classes=classes,
images=images_in_memory or image_paths,
annotations=annotations,
)
def as_pascal_voc(
self,
images_directory_path: Optional[str] = None,
@@ -181,25 +358,22 @@ class DetectionDataset(BaseDataset):
"""
if images_directory_path:
save_dataset_images(
images_directory_path=images_directory_path, images=self.images
dataset=self,
images_directory_path=images_directory_path,
)
if annotations_directory_path:
Path(annotations_directory_path).mkdir(parents=True, exist_ok=True)
for image_path, image in self.images.items():
detections = self.annotations[image_path]
if annotations_directory_path:
for image_path, image, annotations in self:
annotation_name = Path(image_path).stem
annotations_path = os.path.join(
annotations_directory_path, f"{annotation_name}.xml"
)
image_name = Path(image_path).name
pascal_voc_xml = detections_to_pascal_voc(
detections=detections,
detections=annotations,
classes=self.classes,
filename=image_name,
image_shape=image.shape,
image_shape=image.shape, # type: ignore
min_image_area_percentage=min_image_area_percentage,
max_image_area_percentage=max_image_area_percentage,
approximation_percentage=approximation_percentage,
@@ -229,7 +403,7 @@ class DetectionDataset(BaseDataset):
DetectionDataset: A DetectionDataset instance containing
the loaded images and annotations.
Example:
Examples:
```python
import roboflow
from roboflow import Roboflow
@@ -252,13 +426,15 @@ class DetectionDataset(BaseDataset):
```
"""
classes, images, annotations = load_pascal_voc_annotations(
classes, image_paths, annotations = load_pascal_voc_annotations(
images_directory_path=images_directory_path,
annotations_directory_path=annotations_directory_path,
force_masks=force_masks,
)
return DetectionDataset(classes=classes, images=images, annotations=annotations)
return DetectionDataset(
classes=classes, images=image_paths, annotations=annotations
)
@classmethod
def from_yolo(
@@ -267,6 +443,7 @@ class DetectionDataset(BaseDataset):
annotations_directory_path: str,
data_yaml_path: str,
force_masks: bool = False,
is_obb: bool = False,
) -> DetectionDataset:
"""
Creates a Dataset instance from YOLO formatted data.
@@ -281,12 +458,15 @@ class DetectionDataset(BaseDataset):
force_masks (bool, optional): If True, forces
masks to be loaded for all annotations,
regardless of whether they are present.
is_obb (bool, optional): If True, loads the annotations in OBB format.
OBB annotations are defined as `[class_id, x, y, x, y, x, y, x, y]`,
where pairs of [x, y] are box corners.
Returns:
DetectionDataset: A DetectionDataset instance
containing the loaded images and annotations.
Example:
Examples:
```python
import roboflow
from roboflow import Roboflow
@@ -308,13 +488,16 @@ class DetectionDataset(BaseDataset):
# ['dog', 'person']
```
"""
classes, images, annotations = load_yolo_annotations(
classes, image_paths, annotations = load_yolo_annotations(
images_directory_path=images_directory_path,
annotations_directory_path=annotations_directory_path,
data_yaml_path=data_yaml_path,
force_masks=force_masks,
is_obb=is_obb,
)
return DetectionDataset(
classes=classes, images=image_paths, annotations=annotations
)
return DetectionDataset(classes=classes, images=images, annotations=annotations)
def as_yolo(
self,
@@ -355,13 +538,12 @@ class DetectionDataset(BaseDataset):
"""
if images_directory_path is not None:
save_dataset_images(
images_directory_path=images_directory_path, images=self.images
dataset=self, images_directory_path=images_directory_path
)
if annotations_directory_path is not None:
save_yolo_annotations(
dataset=self,
annotations_directory_path=annotations_directory_path,
images=self.images,
annotations=self.annotations,
min_image_area_percentage=min_image_area_percentage,
max_image_area_percentage=max_image_area_percentage,
approximation_percentage=approximation_percentage,
@@ -391,7 +573,7 @@ class DetectionDataset(BaseDataset):
DetectionDataset: A DetectionDataset instance containing
the loaded images and annotations.
Example:
Examples:
```python
import roboflow
from roboflow import Roboflow
@@ -431,6 +613,20 @@ class DetectionDataset(BaseDataset):
Exports the dataset to COCO format. This method saves the
images and their corresponding annotations in COCO format.
!!! tip
The format of the mask is determined automatically based on its structure:
- If a mask contains multiple disconnected components or holes, it will be
saved using the Run-Length Encoding (RLE) format for efficient storage and
processing.
- If a mask consists of a single, contiguous region without any holes, it
will be encoded as a polygon, preserving the outline of the object.
This automatic selection ensures that the masks are stored in the most
appropriate and space-efficient format, complying with COCO dataset
standards.
Args:
images_directory_path (Optional[str]): The path to the directory
where the images should be saved.
@@ -451,103 +647,134 @@ class DetectionDataset(BaseDataset):
"""
if images_directory_path is not None:
save_dataset_images(
images_directory_path=images_directory_path, images=self.images
dataset=self, images_directory_path=images_directory_path
)
if annotations_path is not None:
save_coco_annotations(
dataset=self,
annotation_path=annotations_path,
images=self.images,
annotations=self.annotations,
classes=self.classes,
min_image_area_percentage=min_image_area_percentage,
max_image_area_percentage=max_image_area_percentage,
approximation_percentage=approximation_percentage,
)
@classmethod
def merge(cls, dataset_list: List[DetectionDataset]) -> DetectionDataset:
"""
Merge a list of `DetectionDataset` objects into a single
`DetectionDataset` object.
This method takes a list of `DetectionDataset` objects and combines
their respective fields (`classes`, `images`,
`annotations`) into a single `DetectionDataset` object.
Args:
dataset_list (List[DetectionDataset]): A list of `DetectionDataset`
objects to merge.
Returns:
(DetectionDataset): A single `DetectionDataset` object containing
the merged data from the input list.
Example:
```python
import supervision as sv
ds_1 = sv.DetectionDataset(...)
len(ds_1)
# 100
ds_1.classes
# ['dog', 'person']
ds_2 = sv.DetectionDataset(...)
len(ds_2)
# 200
ds_2.classes
# ['cat']
ds_merged = sv.DetectionDataset.merge([ds_1, ds_2])
len(ds_merged)
# 300
ds_merged.classes
# ['cat', 'dog', 'person']
```
"""
merged_images, merged_annotations = {}, {}
class_lists = [dataset.classes for dataset in dataset_list]
merged_classes = merge_class_lists(class_lists=class_lists)
for dataset in dataset_list:
class_index_mapping = build_class_index_mapping(
source_classes=dataset.classes, target_classes=merged_classes
)
for image_name, image, detections in dataset:
if image_name in merged_annotations:
raise ValueError(
f"Image name {image_name} is not unique across datasets."
)
merged_images[image_name] = image
merged_annotations[image_name] = map_detections_class_id(
source_to_target_mapping=class_index_mapping,
detections=detections,
)
return cls(
classes=merged_classes, images=merged_images, annotations=merged_annotations
)
@dataclass
class ClassificationDataset(BaseDataset):
"""
Dataclass containing information about a classification dataset.
Contains information about a classification dataset, handles lazy image
loading, dataset splitting.
Attributes:
classes (List[str]): List containing dataset class names.
images (Dict[str, np.ndarray]): Dictionary mapping image name to image.
annotations (Dict[str, Detections]): Dictionary mapping
images (Union[List[str], Dict[str, np.ndarray]]):
List of image paths or dictionary mapping image name to image data.
annotations (Dict[str, Classifications]): Dictionary mapping
image name to annotations.
"""
classes: List[str]
images: Dict[str, np.ndarray]
annotations: Dict[str, Classifications]
def __init__(
self,
classes: List[str],
images: Union[List[str], Dict[str, np.ndarray]],
annotations: Dict[str, Classifications],
) -> None:
self.classes = classes
if set(images) != set(annotations):
raise ValueError(
"The keys of the images and annotations dictionaries must match."
)
self.annotations = annotations
# Eliminate duplicates while preserving order
self.image_paths = list(dict.fromkeys(images))
self._images_in_memory: Dict[str, np.ndarray] = {}
if isinstance(images, dict):
self._images_in_memory = images
warn_deprecated(
"Passing a `Dict[str, np.ndarray]` into `ClassificationDataset` is "
"deprecated and will be removed in a future release. Use "
"a list of paths `List[str]` instead."
)
@property
@deprecated(
"`DetectionDataset.images` property is deprecated and will be removed in "
"`supervision-0.26.0`. Iterate with `for path, image, annotation in dataset:` "
"instead."
)
def images(self) -> Dict[str, np.ndarray]:
"""
Load all images to memory and return them as a dictionary.
!!! warning
Only use this when you need all images at once.
It is much more memory-efficient to initialize dataset with
image paths and use `for path, image, annotation in dataset:`.
"""
if self._images_in_memory:
return self._images_in_memory
images = {image_path: cv2.imread(image_path) for image_path in self.image_paths}
return images
def _get_image(self, image_path: str) -> np.ndarray:
"""Assumes that image is in dataset"""
if self._images_in_memory:
return self._images_in_memory[image_path]
return cv2.imread(image_path)
def __len__(self) -> int:
return len(self.images)
return len(self._images_in_memory) or len(self.image_paths)
def __getitem__(self, i: int) -> Tuple[str, np.ndarray, Classifications]:
"""
Returns:
Tuple[str, np.ndarray, Classifications]: The image path, image data,
and its corresponding annotation at index i.
"""
image_path = self.image_paths[i]
image = self._get_image(image_path)
annotation = self.annotations[image_path]
return image_path, image, annotation
def __iter__(self) -> Iterator[Tuple[str, np.ndarray, Classifications]]:
"""
Iterate over the images and annotations in the dataset.
Yields:
Iterator[Tuple[str, np.ndarray, Detections]]:
An iterator that yields tuples containing the image path,
the image data, and its corresponding annotation.
"""
for i in range(len(self)):
image_path, image, annotation = self[i]
yield image_path, image, annotation
def __eq__(self, other) -> bool:
if not isinstance(other, ClassificationDataset):
return False
if set(self.classes) != set(other.classes):
return False
if self.image_paths != other.image_paths:
return False
if self._images_in_memory or other._images_in_memory:
if not np.array_equal(
list(self._images_in_memory.values()),
list(other._images_in_memory.values()),
):
return False
if self.annotations != other.annotations:
return False
return True
def split(
self, split_ratio=0.8, random_state=None, shuffle: bool = True
@@ -567,35 +794,45 @@ class ClassificationDataset(BaseDataset):
Tuple[ClassificationDataset, ClassificationDataset]: A tuple containing
the training and testing datasets.
Example:
Examples:
```python
import supervision as sv
cd = sv.ClassificationDataset(...)
train_cd,test_cd = cd.split(split_ratio=0.7,
random_state=42,shuffle=True)
train_cd,test_cd = cd.split(split_ratio=0.7, random_state=42,shuffle=True)
len(train_cd), len(test_cd)
# (700, 300)
```
"""
image_names = list(self.images.keys())
train_names, test_names = train_test_split(
data=image_names,
train_paths, test_paths = train_test_split(
data=self.image_paths,
train_ratio=split_ratio,
random_state=random_state,
shuffle=shuffle,
)
train_input: Union[List[str], Dict[str, np.ndarray]]
test_input: Union[List[str], Dict[str, np.ndarray]]
if self._images_in_memory:
train_input = {path: self._images_in_memory[path] for path in train_paths}
test_input = {path: self._images_in_memory[path] for path in test_paths}
else:
train_input = train_paths
test_input = test_paths
train_annotations = {path: self.annotations[path] for path in train_paths}
test_annotations = {path: self.annotations[path] for path in test_paths}
train_dataset = ClassificationDataset(
classes=self.classes,
images={name: self.images[name] for name in train_names},
annotations={name: self.annotations[name] for name in train_names},
images=train_input,
annotations=train_annotations,
)
test_dataset = ClassificationDataset(
classes=self.classes,
images={name: self.images[name] for name in test_names},
annotations={name: self.annotations[name] for name in test_names},
images=test_input,
annotations=test_annotations,
)
return train_dataset, test_dataset
def as_folder_structure(self, root_directory_path: str) -> None:
@@ -611,18 +848,16 @@ class ClassificationDataset(BaseDataset):
for class_name in self.classes:
os.makedirs(os.path.join(root_directory_path, class_name), exist_ok=True)
for image_path in self.images:
classification = self.annotations[image_path]
image = self.images[image_path]
image_name = Path(image_path).name
for image_save_path, image, annotation in self:
image_name = Path(image_save_path).name
class_id = (
classification.class_id[0]
if classification.confidence is None
else classification.get_top_k(1)[0][0]
annotation.class_id[0]
if annotation.confidence is None
else annotation.get_top_k(1)[0][0]
)
class_name = self.classes[class_id]
image_path = os.path.join(root_directory_path, class_name, image_name)
cv2.imwrite(image_path, image)
image_save_path = os.path.join(root_directory_path, class_name, image_name)
cv2.imwrite(image_save_path, image)
@classmethod
def from_folder_structure(cls, root_directory_path: str) -> ClassificationDataset:
@@ -635,7 +870,7 @@ class ClassificationDataset(BaseDataset):
Returns:
ClassificationDataset: The dataset.
Example:
Examples:
```python
import roboflow
from roboflow import Roboflow
@@ -655,7 +890,7 @@ class ClassificationDataset(BaseDataset):
classes = os.listdir(root_directory_path)
classes = sorted(set(classes))
images = {}
image_paths = []
annotations = {}
for class_name in classes:
@@ -663,13 +898,13 @@ class ClassificationDataset(BaseDataset):
for image in os.listdir(os.path.join(root_directory_path, class_name)):
image_path = str(os.path.join(root_directory_path, class_name, image))
images[image_path] = cv2.imread(image_path)
image_paths.append(image_path)
annotations[image_path] = Classifications(
class_id=np.array([class_id]),
)
return cls(
classes=classes,
images=images,
images=image_paths,
annotations=annotations,
)
+61 -40
View File
@@ -1,19 +1,28 @@
import os
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Tuple
from typing import TYPE_CHECKING, Dict, List, Tuple
import cv2
import numpy as np
import numpy.typing as npt
from supervision.dataset.utils import (
approximate_mask_with_polygons,
map_detections_class_id,
mask_to_rle,
rle_to_mask,
)
from supervision.detection.core import Detections
from supervision.detection.utils import polygon_to_mask
from supervision.detection.utils import (
contains_holes,
contains_multiple_segments,
polygon_to_mask,
)
from supervision.utils.file import read_json_file, save_json_file
if TYPE_CHECKING:
from supervision.dataset.core import DetectionDataset
def coco_categories_to_classes(coco_categories: List[dict]) -> List[str]:
return [
@@ -57,13 +66,24 @@ def group_coco_annotations_by_image_id(
return annotations
def _polygons_to_masks(
polygons: List[np.ndarray], resolution_wh: Tuple[int, int]
) -> np.ndarray:
def coco_annotations_to_masks(
image_annotations: List[dict], resolution_wh: Tuple[int, int]
) -> npt.NDArray[np.bool_]:
return np.array(
[
polygon_to_mask(polygon=polygon, resolution_wh=resolution_wh)
for polygon in polygons
rle_to_mask(
rle=np.array(image_annotation["segmentation"]["counts"]),
resolution_wh=resolution_wh,
)
if image_annotation["iscrowd"]
else polygon_to_mask(
polygon=np.reshape(
np.asarray(image_annotation["segmentation"], dtype=np.int32),
(-1, 2),
),
resolution_wh=resolution_wh,
)
for image_annotation in image_annotations
],
dtype=bool,
)
@@ -83,13 +103,9 @@ def coco_annotations_to_detections(
xyxy[:, 2:4] += xyxy[:, 0:2]
if with_masks:
polygons = [
np.reshape(
np.asarray(image_annotation["segmentation"], dtype=np.int32), (-1, 2)
)
for image_annotation in image_annotations
]
mask = _polygons_to_masks(polygons=polygons, resolution_wh=resolution_wh)
mask = coco_annotations_to_masks(
image_annotations=image_annotations, resolution_wh=resolution_wh
)
return Detections(
class_id=np.asarray(class_ids, dtype=int), xyxy=xyxy, mask=mask
)
@@ -108,24 +124,35 @@ def detections_to_coco_annotations(
coco_annotations = []
for xyxy, mask, _, class_id, _, _ in detections:
box_width, box_height = xyxy[2] - xyxy[0], xyxy[3] - xyxy[1]
polygon = []
segmentation = []
iscrowd = 0
if mask is not None:
polygon = list(
approximate_mask_with_polygons(
mask=mask,
min_image_area_percentage=min_image_area_percentage,
max_image_area_percentage=max_image_area_percentage,
approximation_percentage=approximation_percentage,
)[0].flatten()
)
iscrowd = contains_holes(mask=mask) or contains_multiple_segments(mask=mask)
if iscrowd:
segmentation = {
"counts": mask_to_rle(mask=mask),
"size": list(mask.shape[:2]),
}
else:
segmentation = [
list(
approximate_mask_with_polygons(
mask=mask,
min_image_area_percentage=min_image_area_percentage,
max_image_area_percentage=max_image_area_percentage,
approximation_percentage=approximation_percentage,
)[0].flatten()
)
]
coco_annotation = {
"id": annotation_id,
"image_id": image_id,
"category_id": int(class_id),
"bbox": [xyxy[0], xyxy[1], box_width, box_height],
"area": box_width * box_height,
"segmentation": [polygon] if polygon else [],
"iscrowd": 0,
"segmentation": segmentation,
"iscrowd": iscrowd,
}
coco_annotations.append(coco_annotation)
annotation_id += 1
@@ -136,7 +163,7 @@ def load_coco_annotations(
images_directory_path: str,
annotations_path: str,
force_masks: bool = False,
) -> Tuple[List[str], Dict[str, np.ndarray], Dict[str, Detections]]:
) -> Tuple[List[str], List[str], Dict[str, Detections]]:
coco_data = read_json_file(file_path=annotations_path)
classes = coco_categories_to_classes(coco_categories=coco_data["categories"])
class_index_mapping = build_coco_class_index_mapping(
@@ -147,7 +174,7 @@ def load_coco_annotations(
coco_annotations=coco_data["annotations"]
)
images = {}
images = []
annotations = {}
for coco_image in coco_images:
@@ -159,7 +186,6 @@ def load_coco_annotations(
image_annotations = coco_annotations_groups.get(coco_image["id"], [])
image_path = os.path.join(images_directory_path, image_name)
image = cv2.imread(image_path)
annotation = coco_annotations_to_detections(
image_annotations=image_annotations,
resolution_wh=(image_width, image_height),
@@ -170,23 +196,20 @@ def load_coco_annotations(
detections=annotation,
)
images[image_path] = image
images.append(image_path)
annotations[image_path] = annotation
return classes, images, annotations
def save_coco_annotations(
dataset: "DetectionDataset",
annotation_path: str,
images: Dict[str, np.ndarray],
annotations: Dict[str, Detections],
classes: List[str],
min_image_area_percentage: float = 0.0,
max_image_area_percentage: float = 1.0,
approximation_percentage: float = 0.75,
) -> None:
Path(annotation_path).parent.mkdir(parents=True, exist_ok=True)
info = {}
licenses = [
{
"id": 1,
@@ -197,10 +220,10 @@ def save_coco_annotations(
coco_annotations = []
coco_images = []
coco_categories = classes_to_coco_categories(classes=classes)
coco_categories = classes_to_coco_categories(classes=dataset.classes)
image_id, annotation_id = 1, 1
for image_path, image in images.items():
for image_path, image, annotation in dataset:
image_height, image_width, _ = image.shape
image_name = f"{Path(image_path).stem}{Path(image_path).suffix}"
coco_image = {
@@ -213,10 +236,8 @@ def save_coco_annotations(
}
coco_images.append(coco_image)
detections = annotations[image_path]
coco_annotation, annotation_id = detections_to_coco_annotations(
detections=detections,
detections=annotation,
image_id=image_id,
annotation_id=annotation_id,
min_image_area_percentage=min_image_area_percentage,
@@ -228,7 +249,7 @@ def save_coco_annotations(
image_id += 1
annotation_dict = {
"info": info,
"info": {},
"licenses": licenses,
"categories": coco_categories,
"images": coco_images,
+18 -23
View File
@@ -5,7 +5,8 @@ from xml.etree.ElementTree import Element, SubElement
import cv2
import numpy as np
from defusedxml.ElementTree import fromstring, parse, tostring
from defusedxml.ElementTree import parse, tostring
from defusedxml.minidom import parseString
from supervision.dataset.utils import approximate_mask_with_polygons
from supervision.detection.core import Detections
@@ -129,8 +130,7 @@ def detections_to_pascal_voc(
annotation.append(next_object)
# Generate XML string
xml_string = fromstring(tostring(annotation)).toprettyxml(indent=" ")
xml_string = parseString(tostring(annotation)).toprettyxml(indent=" ")
return xml_string
@@ -138,7 +138,7 @@ def load_pascal_voc_annotations(
images_directory_path: str,
annotations_directory_path: str,
force_masks: bool = False,
) -> Tuple[List[str], Dict[str, np.ndarray], Dict[str, Detections]]:
) -> Tuple[List[str], List[str], Dict[str, Detections]]:
"""
Loads PASCAL VOC XML annotations and returns the image name,
a Detections instance, and a list of class names.
@@ -151,44 +151,39 @@ def load_pascal_voc_annotations(
annotations, regardless of whether they are present.
Returns:
Tuple[List[str], Dict[str, np.ndarray], Dict[str, Detections]]: A tuple
containing a list of class names,
a dictionary with image names as keys and
images as values, and a dictionary with image names as
keys and corresponding Detections instances as values.
Tuple[List[str], List[str], Dict[str, Detections]]: A tuple with a list
of class names, a list of paths to images, and a dictionary with image
paths as keys and corresponding Detections instances as values.
"""
image_paths = list_files_with_extensions(
directory=images_directory_path, extensions=["jpg", "jpeg", "png"]
)
image_paths = [
str(path)
for path in list_files_with_extensions(
directory=images_directory_path, extensions=["jpg", "jpeg", "png"]
)
]
classes = []
images = {}
classes: List[str] = []
annotations = {}
for image_path in image_paths:
image_name = Path(image_path).stem
image_path = str(image_path)
image = cv2.imread(image_path)
annotation_path = os.path.join(annotations_directory_path, f"{image_name}.xml")
image_stem = Path(image_path).stem
annotation_path = os.path.join(annotations_directory_path, f"{image_stem}.xml")
if not os.path.exists(annotation_path):
images[image_path] = image
annotations[image_path] = Detections.empty()
continue
tree = parse(annotation_path)
root = tree.getroot()
image = cv2.imread(image_path)
resolution_wh = (image.shape[1], image.shape[0])
annotation, classes = detections_from_xml_obj(
root, classes, resolution_wh, force_masks
)
images[image_path] = image
annotations[image_path] = annotation
return classes, images, annotations
return classes, image_paths, annotations
def detections_from_xml_obj(
+46 -25
View File
@@ -1,10 +1,11 @@
import os
from pathlib import Path
from typing import Dict, List, Optional, Tuple
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple
import cv2
import numpy as np
from supervision.config import ORIENTED_BOX_COORDINATES
from supervision.dataset.utils import approximate_mask_with_polygons
from supervision.detection.core import Detections
from supervision.detection.utils import polygon_to_mask, polygon_to_xyxy
@@ -16,6 +17,9 @@ from supervision.utils.file import (
save_yaml_file,
)
if TYPE_CHECKING:
from supervision.dataset.core import DetectionDataset
def _parse_box(values: List[str]) -> np.ndarray:
x_center, y_center, width, height = values
@@ -70,12 +74,15 @@ def _image_name_to_annotation_name(image_name: str) -> str:
def yolo_annotations_to_detections(
lines: List[str], resolution_wh: Tuple[int, int], with_masks: bool
lines: List[str],
resolution_wh: Tuple[int, int],
with_masks: bool,
is_obb: bool = False,
) -> Detections:
if len(lines) == 0:
return Detections.empty()
class_id, relative_xyxy, relative_polygon = [], [], []
class_id, relative_xyxy, relative_polygon, relative_xyxyxyxy = [], [], [], []
w, h = resolution_wh
for line in lines:
values = line.split()
@@ -88,21 +95,30 @@ def yolo_annotations_to_detections(
elif len(values) > 5:
polygon = _parse_polygon(values=values[1:])
relative_xyxy.append(polygon_to_xyxy(polygon=polygon))
if is_obb:
relative_xyxyxyxy.append(np.array(values[1:]))
if with_masks:
relative_polygon.append(polygon)
class_id = np.array(class_id, dtype=int)
relative_xyxy = np.array(relative_xyxy, dtype=np.float32)
xyxy = relative_xyxy * np.array([w, h, w, h], dtype=np.float32)
data = {}
if is_obb:
relative_xyxyxyxy = np.array(relative_xyxyxyxy, dtype=np.float32)
xyxyxyxy = relative_xyxyxyxy.reshape(-1, 4, 2)
xyxyxyxy *= np.array([w, h], dtype=np.float32)
data[ORIENTED_BOX_COORDINATES] = xyxyxyxy
if not with_masks:
return Detections(class_id=class_id, xyxy=xyxy)
return Detections(class_id=class_id, xyxy=xyxy, data=data)
polygons = [
(polygon * np.array(resolution_wh)).astype(int) for polygon in relative_polygon
]
mask = _polygons_to_masks(polygons=polygons, resolution_wh=resolution_wh)
return Detections(class_id=class_id, xyxy=xyxy, mask=mask)
return Detections(class_id=class_id, xyxy=xyxy, data=data, mask=mask)
def load_yolo_annotations(
@@ -110,7 +126,8 @@ def load_yolo_annotations(
annotations_directory_path: str,
data_yaml_path: str,
force_masks: bool = False,
) -> Tuple[List[str], Dict[str, np.ndarray], Dict[str, Detections]]:
is_obb: bool = False,
) -> Tuple[List[str], List[str], Dict[str, Detections]]:
"""
Loads YOLO annotations and returns class names, images,
and their corresponding detections.
@@ -123,32 +140,34 @@ def load_yolo_annotations(
YAML file containing class information.
force_masks (bool, optional): If True, forces masks to be loaded
for all annotations, regardless of whether they are present.
is_obb (bool, optional): If True, loads the annotations in OBB format.
OBB annotations are defined as `[class_id, x, y, x, y, x, y, x, y]`,
where pairs of [x, y] are box corners.
Returns:
Tuple[List[str], Dict[str, np.ndarray], Dict[str, Detections]]:
Tuple[List[str], List[str], Dict[str, Detections]]:
A tuple containing a list of class names, a dictionary with
image names as keys and images as values, and a dictionary
with image names as keys and corresponding Detections instances as values.
"""
image_paths = list_files_with_extensions(
directory=images_directory_path, extensions=["jpg", "jpeg", "png"]
)
image_paths = [
str(path)
for path in list_files_with_extensions(
directory=images_directory_path, extensions=["jpg", "jpeg", "png"]
)
]
classes = _extract_class_names(file_path=data_yaml_path)
images = {}
annotations = {}
for image_path in image_paths:
image_stem = Path(image_path).stem
image_path = str(image_path)
image = cv2.imread(image_path)
annotation_path = os.path.join(annotations_directory_path, f"{image_stem}.txt")
if not os.path.exists(annotation_path):
images[image_path] = image
annotations[image_path] = Detections.empty()
continue
image = cv2.imread(image_path)
lines = read_txt_file(file_path=annotation_path, skip_empty=True)
h, w, _ = image.shape
resolution_wh = (w, h)
@@ -156,12 +175,13 @@ def load_yolo_annotations(
with_masks = _with_mask(lines=lines)
with_masks = force_masks if force_masks else with_masks
annotation = yolo_annotations_to_detections(
lines=lines, resolution_wh=resolution_wh, with_masks=with_masks
lines=lines,
resolution_wh=resolution_wh,
with_masks=with_masks,
is_obb=is_obb,
)
images[image_path] = image
annotations[image_path] = annotation
return classes, images, annotations
return classes, image_paths, annotations
def object_to_yolo(
@@ -195,6 +215,9 @@ def detections_to_yolo_annotations(
) -> List[str]:
annotation = []
for xyxy, mask, _, class_id, _, _ in detections:
if class_id is None:
raise ValueError("Class ID is required for YOLO annotations.")
if mask is not None:
polygons = approximate_mask_with_polygons(
mask=mask,
@@ -220,24 +243,22 @@ def detections_to_yolo_annotations(
def save_yolo_annotations(
dataset: "DetectionDataset",
annotations_directory_path: str,
images: Dict[str, np.ndarray],
annotations: Dict[str, Detections],
min_image_area_percentage: float = 0.0,
max_image_area_percentage: float = 1.0,
approximation_percentage: float = 0.75,
) -> None:
Path(annotations_directory_path).mkdir(parents=True, exist_ok=True)
for image_path, image in images.items():
detections = annotations[image_path]
for image_path, image, annotation in dataset:
image_name = Path(image_path).name
yolo_annotations_name = _image_name_to_annotation_name(image_name=image_name)
yolo_annotations_path = os.path.join(
annotations_directory_path, yolo_annotations_name
)
lines = detections_to_yolo_annotations(
detections=detections,
image_shape=image.shape,
detections=annotation,
image_shape=image.shape, # type: ignore
min_image_area_percentage=min_image_area_percentage,
max_image_area_percentage=max_image_area_percentage,
approximation_percentage=approximation_percentage,
+135 -7
View File
@@ -1,11 +1,13 @@
import copy
import os
import random
import shutil
from pathlib import Path
from typing import Dict, List, Optional, Tuple, TypeVar
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, TypeVar, Union
import cv2
import numpy as np
import numpy.typing as npt
from supervision.detection.core import Detections
from supervision.detection.utils import (
@@ -14,6 +16,9 @@ from supervision.detection.utils import (
mask_to_polygons,
)
if TYPE_CHECKING:
from supervision.dataset.core import DetectionDataset
T = TypeVar("T")
@@ -58,6 +63,7 @@ def merge_class_lists(class_lists: List[List[str]]) -> List[str]:
def build_class_index_mapping(
source_classes: List[str], target_classes: List[str]
) -> Dict[int, int]:
"""Returns the index map of source classes -> target classes."""
index_mapping = {}
for i, class_name in enumerate(source_classes):
@@ -93,14 +99,16 @@ def map_detections_class_id(
def save_dataset_images(
images_directory_path: str, images: Dict[str, np.ndarray]
dataset: "DetectionDataset", images_directory_path: str
) -> None:
Path(images_directory_path).mkdir(parents=True, exist_ok=True)
for image_path, image in images.items():
image_name = Path(image_path).name
target_image_path = os.path.join(images_directory_path, image_name)
cv2.imwrite(target_image_path, image)
for image_path in dataset.image_paths:
final_path = os.path.join(images_directory_path, Path(image_path).name)
if image_path in dataset._images_in_memory:
image = dataset._images_in_memory[image_path]
cv2.imwrite(final_path, image)
else:
shutil.copyfile(image_path, final_path)
def train_test_split(
@@ -129,3 +137,123 @@ def train_test_split(
split_index = int(len(data) * train_ratio)
return data[:split_index], data[split_index:]
def rle_to_mask(
rle: Union[npt.NDArray[np.int_], List[int]], resolution_wh: Tuple[int, int]
) -> npt.NDArray[np.bool_]:
"""
Converts run-length encoding (RLE) to a binary mask.
Args:
rle (Union[npt.NDArray[np.int_], List[int]]): The 1D RLE array, the format
used in the COCO dataset (column-wise encoding, values of an array with
even indices represent the number of pixels assigned as background,
values of an array with odd indices represent the number of pixels
assigned as foreground object).
resolution_wh (Tuple[int, int]): The width (w) and height (h)
of the desired binary mask.
Returns:
The generated 2D Boolean mask of shape `(h, w)`, where the foreground object is
marked with `True`'s and the rest is filled with `False`'s.
Raises:
AssertionError: If the sum of pixels encoded in RLE differs from the
number of pixels in the expected mask (computed based on resolution_wh).
Examples:
```python
import supervision as sv
sv.rle_to_mask([5, 2, 2, 2, 5], (4, 4))
# array([
# [False, False, False, False],
# [False, True, True, False],
# [False, True, True, False],
# [False, False, False, False],
# ])
```
"""
if isinstance(rle, list):
rle = np.array(rle, dtype=int)
width, height = resolution_wh
assert width * height == np.sum(rle), (
"the sum of the number of pixels in the RLE must be the same "
"as the number of pixels in the expected mask"
)
zero_one_values = np.zeros(shape=(rle.size, 1), dtype=np.uint8)
zero_one_values[1::2] = 1
decoded_rle = np.repeat(zero_one_values, rle, axis=0)
decoded_rle = np.append(
decoded_rle, np.zeros(width * height - len(decoded_rle), dtype=np.uint8)
)
return decoded_rle.reshape((height, width), order="F")
def mask_to_rle(mask: npt.NDArray[np.bool_]) -> List[int]:
"""
Converts a binary mask into a run-length encoding (RLE).
Args:
mask (npt.NDArray[np.bool_]): 2D binary mask where `True` indicates foreground
object and `False` indicates background.
Returns:
The run-length encoded mask. Values of a list with even indices
represent the number of pixels assigned as background (`False`), values
of a list with odd indices represent the number of pixels assigned
as foreground object (`True`).
Raises:
AssertionError: If input mask is not 2D or is empty.
Examples:
```python
import numpy as np
import supervision as sv
mask = np.array([
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
])
sv.mask_to_rle(mask)
# [0, 16]
mask = np.array([
[False, False, False, False],
[False, True, True, False],
[False, True, True, False],
[False, False, False, False],
])
sv.mask_to_rle(mask)
# [5, 2, 2, 2, 5]
```
![mask_to_rle](https://media.roboflow.com/supervision-docs/mask-to-rle.png){ align=center width="800" }
""" # noqa E501 // docs
assert mask.ndim == 2, "Input mask must be 2D"
assert mask.size != 0, "Input mask cannot be empty"
on_value_change_indices = np.where(
mask.ravel(order="F") != np.roll(mask.ravel(order="F"), 1)
)[0]
on_value_change_indices = np.append(on_value_change_indices, mask.size)
# need to add 0 at the beginning when the same value is in the first and
# last element of the flattened mask
if on_value_change_indices[0] != 0:
on_value_change_indices = np.insert(on_value_change_indices, 0, 0)
rle = np.diff(on_value_change_indices)
if mask[0][0] == 1:
rle = np.insert(rle, 0, 0)
return list(rle)
-155
View File
@@ -1,155 +0,0 @@
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.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.
Attributes:
color (Union[Color, ColorPalette]): The color to draw the bounding box,
can be a single color or a color palette
thickness (int): The thickness of the bounding box lines, default is 2
text_color (Color): The color of the text on the bounding box, default is white
text_scale (float): The scale of the text on the bounding box, default is 0.5
text_thickness (int): The thickness of the text on the bounding box,
default is 1
text_padding (int): The padding around the text on the bounding box,
default is 5
"""
def __init__(
self,
color: Union[Color, ColorPalette] = ColorPalette.DEFAULT,
thickness: int = 2,
text_color: Color = Color.BLACK,
text_scale: float = 0.5,
text_thickness: int = 1,
text_padding: int = 10,
):
self.color: Union[Color, ColorPalette] = color
self.thickness: int = thickness
self.text_color: Color = text_color
self.text_scale: float = text_scale
self.text_thickness: int = text_thickness
self.text_padding: int = text_padding
@scene_to_annotator_img_type
def annotate(
self,
scene: ImageType,
detections: Detections,
labels: Optional[List[str]] = None,
skip_label: bool = False,
) -> ImageType:
"""
Draws bounding boxes on the frame using the detections provided.
Args:
scene (ImageType): The image on which the bounding boxes will be drawn.
`ImageType` is a flexible type, accepting either `numpy.ndarray`
or `PIL.Image.Image`.
detections (Detections): The detections for which the
bounding boxes will be drawn
labels (Optional[List[str]]): An optional list of labels
corresponding to each detection. If `labels` are not provided,
corresponding `class_id` will be used as label.
skip_label (bool): Is set to `True`, skips bounding box label annotation.
Returns:
ImageType: The image with the bounding boxes drawn on it, matching the
type of `scene` (`numpy.ndarray` or `PIL.Image.Image`)
Example:
```python
import supervision as sv
classes = ['person', ...]
image = ...
detections = sv.Detections(...)
box_annotator = sv.BoxAnnotator()
labels = [
f"{classes[class_id]} {confidence:0.2f}"
for _, _, confidence, class_id, _ in detections
]
annotated_frame = box_annotator.annotate(
scene=image.copy(),
detections=detections,
labels=labels
)
```
"""
font = cv2.FONT_HERSHEY_SIMPLEX
for i in range(len(detections)):
x1, y1, x2, y2 = detections.xyxy[i].astype(int)
class_id = (
detections.class_id[i] if detections.class_id is not None else None
)
idx = class_id if class_id is not None else i
color = (
self.color.by_idx(idx)
if isinstance(self.color, ColorPalette)
else self.color
)
cv2.rectangle(
img=scene,
pt1=(x1, y1),
pt2=(x2, y2),
color=color.as_bgr(),
thickness=self.thickness,
)
if skip_label:
continue
text = (
f"{class_id}"
if (labels is None or len(detections) != len(labels))
else labels[i]
)
text_width, text_height = cv2.getTextSize(
text=text,
fontFace=font,
fontScale=self.text_scale,
thickness=self.text_thickness,
)[0]
text_x = x1 + self.text_padding
text_y = y1 - self.text_padding
text_background_x1 = x1
text_background_y1 = y1 - 2 * self.text_padding - text_height
text_background_x2 = x1 + 2 * self.text_padding + text_width
text_background_y2 = y1
cv2.rectangle(
img=scene,
pt1=(text_background_x1, text_background_y1),
pt2=(text_background_x2, text_background_y2),
color=color.as_bgr(),
thickness=cv2.FILLED,
)
cv2.putText(
img=scene,
text=text,
org=(text_x, text_y),
fontFace=font,
fontScale=self.text_scale,
color=self.text_color.as_rgb(),
thickness=self.text_thickness,
lineType=cv2.LINE_AA,
)
return scene
+443 -102
View File
@@ -7,53 +7,101 @@ from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
import numpy as np
from supervision.config import CLASS_NAME_DATA_FIELD, ORIENTED_BOX_COORDINATES
from supervision.detection.utils import (
from supervision.detection.lmm import (
LMM,
from_florence_2,
from_paligemma,
validate_lmm_parameters,
)
from supervision.detection.overlap_filter import (
box_non_max_merge,
box_non_max_suppression,
mask_non_max_suppression,
)
from supervision.detection.utils import (
box_iou_batch,
calculate_masks_centroids,
extract_ultralytics_masks,
get_data_item,
is_data_equal,
mask_non_max_suppression,
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.utils.internal import get_instance_variables
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
@@ -69,15 +117,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
@@ -176,8 +216,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
@@ -188,7 +228,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.
@@ -201,13 +241,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 hasattr(ultralytics_results, "obb") 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()
@@ -385,23 +428,86 @@ class Detections:
xyxy=mmdet_results.pred_instances.bboxes.cpu().numpy(),
confidence=mmdet_results.pred_instances.scores.cpu().numpy(),
class_id=mmdet_results.pred_instances.labels.cpu().numpy().astype(int),
mask=mmdet_results.pred_instances.masks.cpu().numpy()
if "masks" in mmdet_results.pred_instances
else None,
)
@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
[transformer](https://github.com/huggingface/transformers) inference result.
Creates a Detections instance from object detection or segmentation
[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.
"""
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
)
```
!!! 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().detach().numpy(),
class_id=class_ids,
data=data,
)
else:
raise NotImplementedError(
"Only object detection and semantic segmentation results are supported."
)
@classmethod
def from_detectron2(cls, detectron2_results) -> Detections:
@@ -439,6 +545,9 @@ class Detections:
return cls(
xyxy=detectron2_results["instances"].pred_boxes.tensor.cpu().numpy(),
confidence=detectron2_results["instances"].scores.cpu().numpy(),
mask=detectron2_results["instances"].pred_masks.cpu().numpy()
if hasattr(detectron2_results["instances"], "pred_masks")
else None,
class_id=detectron2_results["instances"]
.pred_classes.cpu()
.numpy()
@@ -448,17 +557,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.
@@ -471,14 +575,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)
@@ -500,45 +608,6 @@ class Detections:
data=data,
)
@classmethod
@deprecated(
"`Detections.from_roboflow` is deprecated and will be removed in "
"`supervision-0.22.0`. Use `Detections.from_inference` instead."
)
def from_roboflow(cls, roboflow_result: Union[dict, Any]) -> Detections:
"""
!!! failure "Deprecated"
`Detections.from_roboflow` is deprecated and will be removed in
`supervision-0.22.0`. Use `Detections.from_inference` instead.
Create a Detections object from the [Roboflow](https://roboflow.com/)
API inference result or the [Inference](https://inference.roboflow.com/)
package results.
Args:
roboflow_result (dict): The result from the
Roboflow API containing predictions.
Returns:
(Detections): A Detections object containing the bounding boxes, class IDs,
and confidences of the predictions.
Example:
```python
import cv2
import supervision as sv
from inference.models.utils import get_roboflow_model
image = cv2.imread(<SOURCE_IMAGE_PATH>)
model = get_roboflow_model(model_id="yolov8s-640")
result = model.infer(image)[0]
detections = sv.Detections.from_roboflow(result)
```
"""
return cls.from_inference(roboflow_result)
@classmethod
def from_sam(cls, sam_result: List[dict]) -> Detections:
"""
@@ -578,7 +647,7 @@ class Detections:
if np.asarray(xywh).shape[0] == 0:
return cls.empty()
xyxy = xywh_to_xyxy(boxes_xywh=xywh)
xyxy = xywh_to_xyxy(xywh=xywh)
return cls(xyxy=xyxy, mask=mask)
@classmethod
@@ -710,6 +779,69 @@ class Detections:
class_id=paddledet_result["bbox"][:, 0].astype(int),
)
@classmethod
def from_lmm(
cls, lmm: Union[LMM, str], result: Union[str, dict], **kwargs
) -> Detections:
"""
Creates a Detections object from the given result string based on the specified
Large Multimodal Model (LMM).
Args:
lmm (Union[LMM, str]): The type of LMM (Large Multimodal Model) to use.
result (str): The result string containing the detection data.
**kwargs: Additional keyword arguments required by the specified LMM.
Returns:
Detections: A new Detections object.
Raises:
ValueError: If the LMM is invalid, required arguments are missing, or
disallowed arguments are provided.
ValueError: If the specified LMM is not supported.
Examples:
```python
import supervision as sv
paligemma_result = "<loc0256><loc0256><loc0768><loc0768> cat"
detections = sv.Detections.from_lmm(
sv.LMM.PALIGEMMA,
paligemma_result,
resolution_wh=(1000, 1000),
classes=['cat', 'dog']
)
detections.xyxy
# array([[250., 250., 750., 750.]])
detections.class_id
# array([0])
```
"""
lmm = validate_lmm_parameters(lmm, result, kwargs)
if lmm == LMM.PALIGEMMA:
assert isinstance(result, str)
xyxy, class_id, class_name = from_paligemma(result, **kwargs)
data = {CLASS_NAME_DATA_FIELD: class_name}
return cls(xyxy=xyxy, class_id=class_id, data=data)
if lmm == LMM.FLORENCE_2:
assert isinstance(result, dict)
xyxy, labels, mask, xyxyxyxy = from_florence_2(result, **kwargs)
if len(xyxy) == 0:
return cls.empty()
data = {}
if labels is not None:
data[CLASS_NAME_DATA_FIELD] = labels
if xyxyxyxy is not None:
data[ORIENTED_BOX_COORDINATES] = xyxyxyxy
return cls(xyxy=xyxy, mask=mask, data=data)
raise ValueError(f"Unsupported LMM: {lmm}")
@classmethod
def empty(cls) -> Detections:
"""
@@ -732,6 +864,14 @@ class Detections:
class_id=np.array([], dtype=int),
)
def is_empty(self) -> bool:
"""
Returns `True` if the `Detections` object is considered empty.
"""
empty_detections = Detections.empty()
empty_detections.data = self.data
return self == empty_detections
@classmethod
def merge(cls, detections_list: List[Detections]) -> Detections:
"""
@@ -739,9 +879,14 @@ class Detections:
This method takes a list of Detections objects and combines their
respective fields (`xyxy`, `mask`, `confidence`, `class_id`, and `tracker_id`)
into a single Detections object. If all elements in a field are not
`None`, the corresponding field will be stacked.
Otherwise, the field will be set to `None`.
into a single Detections object.
For example, if merging Detections with 3 and 4 detected objects, this method
will return a Detections with 7 objects (7 entries in `xyxy`, `mask`, etc).
!!! Note
When merging, empty `Detections` objects are ignored.
Args:
detections_list (List[Detections]): A list of Detections objects to merge.
@@ -781,6 +926,10 @@ class Detections:
array([0.1, 0.2, 0.3])
```
"""
detections_list = [
detections for detections in detections_list if not detections.is_empty()
]
if len(detections_list) == 0:
return Detections.empty()
@@ -1055,3 +1204,195 @@ class Detections:
)
return self[indices]
def with_nmm(
self, threshold: float = 0.5, class_agnostic: bool = False
) -> Detections:
"""
Perform non-maximum merging on the current set of object detections.
Args:
threshold (float, optional): The intersection-over-union threshold
to use for non-maximum merging. Defaults to 0.5.
class_agnostic (bool, optional): Whether to perform class-agnostic
non-maximum merging. If True, the class_id of each detection
will be ignored. Defaults to False.
Returns:
Detections: A new Detections object containing the subset of detections
after non-maximum merging.
Raises:
AssertionError: If `confidence` is None or `class_id` is None and
class_agnostic is False.
![non-max-merging](https://media.roboflow.com/supervision-docs/non-max-merging.png){ align=center width="800" }
""" # noqa: E501 // docs
if len(self) == 0:
return self
assert (
self.confidence is not None
), "Detections confidence must be given for NMM to be executed."
if class_agnostic:
predictions = np.hstack((self.xyxy, self.confidence.reshape(-1, 1)))
else:
assert self.class_id is not None, (
"Detections class_id must be given for NMM to be executed. If you"
" intended to perform class agnostic NMM set class_agnostic=True."
)
predictions = np.hstack(
(
self.xyxy,
self.confidence.reshape(-1, 1),
self.class_id.reshape(-1, 1),
)
)
merge_groups = box_non_max_merge(
predictions=predictions, iou_threshold=threshold
)
result = []
for merge_group in merge_groups:
unmerged_detections = [self[i] for i in merge_group]
merged_detections = merge_inner_detections_objects(
unmerged_detections, threshold
)
result.append(merged_detections)
return Detections.merge(result)
def merge_inner_detection_object_pair(
detections_1: Detections, detections_2: Detections
) -> Detections:
"""
Merges two Detections object into a single Detections object.
Assumes each Detections contains exactly one object.
A `winning` detection is determined based on the confidence score of the two
input detections. This winning detection is then used to specify which
`class_id`, `tracker_id`, and `data` to include in the merged Detections object.
The resulting `confidence` of the merged object is calculated by the weighted
contribution of ea detection to the merged object.
The bounding boxes and masks of the two input detections are merged into a
single bounding box and mask, respectively.
Args:
detections_1 (Detections):
The first Detections object
detections_2 (Detections):
The second Detections object
Returns:
Detections: A new Detections object, with merged attributes.
Raises:
ValueError: If the input Detections objects do not have exactly 1 detected
object.
Example:
```python
import cv2
import supervision as sv
from inference import get_model
image = cv2.imread(<SOURCE_IMAGE_PATH>)
model = get_model(model_id="yolov8s-640")
result = model.infer(image)[0]
detections = sv.Detections.from_inference(result)
merged_detections = merge_object_detection_pair(
detections[0], detections[1])
```
"""
if len(detections_1) != 1 or len(detections_2) != 1:
raise ValueError("Both Detections should have exactly 1 detected object.")
validate_fields_both_defined_or_none(detections_1, detections_2)
xyxy_1 = detections_1.xyxy[0]
xyxy_2 = detections_2.xyxy[0]
if detections_1.confidence is None and detections_2.confidence is None:
merged_confidence = None
else:
detection_1_area = (xyxy_1[2] - xyxy_1[0]) * (xyxy_1[3] - xyxy_1[1])
detections_2_area = (xyxy_2[2] - xyxy_2[0]) * (xyxy_2[3] - xyxy_2[1])
merged_confidence = (
detection_1_area * detections_1.confidence[0]
+ detections_2_area * detections_2.confidence[0]
) / (detection_1_area + detections_2_area)
merged_confidence = np.array([merged_confidence])
merged_x1, merged_y1 = np.minimum(xyxy_1[:2], xyxy_2[:2])
merged_x2, merged_y2 = np.maximum(xyxy_1[2:], xyxy_2[2:])
merged_xyxy = np.array([[merged_x1, merged_y1, merged_x2, merged_y2]])
if detections_1.mask is None and detections_2.mask is None:
merged_mask = None
else:
merged_mask = np.logical_or(detections_1.mask, detections_2.mask)
if detections_1.confidence is None and detections_2.confidence is None:
winning_detection = detections_1
elif detections_1.confidence[0] >= detections_2.confidence[0]:
winning_detection = detections_1
else:
winning_detection = detections_2
return Detections(
xyxy=merged_xyxy,
mask=merged_mask,
confidence=merged_confidence,
class_id=winning_detection.class_id,
tracker_id=winning_detection.tracker_id,
data=winning_detection.data,
)
def merge_inner_detections_objects(
detections: List[Detections], threshold=0.5
) -> Detections:
"""
Given N detections each of length 1 (exactly one object inside), combine them into a
single detection object of length 1. The contained inner object will be the merged
result of all the input detections.
For example, this lets you merge N boxes into one big box, N masks into one mask,
etc.
"""
detections_1 = detections[0]
for detections_2 in detections[1:]:
box_iou = box_iou_batch(detections_1.xyxy, detections_2.xyxy)[0]
if box_iou < threshold:
break
detections_1 = merge_inner_detection_object_pair(detections_1, detections_2)
return detections_1
def validate_fields_both_defined_or_none(
detections_1: Detections, detections_2: Detections
) -> None:
"""
Verify that for each optional field in the Detections, both instances either have
the field set to None or both have it set to non-None values.
`data` field is ignored.
Raises:
ValueError: If one field is None and the other is not, for any of the fields.
"""
attributes = get_instance_variables(detections_1)
for attribute in attributes:
value_1 = getattr(detections_1, attribute)
value_2 = getattr(detections_2, attribute)
if (value_1 is None) != (value_2 is None):
raise ValueError(
f"Field '{attribute}' should be consistently None or not None in both "
"Detections."
)
+26 -20
View File
@@ -1,12 +1,15 @@
import warnings
from typing import Dict, Iterable, Optional, Tuple
import cv2
import numpy as np
from supervision.detection.core import Detections
from supervision.detection.utils import cross_product
from supervision.draw.color import Color
from supervision.draw.utils import draw_text
from supervision.geometry.core import Point, Position, Vector
from supervision.utils.internal import SupervisionWarnings
class LineZone:
@@ -81,6 +84,8 @@ class LineZone:
self.in_count: int = 0
self.out_count: int = 0
self.triggering_anchors = triggering_anchors
if not list(self.triggering_anchors):
raise ValueError("Triggering anchors cannot be empty.")
@staticmethod
def calculate_region_of_interest_limits(vector: Vector) -> Tuple[Vector, Vector]:
@@ -140,6 +145,15 @@ class LineZone:
if len(detections) == 0:
return crossed_in, crossed_out
if detections.tracker_id is None:
warnings.warn(
"Line zone counting skipped. LineZone requires tracker_id. Refer to "
"https://supervision.roboflow.com/latest/trackers for more "
"information.",
category=SupervisionWarnings,
)
return crossed_in, crossed_out
all_anchors = np.array(
[
detections.get_anchors_coordinates(anchor)
@@ -147,31 +161,23 @@ class LineZone:
]
)
cross_products_1 = cross_product(all_anchors, self.limits[0])
cross_products_2 = cross_product(all_anchors, self.limits[1])
in_limits = (cross_products_1 > 0) == (cross_products_2 > 0)
in_limits = np.all(in_limits, axis=0)
triggers = cross_product(all_anchors, self.vector) < 0
has_any_left_trigger = np.any(triggers, axis=0)
has_any_right_trigger = np.any(~triggers, axis=0)
is_uniformly_triggered = ~(has_any_left_trigger & has_any_right_trigger)
for i, tracker_id in enumerate(detections.tracker_id):
if tracker_id is None:
if not in_limits[i]:
continue
box_anchors = [Point(x=x, y=y) for x, y in all_anchors[:, i, :]]
in_limits = all(
[
self.is_point_in_limits(point=anchor, limits=self.limits)
for anchor in box_anchors
]
)
if not in_limits:
if not is_uniformly_triggered[i]:
continue
triggers = [
self.vector.cross_product(point=anchor) < 0 for anchor in box_anchors
]
if len(set(triggers)) == 2:
continue
tracker_state = triggers[0]
tracker_state = has_any_left_trigger[i]
if tracker_id not in self.tracker_state:
self.tracker_state[tracker_id] = tracker_state
continue
+184
View File
@@ -0,0 +1,184 @@
import re
from enum import Enum
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
from supervision.detection.utils import polygon_to_mask, polygon_to_xyxy
class LMM(Enum):
PALIGEMMA = "paligemma"
FLORENCE_2 = "florence_2"
RESULT_TYPES: Dict[LMM, type] = {LMM.PALIGEMMA: str, LMM.FLORENCE_2: dict}
REQUIRED_ARGUMENTS: Dict[LMM, List[str]] = {
LMM.PALIGEMMA: ["resolution_wh"],
LMM.FLORENCE_2: ["resolution_wh"],
}
ALLOWED_ARGUMENTS: Dict[LMM, List[str]] = {
LMM.PALIGEMMA: ["resolution_wh", "classes"],
LMM.FLORENCE_2: ["resolution_wh"],
}
SUPPORTED_TASKS_FLORENCE_2 = [
"<OD>",
"<CAPTION_TO_PHRASE_GROUNDING>",
"<DENSE_REGION_CAPTION>",
"<REGION_PROPOSAL>",
"<OCR_WITH_REGION>",
"<REFERRING_EXPRESSION_SEGMENTATION>",
"<REGION_TO_SEGMENTATION>",
"<OPEN_VOCABULARY_DETECTION>",
"<REGION_TO_CATEGORY>",
"<REGION_TO_DESCRIPTION>",
]
def validate_lmm_parameters(
lmm: Union[LMM, str], result: Any, kwargs: Dict[str, Any]
) -> LMM:
if isinstance(lmm, str):
try:
lmm = LMM(lmm.lower())
except ValueError:
raise ValueError(
f"Invalid lmm value: {lmm}. Must be one of {[e.value for e in LMM]}"
)
if not isinstance(result, RESULT_TYPES[lmm]):
raise ValueError(
f"Invalid LMM result type: {type(result)}. Must be {RESULT_TYPES[lmm]}"
)
required_args = REQUIRED_ARGUMENTS.get(lmm, [])
for arg in required_args:
if arg not in kwargs:
raise ValueError(f"Missing required argument: {arg}")
allowed_args = ALLOWED_ARGUMENTS.get(lmm, [])
for arg in kwargs:
if arg not in allowed_args:
raise ValueError(f"Argument {arg} is not allowed for {lmm.name}")
return lmm
def from_paligemma(
result: str, resolution_wh: Tuple[int, int], classes: Optional[List[str]] = None
) -> Tuple[np.ndarray, Optional[np.ndarray], np.ndarray]:
w, h = resolution_wh
pattern = re.compile(
r"(?<!<loc\d{4}>)<loc(\d{4})><loc(\d{4})><loc(\d{4})><loc(\d{4})> ([\w\s\-]+)"
)
matches = pattern.findall(result)
matches = np.array(matches) if matches else np.empty((0, 5))
xyxy, class_name = matches[:, [1, 0, 3, 2]], matches[:, 4]
xyxy = xyxy.astype(int) / 1024 * np.array([w, h, w, h])
class_name = np.char.strip(class_name.astype(str))
class_id = None
if classes is not None:
mask = np.array([name in classes for name in class_name]).astype(bool)
xyxy, class_name = xyxy[mask], class_name[mask]
class_id = np.array([classes.index(name) for name in class_name])
return xyxy, class_id, class_name
def from_florence_2(
result: dict, resolution_wh: Tuple[int, int]
) -> Tuple[
np.ndarray, Optional[np.ndarray], Optional[np.ndarray], Optional[np.ndarray]
]:
"""
Parse results from the Florence 2 multi-model model.
https://huggingface.co/microsoft/Florence-2-large
Parameters:
result: dict containing the model output
Returns:
xyxy (np.ndarray): An array of shape `(n, 4)` containing
the bounding boxes coordinates in format `[x1, y1, x2, y2]`
labels: (Optional[np.ndarray]): An array of shape `(n,)` containing
the class labels for each bounding box
masks: (Optional[np.ndarray]): An array of shape `(n, h, w)` containing
the segmentation masks for each bounding box
obb_boxes: (Optional[np.ndarray]): An array of shape `(n, 4, 2)` containing
oriented bounding boxes.
"""
assert len(result) == 1, f"Expected result with a single element. Got: {result}"
task = list(result.keys())[0]
if task not in SUPPORTED_TASKS_FLORENCE_2:
raise ValueError(
f"{task} not supported. Supported tasks are: {SUPPORTED_TASKS_FLORENCE_2}"
)
result = result[task]
if task in ["<OD>", "<CAPTION_TO_PHRASE_GROUNDING>", "<DENSE_REGION_CAPTION>"]:
xyxy = np.array(result["bboxes"], dtype=np.float32)
labels = np.array(result["labels"])
return xyxy, labels, None, None
if task == "<REGION_PROPOSAL>":
xyxy = np.array(result["bboxes"], dtype=np.float32)
# provides labels, but they are ["", "", "", ...]
return xyxy, None, None, None
if task == "<OCR_WITH_REGION>":
xyxyxyxy = np.array(result["quad_boxes"], dtype=np.float32)
xyxyxyxy = xyxyxyxy.reshape(-1, 4, 2)
xyxy = np.array([polygon_to_xyxy(polygon) for polygon in xyxyxyxy])
labels = np.array(result["labels"])
return xyxy, labels, None, xyxyxyxy
if task in ["<REFERRING_EXPRESSION_SEGMENTATION>", "<REGION_TO_SEGMENTATION>"]:
xyxy_list = []
masks_list = []
for polygons_of_same_class in result["polygons"]:
for polygon in polygons_of_same_class:
polygon = np.reshape(polygon, (-1, 2)).astype(np.int32)
mask = polygon_to_mask(polygon, resolution_wh).astype(bool)
masks_list.append(mask)
xyxy = polygon_to_xyxy(polygon)
xyxy_list.append(xyxy)
# per-class labels also provided, but they are ["", "", "", ...]
# when we figure out how to set class names, we can do
# zip(result["labels"], result["polygons"])
xyxy = np.array(xyxy_list, dtype=np.float32)
masks = np.array(masks_list)
return xyxy, None, masks, None
if task == "<OPEN_VOCABULARY_DETECTION>":
xyxy = np.array(result["bboxes"], dtype=np.float32)
labels = np.array(result["bboxes_labels"])
# Also has "polygons" and "polygons_labels", but they don't seem to be used
return xyxy, labels, None, None
if task in ["<REGION_TO_CATEGORY>", "<REGION_TO_DESCRIPTION>"]:
assert isinstance(
result, str
), f"Expected string as <REGION_TO_CATEGORY> result, got {type(result)}"
if result == "No object detected.":
return np.empty((0, 4), dtype=np.float32), np.array([]), None, None
pattern = re.compile(r"<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>")
match = pattern.search(result)
assert (
match is not None
), f"Expected string to end in location tags, but got {result}"
w, h = resolution_wh
xyxy = np.array([match.groups()], dtype=np.float32)
xyxy *= np.array([w, h, w, h]) / 1000
result_string = result[: match.start()]
labels = np.array([result_string])
return xyxy, labels, None, None
assert False, f"Unimplemented task: {task}"
+263
View File
@@ -0,0 +1,263 @@
from enum import Enum
from typing import List, Union
import numpy as np
import numpy.typing as npt
from supervision.detection.utils import box_iou_batch, mask_iou_batch
def resize_masks(masks: np.ndarray, max_dimension: int = 640) -> np.ndarray:
"""
Resize all masks in the array to have a maximum dimension of max_dimension,
maintaining aspect ratio.
Args:
masks (np.ndarray): 3D array of binary masks with shape (N, H, W).
max_dimension (int): The maximum dimension for the resized masks.
Returns:
np.ndarray: Array of resized masks.
"""
max_height = np.max(masks.shape[1])
max_width = np.max(masks.shape[2])
scale = min(max_dimension / max_height, max_dimension / max_width)
new_height = int(scale * max_height)
new_width = int(scale * max_width)
x = np.linspace(0, max_width - 1, new_width).astype(int)
y = np.linspace(0, max_height - 1, new_height).astype(int)
xv, yv = np.meshgrid(x, y)
resized_masks = masks[:, yv, xv]
resized_masks = resized_masks.reshape(masks.shape[0], new_height, new_width)
return resized_masks
def mask_non_max_suppression(
predictions: np.ndarray,
masks: np.ndarray,
iou_threshold: float = 0.5,
mask_dimension: int = 640,
) -> np.ndarray:
"""
Perform Non-Maximum Suppression (NMS) on segmentation predictions.
Args:
predictions (np.ndarray): A 2D array of object detection predictions in
the format of `(x_min, y_min, x_max, y_max, score)`
or `(x_min, y_min, x_max, y_max, score, class)`. Shape: `(N, 5)` or
`(N, 6)`, where N is the number of predictions.
masks (np.ndarray): A 3D array of binary masks corresponding to the predictions.
Shape: `(N, H, W)`, where N is the number of predictions, and H, W are the
dimensions of each mask.
iou_threshold (float, optional): The intersection-over-union threshold
to use for non-maximum suppression.
mask_dimension (int, optional): The dimension to which the masks should be
resized before computing IOU values. Defaults to 640.
Returns:
np.ndarray: A boolean array indicating which predictions to keep after
non-maximum suppression.
Raises:
AssertionError: If `iou_threshold` is not within the closed
range from `0` to `1`.
"""
assert 0 <= iou_threshold <= 1, (
"Value of `iou_threshold` must be in the closed range from 0 to 1, "
f"{iou_threshold} given."
)
rows, columns = predictions.shape
if columns == 5:
predictions = np.c_[predictions, np.zeros(rows)]
sort_index = predictions[:, 4].argsort()[::-1]
predictions = predictions[sort_index]
masks = masks[sort_index]
masks_resized = resize_masks(masks, mask_dimension)
ious = mask_iou_batch(masks_resized, masks_resized)
categories = predictions[:, 5]
keep = np.ones(rows, dtype=bool)
for i in range(rows):
if keep[i]:
condition = (ious[i] > iou_threshold) & (categories[i] == categories)
keep[i + 1 :] = np.where(condition[i + 1 :], False, keep[i + 1 :])
return keep[sort_index.argsort()]
def box_non_max_suppression(
predictions: np.ndarray, iou_threshold: float = 0.5
) -> np.ndarray:
"""
Perform Non-Maximum Suppression (NMS) on object detection predictions.
Args:
predictions (np.ndarray): An array of object detection predictions in
the format of `(x_min, y_min, x_max, y_max, score)`
or `(x_min, y_min, x_max, y_max, score, class)`.
iou_threshold (float, optional): The intersection-over-union threshold
to use for non-maximum suppression.
Returns:
np.ndarray: A boolean array indicating which predictions to keep after n
on-maximum suppression.
Raises:
AssertionError: If `iou_threshold` is not within the
closed range from `0` to `1`.
"""
assert 0 <= iou_threshold <= 1, (
"Value of `iou_threshold` must be in the closed range from 0 to 1, "
f"{iou_threshold} given."
)
rows, columns = predictions.shape
# add column #5 - category filled with zeros for agnostic nms
if columns == 5:
predictions = np.c_[predictions, np.zeros(rows)]
# sort predictions column #4 - score
sort_index = np.flip(predictions[:, 4].argsort())
predictions = predictions[sort_index]
boxes = predictions[:, :4]
categories = predictions[:, 5]
ious = box_iou_batch(boxes, boxes)
ious = ious - np.eye(rows)
keep = np.ones(rows, dtype=bool)
for index, (iou, category) in enumerate(zip(ious, categories)):
if not keep[index]:
continue
# drop detections with iou > iou_threshold and
# same category as current detections
condition = (iou > iou_threshold) & (categories == category)
keep = keep & ~condition
return keep[sort_index.argsort()]
def group_overlapping_boxes(
predictions: npt.NDArray[np.float64], iou_threshold: float = 0.5
) -> List[List[int]]:
"""
Apply greedy version of non-maximum merging to avoid detecting too many
overlapping bounding boxes for a given object.
Args:
predictions (npt.NDArray[np.float64]): An array of shape `(n, 5)` containing
the bounding boxes coordinates in format `[x1, y1, x2, y2]`
and the confidence scores.
iou_threshold (float, optional): The intersection-over-union threshold
to use for non-maximum suppression. Defaults to 0.5.
Returns:
List[List[int]]: Groups of prediction indices be merged.
Each group may have 1 or more elements.
"""
merge_groups: List[List[int]] = []
scores = predictions[:, 4]
order = scores.argsort()
while len(order) > 0:
idx = int(order[-1])
order = order[:-1]
if len(order) == 0:
merge_groups.append([idx])
break
merge_candidate = np.expand_dims(predictions[idx], axis=0)
ious = box_iou_batch(predictions[order][:, :4], merge_candidate[:, :4])
ious = ious.flatten()
above_threshold = ious >= iou_threshold
merge_group = [idx] + np.flip(order[above_threshold]).tolist()
merge_groups.append(merge_group)
order = order[~above_threshold]
return merge_groups
def box_non_max_merge(
predictions: npt.NDArray[np.float64],
iou_threshold: float = 0.5,
) -> List[List[int]]:
"""
Apply greedy version of non-maximum merging per category to avoid detecting
too many overlapping bounding boxes for a given object.
Args:
predictions (npt.NDArray[np.float64]): An array of shape `(n, 5)` or `(n, 6)`
containing the bounding boxes coordinates in format `[x1, y1, x2, y2]`,
the confidence scores and class_ids. Omit class_id column to allow
detections of different classes to be merged.
iou_threshold (float, optional): The intersection-over-union threshold
to use for non-maximum suppression. Defaults to 0.5.
Returns:
List[List[int]]: Groups of prediction indices be merged.
Each group may have 1 or more elements.
"""
if predictions.shape[1] == 5:
return group_overlapping_boxes(predictions, iou_threshold)
category_ids = predictions[:, 5]
merge_groups = []
for category_id in np.unique(category_ids):
curr_indices = np.where(category_ids == category_id)[0]
merge_class_groups = group_overlapping_boxes(
predictions[curr_indices], iou_threshold
)
for merge_class_group in merge_class_groups:
merge_groups.append(curr_indices[merge_class_group].tolist())
for merge_group in merge_groups:
if len(merge_group) == 0:
raise ValueError(
f"Empty group detected when non-max-merging "
f"detections: {merge_groups}"
)
return merge_groups
class OverlapFilter(Enum):
"""
Enum specifying the strategy for filtering overlapping detections.
Attributes:
NONE: Do not filter detections based on overlap.
NON_MAX_SUPPRESSION: Filter detections using non-max suppression. This means,
detections that overlap by more than a set threshold will be discarded,
except for the one with the highest confidence.
NON_MAX_MERGE: Merge detections with non-max merging. This means,
detections that overlap by more than a set threshold will be merged
into a single detection.
"""
NONE = "none"
NON_MAX_SUPPRESSION = "non_max_suppression"
NON_MAX_MERGE = "non_max_merge"
def validate_overlap_filter(
strategy: Union[OverlapFilter, str],
) -> OverlapFilter:
if isinstance(strategy, str):
try:
strategy = OverlapFilter(strategy.lower())
except ValueError:
raise ValueError(
f"Invalid strategy value: {strategy}. Must be one of "
f"{[e.value for e in OverlapFilter]}"
)
return strategy
+55 -12
View File
@@ -1,23 +1,42 @@
import warnings
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Callable, Optional, Tuple
from typing import Callable, Optional, Tuple, Union
import numpy as np
from supervision.detection.core import Detections
from supervision.detection.utils import move_boxes
from supervision.detection.overlap_filter import OverlapFilter, validate_overlap_filter
from supervision.detection.utils import move_boxes, move_masks
from supervision.utils.image import crop_image
from supervision.utils.internal import SupervisionWarnings
def move_detections(detections: Detections, offset: np.array) -> Detections:
def move_detections(
detections: Detections,
offset: np.ndarray,
resolution_wh: Optional[Tuple[int, int]] = None,
) -> Detections:
"""
Args:
detections (sv.Detections): Detections object to be moved.
offset (np.array): An array of shape `(2,)` containing offset values in format
offset (np.ndarray): An array of shape `(2,)` containing offset values in format
is `[dx, dy]`.
resolution_wh (Tuple[int, int]): The width and height of the desired mask
resolution. Required for segmentation detections.
Returns:
(sv.Detections) repositioned Detections object.
"""
detections.xyxy = move_boxes(xyxy=detections.xyxy, offset=offset)
if detections.mask is not None:
if resolution_wh is None:
raise ValueError(
"Resolution width and height are required for moving segmentation "
"detections. This should be the same as (width, height) of image shape."
)
detections.mask = move_masks(
masks=detections.mask, offset=offset, resolution_wh=resolution_wh
)
return detections
@@ -34,8 +53,10 @@ class InferenceSlicer:
`(width, height)`.
overlap_ratio_wh (Tuple[float, float]): Overlap ratio between consecutive
slices in the format `(width_ratio, height_ratio)`.
iou_threshold (Optional[float]): Intersection over Union (IoU) threshold
used for non-max suppression.
overlap_filter_strategy (Union[OverlapFilter, str]): Strategy for
filtering or merging overlapping detections in slices.
iou_threshold (float): Intersection over Union (IoU) threshold
used when filtering by overlap.
callback (Callable): A function that performs inference on a given image
slice and returns detections.
thread_workers (int): Number of threads for parallel execution.
@@ -52,12 +73,18 @@ class InferenceSlicer:
callback: Callable[[np.ndarray], Detections],
slice_wh: Tuple[int, int] = (320, 320),
overlap_ratio_wh: Tuple[float, float] = (0.2, 0.2),
iou_threshold: Optional[float] = 0.5,
overlap_filter_strategy: Union[
OverlapFilter, str
] = OverlapFilter.NON_MAX_SUPPRESSION,
iou_threshold: float = 0.5,
thread_workers: int = 1,
):
overlap_filter_strategy = validate_overlap_filter(overlap_filter_strategy)
self.slice_wh = slice_wh
self.overlap_ratio_wh = overlap_ratio_wh
self.iou_threshold = iou_threshold
self.overlap_filter_strategy = overlap_filter_strategy
self.callback = callback
self.thread_workers = thread_workers
@@ -88,7 +115,10 @@ class InferenceSlicer:
result = model(image_slice)[0]
return sv.Detections.from_ultralytics(result)
slicer = sv.InferenceSlicer(callback = callback)
slicer = sv.InferenceSlicer(
callback=callback,
overlap_filter_strategy=sv.OverlapFilter.NON_MAX_SUPPRESSION,
)
detections = slicer(image)
```
@@ -108,9 +138,19 @@ class InferenceSlicer:
for future in as_completed(futures):
detections_list.append(future.result())
return Detections.merge(detections_list=detections_list).with_nms(
threshold=self.iou_threshold
)
merged = Detections.merge(detections_list=detections_list)
if self.overlap_filter_strategy == OverlapFilter.NONE:
return merged
elif self.overlap_filter_strategy == OverlapFilter.NON_MAX_SUPPRESSION:
return merged.with_nms(threshold=self.iou_threshold)
elif self.overlap_filter_strategy == OverlapFilter.NON_MAX_MERGE:
return merged.with_nmm(threshold=self.iou_threshold)
else:
warnings.warn(
f"Invalid overlap filter strategy: {self.overlap_filter_strategy}",
category=SupervisionWarnings,
)
return merged
def _run_callback(self, image, offset) -> Detections:
"""
@@ -126,7 +166,10 @@ class InferenceSlicer:
"""
image_slice = crop_image(image=image, xyxy=offset)
detections = self.callback(image_slice)
detections = move_detections(detections=detections, offset=offset[:2])
resolution_wh = (image.shape[1], image.shape[0])
detections = move_detections(
detections=detections, offset=offset[:2], resolution_wh=resolution_wh
)
return detections
+21 -10
View File
@@ -1,8 +1,10 @@
import warnings
from dataclasses import replace
from typing import Iterable, Optional, Tuple
import cv2
import numpy as np
import numpy.typing as npt
from supervision import Detections
from supervision.detection.utils import clip_boxes, polygon_to_mask
@@ -10,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:
@@ -20,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
@@ -39,22 +40,32 @@ class PolygonZone:
)
def __init__(
self,
polygon: np.ndarray,
frame_resolution_wh: Tuple[int, int],
polygon: npt.NDArray[np.int64],
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
if not list(self.triggering_anchors):
raise ValueError("Triggering anchors cannot be empty.")
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) -> np.ndarray:
def trigger(self, detections: Detections) -> npt.NDArray[np.bool_]:
"""
Determines if the detections are within the polygon zone.
@@ -78,13 +89,13 @@ class PolygonZone:
]
)
is_in_zone = (
is_in_zone: npt.NDArray[np.bool_] = (
self.mask[all_clipped_anchors[:, :, 1], all_clipped_anchors[:, :, 0]]
.transpose()
.astype(bool)
)
is_in_zone = np.all(is_in_zone, axis=1)
is_in_zone: npt.NDArray[np.bool_] = np.all(is_in_zone, axis=1)
self.current_count = int(np.sum(is_in_zone))
return is_in_zone.astype(bool)
+8 -6
View File
@@ -1,3 +1,4 @@
import warnings
from collections import defaultdict, deque
from copy import deepcopy
from typing import Optional
@@ -5,6 +6,7 @@ from typing import Optional
import numpy as np
from supervision.detection.core import Detections
from supervision.utils.internal import SupervisionWarnings
class DetectionsSmoother:
@@ -39,7 +41,7 @@ class DetectionsSmoother:
tracker = sv.ByteTrack(frame_rate=video_info.fps)
smoother = sv.DetectionsSmoother()
annotator = sv.BoundingBoxAnnotator()
box_annotator = sv.BoxAnnotator()
with sv.VideoSink(<TARGET_FILE_PATH>, video_info=video_info) as sink:
for frame in frame_generator:
@@ -48,7 +50,7 @@ class DetectionsSmoother:
detections = tracker.update_with_detections(detections)
detections = smoother.update_with_detections(detections)
annotated_frame = bounding_box_annotator.annotate(frame.copy(), detections)
annotated_frame = box_annotator.annotate(frame.copy(), detections)
sink.write_frame(annotated_frame)
```
""" # noqa: E501 // docs
@@ -70,16 +72,16 @@ class DetectionsSmoother:
"""
if detections.tracker_id is None:
print(
warnings.warn(
"Smoothing skipped. DetectionsSmoother requires tracker_id. Refer to "
"https://supervision.roboflow.com/latest/trackers for more information."
"https://supervision.roboflow.com/latest/trackers for more "
"information.",
category=SupervisionWarnings,
)
return detections
for detection_idx in range(len(detections)):
tracker_id = detections.tracker_id[detection_idx]
if tracker_id is None:
continue
self.tracks[tracker_id].append(detections[detection_idx])
+361 -271
View File
@@ -1,10 +1,12 @@
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
import numpy.typing as npt
from supervision.config import CLASS_NAME_DATA_FIELD
from supervision.geometry.core import Vector
MIN_POLYGON_POINT_COUNT = 3
@@ -56,7 +58,9 @@ def box_iou_batch(boxes_true: np.ndarray, boxes_detection: np.ndarray) -> np.nda
bottom_right = np.minimum(boxes_true[:, None, 2:], boxes_detection[:, 2:])
area_inter = np.prod(np.clip(bottom_right - top_left, a_min=0, a_max=None), 2)
return area_inter / (area_true[:, None] + area_detection - area_inter)
ious = area_inter / (area_true[:, None] + area_detection - area_inter)
ious = np.nan_to_num(ious)
return ious
def _mask_iou_batch_split(
@@ -136,144 +140,6 @@ def mask_iou_batch(
return np.vstack(ious)
def resize_masks(masks: np.ndarray, max_dimension: int = 640) -> np.ndarray:
"""
Resize all masks in the array to have a maximum dimension of max_dimension,
maintaining aspect ratio.
Args:
masks (np.ndarray): 3D array of binary masks with shape (N, H, W).
max_dimension (int): The maximum dimension for the resized masks.
Returns:
np.ndarray: Array of resized masks.
"""
max_height = np.max(masks.shape[1])
max_width = np.max(masks.shape[2])
scale = min(max_dimension / max_height, max_dimension / max_width)
new_height = int(scale * max_height)
new_width = int(scale * max_width)
x = np.linspace(0, max_width - 1, new_width).astype(int)
y = np.linspace(0, max_height - 1, new_height).astype(int)
xv, yv = np.meshgrid(x, y)
resized_masks = masks[:, yv, xv]
resized_masks = resized_masks.reshape(masks.shape[0], new_height, new_width)
return resized_masks
def mask_non_max_suppression(
predictions: np.ndarray,
masks: np.ndarray,
iou_threshold: float = 0.5,
mask_dimension: int = 640,
) -> np.ndarray:
"""
Perform Non-Maximum Suppression (NMS) on segmentation predictions.
Args:
predictions (np.ndarray): A 2D array of object detection predictions in
the format of `(x_min, y_min, x_max, y_max, score)`
or `(x_min, y_min, x_max, y_max, score, class)`. Shape: `(N, 5)` or
`(N, 6)`, where N is the number of predictions.
masks (np.ndarray): A 3D array of binary masks corresponding to the predictions.
Shape: `(N, H, W)`, where N is the number of predictions, and H, W are the
dimensions of each mask.
iou_threshold (float, optional): The intersection-over-union threshold
to use for non-maximum suppression.
mask_dimension (int, optional): The dimension to which the masks should be
resized before computing IOU values. Defaults to 640.
Returns:
np.ndarray: A boolean array indicating which predictions to keep after
non-maximum suppression.
Raises:
AssertionError: If `iou_threshold` is not within the closed
range from `0` to `1`.
"""
assert 0 <= iou_threshold <= 1, (
"Value of `iou_threshold` must be in the closed range from 0 to 1, "
f"{iou_threshold} given."
)
rows, columns = predictions.shape
if columns == 5:
predictions = np.c_[predictions, np.zeros(rows)]
sort_index = predictions[:, 4].argsort()[::-1]
predictions = predictions[sort_index]
masks = masks[sort_index]
masks_resized = resize_masks(masks, mask_dimension)
ious = mask_iou_batch(masks_resized, masks_resized)
categories = predictions[:, 5]
keep = np.ones(rows, dtype=bool)
for i in range(rows):
if keep[i]:
condition = (ious[i] > iou_threshold) & (categories[i] == categories)
keep[i + 1 :] = np.where(condition[i + 1 :], False, keep[i + 1 :])
return keep[sort_index.argsort()]
def box_non_max_suppression(
predictions: np.ndarray, iou_threshold: float = 0.5
) -> np.ndarray:
"""
Perform Non-Maximum Suppression (NMS) on object detection predictions.
Args:
predictions (np.ndarray): An array of object detection predictions in
the format of `(x_min, y_min, x_max, y_max, score)`
or `(x_min, y_min, x_max, y_max, score, class)`.
iou_threshold (float, optional): The intersection-over-union threshold
to use for non-maximum suppression.
Returns:
np.ndarray: A boolean array indicating which predictions to keep after n
on-maximum suppression.
Raises:
AssertionError: If `iou_threshold` is not within the
closed range from `0` to `1`.
"""
assert 0 <= iou_threshold <= 1, (
"Value of `iou_threshold` must be in the closed range from 0 to 1, "
f"{iou_threshold} given."
)
rows, columns = predictions.shape
# add column #5 - category filled with zeros for agnostic nms
if columns == 5:
predictions = np.c_[predictions, np.zeros(rows)]
# sort predictions column #4 - score
sort_index = np.flip(predictions[:, 4].argsort())
predictions = predictions[sort_index]
boxes = predictions[:, :4]
categories = predictions[:, 5]
ious = box_iou_batch(boxes, boxes)
ious = ious - np.eye(rows)
keep = np.ones(rows, dtype=bool)
for index, (iou, category) in enumerate(zip(ious, categories)):
if not keep[index]:
continue
# drop detections with iou > iou_threshold and
# same category as current detections
condition = (iou > iou_threshold) & (categories == category)
keep = keep & ~condition
return keep[sort_index.argsort()]
def clip_boxes(xyxy: np.ndarray, resolution_wh: Tuple[int, int]) -> np.ndarray:
"""
Clips bounding boxes coordinates to fit within the frame resolution.
@@ -289,6 +155,25 @@ def clip_boxes(xyxy: np.ndarray, resolution_wh: Tuple[int, int]) -> np.ndarray:
np.ndarray: A numpy array of shape `(N, 4)` where each row
corresponds to a bounding box with coordinates clipped to fit
within the frame resolution.
Examples:
```python
import numpy as np
import supervision as sv
xyxy = np.array([
[10, 20, 300, 200],
[15, 25, 350, 450],
[-10, -20, 30, 40]
])
sv.clip_boxes(xyxy=xyxy, resolution_wh=(320, 240))
# array([
# [ 10, 20, 300, 200],
# [ 15, 25, 320, 240],
# [ 0, 0, 30, 40]
# ])
```
"""
result = np.copy(xyxy)
width, height = resolution_wh
@@ -297,10 +182,124 @@ def clip_boxes(xyxy: np.ndarray, resolution_wh: Tuple[int, int]) -> np.ndarray:
return result
def xywh_to_xyxy(boxes_xywh: np.ndarray) -> np.ndarray:
xyxy = boxes_xywh.copy()
xyxy[:, 2] = boxes_xywh[:, 0] + boxes_xywh[:, 2]
xyxy[:, 3] = boxes_xywh[:, 1] + boxes_xywh[:, 3]
def pad_boxes(xyxy: np.ndarray, px: int, py: Optional[int] = None) -> np.ndarray:
"""
Pads bounding boxes coordinates with a constant padding.
Args:
xyxy (np.ndarray): A numpy array of shape `(N, 4)` where each
row corresponds to a bounding box in the format
`(x_min, y_min, x_max, y_max)`.
px (int): The padding value to be added to both the left and right sides of
each bounding box.
py (Optional[int]): The padding value to be added to both the top and bottom
sides of each bounding box. If not provided, `px` will be used for both
dimensions.
Returns:
np.ndarray: A numpy array of shape `(N, 4)` where each row corresponds to a
bounding box with coordinates padded according to the provided padding
values.
Examples:
```python
import numpy as np
import supervision as sv
xyxy = np.array([
[10, 20, 30, 40],
[15, 25, 35, 45]
])
sv.pad_boxes(xyxy=xyxy, px=5, py=10)
# array([
# [ 5, 10, 35, 50],
# [10, 15, 40, 55]
# ])
```
"""
if py is None:
py = px
result = xyxy.copy()
result[:, [0, 1]] -= [px, py]
result[:, [2, 3]] += [px, py]
return result
def xywh_to_xyxy(xywh: np.ndarray) -> np.ndarray:
"""
Converts bounding box coordinates from `(x, y, width, height)`
format to `(x_min, y_min, x_max, y_max)` format.
Args:
xywh (np.ndarray): A numpy array of shape `(N, 4)` where each row
corresponds to a bounding box in the format `(x, y, width, height)`.
Returns:
np.ndarray: A numpy array of shape `(N, 4)` where each row corresponds
to a bounding box in the format `(x_min, y_min, x_max, y_max)`.
Examples:
```python
import numpy as np
import supervision as sv
xywh = np.array([
[10, 20, 30, 40],
[15, 25, 35, 45]
])
sv.xywh_to_xyxy(xywh=xywh)
# array([
# [10, 20, 40, 60],
# [15, 25, 50, 70]
# ])
```
"""
xyxy = xywh.copy()
xyxy[:, 2] = xywh[:, 0] + xywh[:, 2]
xyxy[:, 3] = xywh[:, 1] + xywh[:, 3]
return xyxy
def xcycwh_to_xyxy(xcycwh: np.ndarray) -> np.ndarray:
"""
Converts bounding box coordinates from `(center_x, center_y, width, height)`
format to `(x_min, y_min, x_max, y_max)` format.
Args:
xcycwh (np.ndarray): A numpy array of shape `(N, 4)` where each row
corresponds to a bounding box in the format `(center_x, center_y, width,
height)`.
Returns:
np.ndarray: A numpy array of shape `(N, 4)` where each row corresponds
to a bounding box in the format `(x_min, y_min, x_max, y_max)`.
Examples:
```python
import numpy as np
import supervision as sv
xcycwh = np.array([
[50, 50, 20, 30],
[30, 40, 10, 15]
])
sv.xcycwh_to_xyxy(xcycwh=xcycwh)
# array([
# [40, 35, 60, 65],
# [25, 32.5, 35, 47.5]
# ])
```
"""
xyxy = xcycwh.copy()
xyxy[:, 0] = xcycwh[:, 0] - xcycwh[:, 2] / 2
xyxy[:, 1] = xcycwh[:, 1] - xcycwh[:, 3] / 2
xyxy[:, 2] = xcycwh[:, 0] + xcycwh[:, 2] / 2
xyxy[:, 3] = xcycwh[:, 1] + xcycwh[:, 3] / 2
return xyxy
@@ -317,7 +316,7 @@ def mask_to_xyxy(masks: np.ndarray) -> np.ndarray:
`(x_min, y_min, x_max, y_max)` for each mask
"""
n = masks.shape[0]
bboxes = np.zeros((n, 4), dtype=int)
xyxy = np.zeros((n, 4), dtype=int)
for i, mask in enumerate(masks):
rows, cols = np.where(mask)
@@ -325,9 +324,9 @@ def mask_to_xyxy(masks: np.ndarray) -> np.ndarray:
if len(rows) > 0 and len(cols) > 0:
x_min, x_max = np.min(cols), np.max(cols)
y_min, y_max = np.min(rows), np.max(rows)
bboxes[i, :] = [x_min, y_min, x_max, y_max]
xyxy[i, :] = [x_min, y_min, x_max, y_max]
return bboxes
return xyxy
def mask_to_polygons(mask: np.ndarray) -> List[np.ndarray]:
@@ -500,7 +499,7 @@ def process_roboflow_result(
np.ndarray,
Optional[np.ndarray],
Optional[np.ndarray],
Dict[str, List[np.ndarray]],
Dict[str, Union[List[np.ndarray], np.ndarray]],
]:
if not roboflow_result["predictions"]:
return (
@@ -563,59 +562,103 @@ def process_roboflow_result(
return xyxy, confidence, class_id, masks, tracker_id, data
def move_boxes(xyxy: np.ndarray, offset: np.ndarray) -> np.ndarray:
def move_boxes(
xyxy: npt.NDArray[np.float64], offset: npt.NDArray[np.int32]
) -> npt.NDArray[np.float64]:
"""
Parameters:
xyxy (np.ndarray): An array of shape `(n, 4)` containing the bounding boxes
coordinates in format `[x1, y1, x2, y2]`
xyxy (npt.NDArray[np.float64]): An array of shape `(n, 4)` containing the
bounding boxes coordinates in format `[x1, y1, x2, y2]`
offset (np.array): An array of shape `(2,)` containing offset values in format
is `[dx, dy]`.
Returns:
np.ndarray: Repositioned bounding boxes.
npt.NDArray[np.float64]: Repositioned bounding boxes.
Example:
Examples:
```python
import numpy as np
import supervision as sv
boxes = np.array([[10, 10, 20, 20], [30, 30, 40, 40]])
xyxy = np.array([
[10, 10, 20, 20],
[30, 30, 40, 40]
])
offset = np.array([5, 5])
moved_box = sv.move_boxes(boxes, offset)
print(moved_box)
# np.array([
sv.move_boxes(xyxy=xyxy, offset=offset)
# array([
# [15, 15, 25, 25],
# [35, 35, 45, 45]
# [35, 35, 45, 45]
# ])
```
"""
return xyxy + np.hstack([offset, offset])
def scale_boxes(xyxy: np.ndarray, factor: float) -> np.ndarray:
def move_masks(
masks: npt.NDArray[np.bool_],
offset: npt.NDArray[np.int32],
resolution_wh: Tuple[int, int],
) -> npt.NDArray[np.bool_]:
"""
Offset the masks in an array by the specified (x, y) amount.
Args:
masks (npt.NDArray[np.bool_]): A 3D array of binary masks corresponding to the
predictions. Shape: `(N, H, W)`, where N is the number of predictions, and
H, W are the dimensions of each mask.
offset (npt.NDArray[np.int32]): An array of shape `(2,)` containing non-negative
int values `[dx, dy]`.
resolution_wh (Tuple[int, int]): The width and height of the desired mask
resolution.
Returns:
(npt.NDArray[np.bool_]) repositioned masks, optionally padded to the specified
shape.
"""
if offset[0] < 0 or offset[1] < 0:
raise ValueError(f"Offset values must be non-negative integers. Got: {offset}")
mask_array = np.full((masks.shape[0], resolution_wh[1], resolution_wh[0]), False)
mask_array[
:,
offset[1] : masks.shape[1] + offset[1],
offset[0] : masks.shape[2] + offset[0],
] = masks
return mask_array
def scale_boxes(
xyxy: npt.NDArray[np.float64], factor: float
) -> npt.NDArray[np.float64]:
"""
Scale the dimensions of bounding boxes.
Parameters:
xyxy (np.ndarray): An array of shape `(n, 4)` containing the bounding boxes
coordinates in format `[x1, y1, x2, y2]`
xyxy (npt.NDArray[np.float64]): An array of shape `(n, 4)` containing the
bounding boxes coordinates in format `[x1, y1, x2, y2]`
factor (float): A float value representing the factor by which the box
dimensions are scaled. A factor greater than 1 enlarges the boxes, while a
factor less than 1 shrinks them.
Returns:
np.ndarray: Scaled bounding boxes.
npt.NDArray[np.float64]: Scaled bounding boxes.
Example:
Examples:
```python
import numpy as np
import supervision as sv
boxes = np.array([[10, 10, 20, 20], [30, 30, 40, 40]])
factor = 1.5
scaled_bb = sv.scale_boxes(boxes, factor)
print(scaled_bb)
# np.array([
xyxy = np.array([
[10, 10, 20, 20],
[30, 30, 40, 40]
])
sv.scale_boxes(xyxy=xyxy, factor=1.5)
# array([
# [ 7.5, 7.5, 22.5, 22.5],
# [27.5, 27.5, 42.5, 42.5]
# ])
@@ -656,102 +699,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.
@@ -768,17 +715,19 @@ def is_data_equal(data_a: Dict[str, np.ndarray], data_b: Dict[str, np.ndarray])
def merge_data(
data_list: List[Dict[str, Union[np.ndarray, List]]],
) -> Dict[str, Union[np.ndarray, List]]:
data_list: List[Dict[str, Union[npt.NDArray[np.generic], List]]],
) -> Dict[str, Union[npt.NDArray[np.generic], List]]:
"""
Merges the data payloads of a list of Detections instances.
Args:
data_list: The data payloads of the instances.
data_list: The data payloads of the Detections instances. Each data payload
is a dictionary with the same keys, and the values are either lists or
npt.NDArray[np.generic].
Returns:
A single data payload containing the merged data, preserving the original data
types (list or np.ndarray).
types (list or npt.NDArray[np.generic]).
Raises:
ValueError: If data values within a single object have different lengths or if
@@ -799,9 +748,8 @@ def merge_data(
)
merged_data = {key: [] for key in all_keys_sets[0]}
for data in data_list:
for key in merged_data:
for key in data:
merged_data[key].append(data[key])
for key in merged_data:
@@ -845,8 +793,15 @@ def get_data_item(
elif isinstance(value, list):
if isinstance(index, slice):
subset_data[key] = value[index]
elif isinstance(index, (list, np.ndarray)):
elif isinstance(index, list):
subset_data[key] = [value[i] for i in index]
elif isinstance(index, np.ndarray):
if index.dtype == bool:
subset_data[key] = [
value[i] for i, index_value in enumerate(index) if index_value
]
else:
subset_data[key] = [value[i] for i in index]
elif isinstance(index, int):
subset_data[key] = [value[index]]
else:
@@ -855,3 +810,138 @@ def get_data_item(
raise TypeError(f"Unsupported data type for key '{key}': {type(value)}")
return subset_data
def contains_holes(mask: npt.NDArray[np.bool_]) -> bool:
"""
Checks if the binary mask contains holes (background pixels fully enclosed by
foreground pixels).
Args:
mask (npt.NDArray[np.bool_]): 2D binary mask where `True` indicates foreground
object and `False` indicates background.
Returns:
True if holes are detected, False otherwise.
Examples:
```python
import numpy as np
import supervision as sv
mask = np.array([
[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 1, 0, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0]
]).astype(bool)
sv.contains_holes(mask=mask)
# True
mask = np.array([
[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0]
]).astype(bool)
sv.contains_holes(mask=mask)
# False
```
![contains_holes](https://media.roboflow.com/supervision-docs/contains-holes.png){ align=center width="800" }
""" # noqa E501 // docs
mask_uint8 = mask.astype(np.uint8)
_, hierarchy = cv2.findContours(mask_uint8, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
if hierarchy is not None:
parent_contour_index = 3
for h in hierarchy[0]:
if h[parent_contour_index] != -1:
return True
return False
def contains_multiple_segments(
mask: npt.NDArray[np.bool_], connectivity: int = 4
) -> bool:
"""
Checks if the binary mask contains multiple unconnected foreground segments.
Args:
mask (npt.NDArray[np.bool_]): 2D binary mask where `True` indicates foreground
object and `False` indicates background.
connectivity (int) : Default: 4 is 4-way connectivity, which means that
foreground pixels are the part of the same segment/component
if their edges touch.
Alternatively: 8 for 8-way connectivity, when foreground pixels are
connected by their edges or corners touch.
Returns:
True when the mask contains multiple not connected components, False otherwise.
Raises:
ValueError: If connectivity(int) parameter value is not 4 or 8.
Examples:
```python
import numpy as np
import supervision as sv
mask = np.array([
[0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 1, 1],
[0, 1, 1, 0, 1, 1],
[0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 0, 0]
]).astype(bool)
sv.contains_multiple_segments(mask=mask, connectivity=4)
# True
mask = np.array([
[0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 0]
]).astype(bool)
sv.contains_multiple_segments(mask=mask, connectivity=4)
# False
```
![contains_multiple_segments](https://media.roboflow.com/supervision-docs/contains-multiple-segments.png){ align=center width="800" }
""" # noqa E501 // docs
if connectivity != 4 and connectivity != 8:
raise ValueError(
"Incorrect connectivity value. Possible connectivity values: 4 or 8."
)
mask_uint8 = mask.astype(np.uint8)
labels = np.zeros_like(mask_uint8, dtype=np.int32)
number_of_labels, _ = cv2.connectedComponents(
mask_uint8, labels, connectivity=connectivity
)
return number_of_labels > 2
def cross_product(anchors: np.ndarray, vector: Vector) -> np.ndarray:
"""
Get array of cross products of each anchor with a vector.
Args:
anchors: Array of anchors of shape (number of anchors, detections, 2)
vector: Vector to calculate cross product with
Returns:
Array of cross products of shape (number of anchors, detections)
"""
vector_at_zero = np.array(
[vector.end.x - vector.start.x, vector.end.y - vector.start.y]
)
vector_start = np.array([vector.start.x, vector.start.y])
return np.cross(vector_at_zero, anchors - vector_start)
+79 -78
View File
@@ -1,11 +1,11 @@
from __future__ import annotations
from dataclasses import dataclass
from typing import List, Tuple
from typing import List, Tuple, Union
import matplotlib.pyplot as plt
from supervision.utils.internal import classproperty, deprecated
from supervision.utils.internal import classproperty
DEFAULT_COLOR_PALETTE = [
"A351FB",
@@ -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.
@@ -176,73 +228,33 @@ class Color:
return self.b, self.g, self.r
@classproperty
def WHITE(cls):
def WHITE(cls) -> Color:
return Color.from_hex("#FFFFFF")
@classproperty
def BLACK(cls):
def BLACK(cls) -> Color:
return Color.from_hex("#000000")
@classproperty
def RED(cls):
def RED(cls) -> Color:
return Color.from_hex("#FF0000")
@classproperty
def GREEN(cls):
def GREEN(cls) -> Color:
return Color.from_hex("#00FF00")
@classproperty
def BLUE(cls):
def BLUE(cls) -> Color:
return Color.from_hex("#0000FF")
@classproperty
def YELLOW(cls):
def YELLOW(cls) -> Color:
return Color.from_hex("#FFFF00")
@classproperty
def ROBOFLOW(cls):
def ROBOFLOW(cls) -> Color:
return Color.from_hex("#A351FB")
@classmethod
@deprecated(
"`Color.white()` is deprecated and will be removed in "
"`supervision-0.22.0`. Use `Color.WHITE` instead."
)
def white(cls) -> Color:
return Color.from_hex(color_hex="#ffffff")
@classmethod
@deprecated(
"`Color.black()` is deprecated and will be removed in "
"`supervision-0.22.0`. Use `Color.BLACK` instead."
)
def black(cls) -> Color:
return Color.from_hex(color_hex="#000000")
@classmethod
@deprecated(
"`Color.red()` is deprecated and will be removed in "
"`supervision-0.22.0`. Use `Color.RED` instead."
)
def red(cls) -> Color:
return Color.from_hex(color_hex="#ff0000")
@classmethod
@deprecated(
"`Color.green()` is deprecated and will be removed in "
"`supervision-0.22.0`. Use `Color.GREEN` instead."
)
def green(cls) -> Color:
return Color.from_hex(color_hex="#00ff00")
@classmethod
@deprecated(
"`Color.blue()` is deprecated and will be removed in "
"`supervision-0.22.0`. Use `Color.BLUE` instead."
)
def blue(cls) -> Color:
return Color.from_hex(color_hex="#0000ff")
@dataclass
class ColorPalette:
@@ -294,33 +306,6 @@ class ColorPalette:
def LEGACY(cls) -> ColorPalette:
return ColorPalette.from_hex(color_hex_list=LEGACY_COLOR_PALETTE)
@classmethod
@deprecated(
"`ColorPalette.default()` is deprecated and will be removed in "
"`supervision-0.22.0`. Use `Color.DEFAULT` instead."
)
def default(cls) -> ColorPalette:
"""
!!! failure "Deprecated"
`ColorPalette.default()` is deprecated and will be removed in
`supervision-0.22.0`. Use `Color.DEFAULT` instead.
Returns a default color palette.
Returns:
ColorPalette: A ColorPalette instance with default colors.
Example:
```python
import supervision as sv
sv.ColorPalette.default()
# ColorPalette(colors=[Color(r=255, g=64, b=64), Color(r=255, g=161, b=160), ...])
```
""" # noqa: E501 // docs
return ColorPalette.from_hex(color_hex_list=DEFAULT_COLOR_PALETTE)
@classmethod
def from_hex(cls, color_hex_list: List[str]) -> ColorPalette:
"""
@@ -396,3 +381,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
+61 -17
View File
@@ -81,6 +81,58 @@ def draw_filled_rectangle(scene: np.ndarray, rect: Rect, color: Color) -> np.nda
return scene
def draw_rounded_rectangle(
scene: np.ndarray,
rect: Rect,
color: Color,
border_radius: int,
) -> np.ndarray:
"""
Draws a rounded rectangle on an image.
Parameters:
scene (np.ndarray): The image on which the rounded rectangle will be drawn.
rect (Rect): The rectangle to be drawn.
color (Color): The color of the rounded rectangle.
border_radius (int): The radius of the corner rounding.
Returns:
np.ndarray: The image with the rounded rectangle drawn on it.
"""
x1, y1, x2, y2 = rect.as_xyxy_int_tuple()
width, height = x2 - x1, y2 - y1
border_radius = min(border_radius, min(width, height) // 2)
rectangle_coordinates = [
((x1 + border_radius, y1), (x2 - border_radius, y2)),
((x1, y1 + border_radius), (x2, y2 - border_radius)),
]
circle_centers = [
(x1 + border_radius, y1 + border_radius),
(x2 - border_radius, y1 + border_radius),
(x1 + border_radius, y2 - border_radius),
(x2 - border_radius, y2 - border_radius),
]
for coordinates in rectangle_coordinates:
cv2.rectangle(
img=scene,
pt1=coordinates[0],
pt2=coordinates[1],
color=color.as_bgr(),
thickness=-1,
)
for center in circle_centers:
cv2.circle(
img=scene,
center=center,
radius=border_radius,
color=color.as_bgr(),
thickness=-1,
)
return scene
def draw_polygon(
scene: np.ndarray, polygon: np.ndarray, color: Color, thickness: int = 2
) -> np.ndarray:
@@ -238,13 +290,13 @@ def draw_image(
return scene
def calculate_dynamic_text_scale(resolution_wh: Tuple[int, int]) -> float:
def calculate_optimal_text_scale(resolution_wh: Tuple[int, int]) -> float:
"""
Calculate a dynamic font scale based on the resolution of an image.
Calculate font scale based on the resolution of an image.
Parameters:
resolution_wh (Tuple[int, int]): A tuple representing the width and height
of the image.
resolution_wh (Tuple[int, int]): A tuple representing the width and height
of the image.
Returns:
float: The calculated font scale factor.
@@ -252,25 +304,17 @@ def calculate_dynamic_text_scale(resolution_wh: Tuple[int, int]) -> float:
return min(resolution_wh) * 1e-3
def calculate_dynamic_line_thickness(resolution_wh: Tuple[int, int]) -> int:
def calculate_optimal_line_thickness(resolution_wh: Tuple[int, int]) -> int:
"""
Calculate a dynamic line thickness based on the resolution of an image.
Calculate line thickness based on the resolution of an image.
Parameters:
resolution_wh (Tuple[int, int]): A tuple representing the width and height
of the image.
of the image.
Returns:
int: The calculated line thickness in pixels.
"""
min_dimension = min(resolution_wh)
if min_dimension < 480:
if min(resolution_wh) < 1080:
return 2
if min_dimension < 720:
return 2
if min_dimension < 1080:
return 2
if min_dimension < 2160:
return 4
else:
return 4
return 4
+13
View File
@@ -98,6 +98,11 @@ class Rect:
width: float
height: float
@classmethod
def from_xyxy(cls, xyxy: Tuple[float, float, float, float]) -> Rect:
x1, y1, x2, y2 = xyxy
return cls(x=x1, y=y1, width=x2 - x1, height=y2 - y1)
@property
def top_left(self) -> Point:
return Point(x=self.x, y=self.y)
@@ -113,3 +118,11 @@ class Rect:
width=self.width + 2 * padding,
height=self.height + 2 * padding,
)
def as_xyxy_int_tuple(self) -> Tuple[int, int, int, int]:
return (
int(self.x),
int(self.y),
int(self.x + self.width),
int(self.y + self.height),
)
+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
+418
View File
@@ -0,0 +1,418 @@
from abc import ABC, abstractmethod
from logging import warn
from typing import List, Optional, Tuple, Union
import cv2
import numpy as np
from supervision import Rect, pad_boxes
from supervision.annotators.base import ImageType
from supervision.draw.color import Color
from supervision.draw.utils import draw_rounded_rectangle
from supervision.keypoint.core import KeyPoints
from supervision.keypoint.skeletons import SKELETONS_BY_VERTEX_COUNT
from supervision.utils.conversion import ensure_cv2_image_for_annotation
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
@ensure_cv2_image_for_annotation
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 skeleton vertices 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
@ensure_cv2_image_for_annotation
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 skeleton edges 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
class VertexLabelAnnotator:
"""
A class that draws labels of skeleton vertices on images. It uses specified key
points to determine the locations where the vertices should be drawn.
"""
def __init__(
self,
color: Union[Color, List[Color]] = Color.ROBOFLOW,
text_color: Color = Color.WHITE,
text_scale: float = 0.5,
text_thickness: int = 1,
text_padding: int = 10,
border_radius: int = 0,
):
"""
Args:
color (Union[Color, List[Color]], optional): The color to use for each
keypoint label. If a list is provided, the colors will be used in order
for each keypoint.
text_color (Color, optional): The color to use for the labels.
text_scale (float, optional): The scale of the text.
text_thickness (int, optional): The thickness of the text.
text_padding (int, optional): The padding around the text.
border_radius (int, optional): The radius of the rounded corners of the
boxes. Set to a high value to produce circles.
"""
self.border_radius: int = border_radius
self.color: Union[Color, List[Color]] = color
self.text_color: Color = text_color
self.text_scale: float = text_scale
self.text_thickness: int = text_thickness
self.text_padding: int = text_padding
def annotate(
self, scene: ImageType, key_points: KeyPoints, labels: List[str] = None
) -> ImageType:
"""
A class that draws labels of skeleton vertices on images. It uses specified key
points to determine the locations where the vertices should be drawn.
Args:
scene (ImageType): The image where vertex labels 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.
labels (List[str], optional): A list of labels to be displayed on the
annotated image. If not provided, keypoint indices will be used.
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_label_annotator = sv.VertexLabelAnnotator(
color=sv.Color.GREEN,
text_color=sv.Color.BLACK,
border_radius=5
)
annotated_frame = vertex_label_annotator.annotate(
scene=image.copy(),
key_points=key_points
)
```
![vertex-label-annotator-example](https://media.roboflow.com/
supervision-annotator-examples/vertex-label-annotator-example.png)
!!! tip
`VertexLabelAnnotator` allows to customize the color of each keypoint label
values.
Example:
```python
import supervision as sv
image = ...
key_points = sv.KeyPoints(...)
LABELS = [
"nose", "left eye", "right eye", "left ear",
"right ear", "left shoulder", "right shoulder", "left elbow",
"right elbow", "left wrist", "right wrist", "left hip",
"right hip", "left knee", "right knee", "left ankle",
"right ankle"
]
COLORS = [
"#FF6347", "#FF6347", "#FF6347", "#FF6347",
"#FF6347", "#FF1493", "#00FF00", "#FF1493",
"#00FF00", "#FF1493", "#00FF00", "#FFD700",
"#00BFFF", "#FFD700", "#00BFFF", "#FFD700",
"#00BFFF"
]
COLORS = [sv.Color.from_hex(color_hex=c) for c in COLORS]
vertex_label_annotator = sv.VertexLabelAnnotator(
color=COLORS,
text_color=sv.Color.BLACK,
border_radius=5
)
annotated_frame = vertex_label_annotator.annotate(
scene=image.copy(),
key_points=key_points,
labels=labels
)
```
![vertex-label-annotator-custom-example](https://media.roboflow.com/
supervision-annotator-examples/vertex-label-annotator-custom-example.png)
"""
font = cv2.FONT_HERSHEY_SIMPLEX
skeletons_count, points_count, _ = key_points.xy.shape
if skeletons_count == 0:
return scene
anchors = key_points.xy.reshape(points_count * skeletons_count, 2).astype(int)
mask = np.all(anchors != 0, axis=1)
if not np.any(mask):
return scene
colors = self.preprocess_and_validate_colors(
colors=self.color,
points_count=points_count,
skeletons_count=skeletons_count,
)
labels = self.preprocess_and_validate_labels(
labels=labels, points_count=points_count, skeletons_count=skeletons_count
)
anchors = anchors[mask]
colors = colors[mask]
labels = labels[mask]
xyxy = np.array(
[
self.get_text_bounding_box(
text=label,
font=font,
text_scale=self.text_scale,
text_thickness=self.text_thickness,
center_coordinates=tuple(anchor),
)
for anchor, label in zip(anchors, labels)
]
)
xyxy_padded = pad_boxes(xyxy=xyxy, px=self.text_padding)
for text, color, box, box_padded in zip(labels, colors, xyxy, xyxy_padded):
draw_rounded_rectangle(
scene=scene,
rect=Rect.from_xyxy(box_padded),
color=color,
border_radius=self.border_radius,
)
cv2.putText(
img=scene,
text=text,
org=(box[0], box[1] + self.text_padding),
fontFace=font,
fontScale=self.text_scale,
color=self.text_color.as_rgb(),
thickness=self.text_thickness,
lineType=cv2.LINE_AA,
)
return scene
@staticmethod
def get_text_bounding_box(
text: str,
font: int,
text_scale: float,
text_thickness: int,
center_coordinates: Tuple[int, int],
) -> Tuple[int, int, int, int]:
text_w, text_h = cv2.getTextSize(
text=text,
fontFace=font,
fontScale=text_scale,
thickness=text_thickness,
)[0]
center_x, center_y = center_coordinates
return (
center_x - text_w // 2,
center_y - text_h // 2,
center_x + text_w // 2,
center_y + text_h // 2,
)
@staticmethod
def preprocess_and_validate_labels(
labels: Optional[List[str]], points_count: int, skeletons_count: int
) -> np.array:
if labels and len(labels) != points_count:
raise ValueError(
f"Number of labels ({len(labels)}) must match number of key points "
f"({points_count})."
)
if labels is None:
labels = [str(i) for i in range(points_count)]
return np.array(labels * skeletons_count)
@staticmethod
def preprocess_and_validate_colors(
colors: Optional[Union[Color, List[Color]]],
points_count: int,
skeletons_count: int,
) -> np.array:
if isinstance(colors, list) and len(colors) != points_count:
raise ValueError(
f"Number of colors ({len(colors)}) must match number of key points "
f"({points_count})."
)
return (
np.array(colors * skeletons_count)
if isinstance(colors, list)
else np.array([colors] * points_count * skeletons_count)
)
+612
View File
@@ -0,0 +1,612 @@
from __future__ import annotations
from contextlib import suppress
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 [keypoints annotators](/keypoint/annotators).
=== "Ultralytics"
Use [`sv.KeyPoints.from_ultralytics`](/keypoint/core/#supervision.keypoint.core.KeyPoints.from_ultralytics)
method, which accepts [YOLOv8](https://github.com/ultralytics/ultralytics)
pose result.
```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)
```
=== "Inference"
Use [`sv.KeyPoints.from_inference`](/keypoint/core/#supervision.keypoint.core.KeyPoints.from_inference)
method, which accepts [Inference](https://inference.roboflow.com/) pose result.
```python
import cv2
import supervision as sv
from inference import get_model
image = cv2.imread(<SOURCE_IMAGE_PATH>)
model = get_model(model_id=<POSE_MODEL_ID>, api_key=<ROBOFLOW_API_KEY>)
result = model.infer(image)[0]
key_points = sv.KeyPoints.from_inference(result)
```
=== "MediaPipe"
Use [`sv.KeyPoints.from_mediapipe`](/keypoint/core/#supervision.keypoint.core.KeyPoints.from_mediapipe)
method, which accepts [MediaPipe](https://github.com/google-ai-edge/mediapipe)
pose result.
```python
import cv2
import mediapipe as mp
import supervision as sv
image = cv2.imread(<SOURCE_IMAGE_PATH>)
image_height, image_width, _ = image.shape
mediapipe_image = mp.Image(
image_format=mp.ImageFormat.SRGB,
data=cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
options = mp.tasks.vision.PoseLandmarkerOptions(
base_options=mp.tasks.BaseOptions(
model_asset_path="pose_landmarker_heavy.task"
),
running_mode=mp.tasks.vision.RunningMode.IMAGE,
num_poses=2)
PoseLandmarker = mp.tasks.vision.PoseLandmarker
with PoseLandmarker.create_from_options(options) as landmarker:
pose_landmarker_result = landmarker.detect(mediapipe_image)
key_points = sv.KeyPoints.from_mediapipe(
pose_landmarker_result, (image_width, image_height))
```
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 `sv.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_inference(cls, inference_result: Union[dict, Any]) -> KeyPoints:
"""
Create a `sv.KeyPoints` object from the [Roboflow](https://roboflow.com/)
API inference result or the [Inference](https://inference.roboflow.com/)
package results.
Args:
inference_result (dict, any): The result from the
Roboflow API or Inference package containing predictions with keypoints.
Returns:
A `sv.KeyPoints` object containing the keypoint coordinates, class IDs,
and class names, and confidences of each keypoint.
Examples:
```python
import cv2
import supervision as sv
from inference import get_model
image = cv2.imread(<SOURCE_IMAGE_PATH>)
model = get_model(model_id=<POSE_MODEL_ID>, api_key=<ROBOFLOW_API_KEY>)
result = model.infer(image)[0]
key_points = sv.KeyPoints.from_inference(result)
```
```python
import cv2
import supervision as sv
from inference_sdk import InferenceHTTPClient
image = cv2.imread(<SOURCE_IMAGE_PATH>)
client = InferenceHTTPClient(
api_url="https://detect.roboflow.com",
api_key=<ROBOFLOW_API_KEY>
)
result = client.infer(image, model_id=<POSE_MODEL_ID>)
key_points = sv.KeyPoints.from_inference(result)
```
"""
if isinstance(inference_result, list):
raise ValueError(
"from_inference() operates on a single result at a time."
"You can retrieve it like so: inference_result = model.infer(image)[0]"
)
with suppress(AttributeError):
inference_result = inference_result.dict(exclude_none=True, by_alias=True)
if not inference_result.get("predictions"):
return cls.empty()
xy = []
confidence = []
class_id = []
class_names = []
for prediction in inference_result["predictions"]:
prediction_xy = []
prediction_confidence = []
for keypoint in prediction["keypoints"]:
prediction_xy.append([keypoint["x"], keypoint["y"]])
prediction_confidence.append(keypoint["confidence"])
xy.append(prediction_xy)
confidence.append(prediction_confidence)
class_id.append(prediction["class_id"])
class_names.append(prediction["class"])
data = {CLASS_NAME_DATA_FIELD: np.array(class_names)}
return cls(
xy=np.array(xy, dtype=np.float32),
confidence=np.array(confidence, dtype=np.float32),
class_id=np.array(class_id, dtype=int),
data=data,
)
@classmethod
def from_mediapipe(
cls, mediapipe_results, resolution_wh: Tuple[int, int]
) -> KeyPoints:
"""
Creates a `sv.KeyPoints` instance from a
[MediaPipe](https://github.com/google-ai-edge/mediapipe)
pose landmark detection inference result.
Args:
mediapipe_results (Union[PoseLandmarkerResult, FaceLandmarkerResult, SolutionOutputs]):
The output results from Mediapipe. It support pose and face landmarks
from `PoseLandmaker`, `FaceLandmarker` and the legacy ones
from `Pose` and `FaceMesh`.
resolution_wh (Tuple[int, int]): A tuple of the form `(width, height)`
representing the resolution of the frame.
Returns:
A `sv.KeyPoints` object containing the keypoint coordinates and
confidences of each keypoint.
!!! tip
Before you start, download model bundles from the
[MediaPipe website](https://ai.google.dev/edge/mediapipe/solutions/vision/pose_landmarker/index#models).
Examples:
```python
import cv2
import mediapipe as mp
import supervision as sv
image = cv2.imread(<SOURCE_IMAGE_PATH>)
image_height, image_width, _ = image.shape
mediapipe_image = mp.Image(
image_format=mp.ImageFormat.SRGB,
data=cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
options = mp.tasks.vision.PoseLandmarkerOptions(
base_options=mp.tasks.BaseOptions(
model_asset_path="pose_landmarker_heavy.task"
),
running_mode=mp.tasks.vision.RunningMode.IMAGE,
num_poses=2)
PoseLandmarker = mp.tasks.vision.PoseLandmarker
with PoseLandmarker.create_from_options(options) as landmarker:
pose_landmarker_result = landmarker.detect(mediapipe_image)
key_points = sv.KeyPoints.from_mediapipe(
pose_landmarker_result, (image_width, image_height))
```
```python
import cv2
import mediapipe as mp
import supervision as sv
image = cv2.imread(<SOURCE_IMAGE_PATH>)
image_height, image_width, _ = image.shape
mediapipe_image = mp.Image(
image_format=mp.ImageFormat.SRGB,
data=cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
options = mp.tasks.vision.FaceLandmarkerOptions(
base_options=mp.tasks.BaseOptions(
model_asset_path="face_landmarker.task"
),
output_face_blendshapes=True,
output_facial_transformation_matrixes=True,
num_faces=2)
FaceLandmarker = mp.tasks.vision.FaceLandmarker
with FaceLandmarker.create_from_options(options) as landmarker:
face_landmarker_result = landmarker.detect(mediapipe_image)
key_points = sv.KeyPoints.from_mediapipe(
face_landmarker_result, (image_width, image_height))
```
""" # noqa: E501 // docs
if hasattr(mediapipe_results, "pose_landmarks"):
results = mediapipe_results.pose_landmarks
if not isinstance(mediapipe_results.pose_landmarks, list):
if mediapipe_results.pose_landmarks is None:
results = []
else:
results = [
[
landmark
for landmark in mediapipe_results.pose_landmarks.landmark
]
]
elif hasattr(mediapipe_results, "face_landmarks"):
results = mediapipe_results.face_landmarks
elif hasattr(mediapipe_results, "multi_face_landmarks"):
if mediapipe_results.multi_face_landmarks is None:
results = []
else:
results = [
face_landmark.landmark
for face_landmark in mediapipe_results.multi_face_landmarks
]
if len(results) == 0:
return cls.empty()
xy = []
confidence = []
for pose in results:
prediction_xy = []
prediction_confidence = []
for landmark in pose:
keypoint_xy = [
landmark.x * resolution_wh[0],
landmark.y * resolution_wh[1],
]
prediction_xy.append(keypoint_xy)
prediction_confidence.append(landmark.visibility)
xy.append(prediction_xy)
confidence.append(prediction_confidence)
return cls(
xy=np.array(xy, dtype=np.float32),
confidence=np.array(confidence, dtype=np.float32),
)
@classmethod
def from_ultralytics(cls, ultralytics_results) -> KeyPoints:
"""
Creates a `sv.KeyPoints` instance from a
[YOLOv8](https://github.com/ultralytics/ultralytics) pose inference result.
Args:
ultralytics_results (ultralytics.engine.results.Keypoints):
The output Results instance from YOLOv8
Returns:
A `sv.KeyPoints` object containing the keypoint coordinates, class IDs,
and class names, and confidences of each keypoint.
Examples:
```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)
```
"""
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)
@classmethod
def from_yolo_nas(cls, yolo_nas_results) -> KeyPoints:
"""
Create a `sv.KeyPoints` instance from a [YOLO-NAS](https://github.com/Deci-AI/super-gradients/blob/master/YOLONAS-POSE.md)
pose inference results.
Args:
yolo_nas_results (ImagePoseEstimationPrediction): The output object from
YOLO NAS.
Returns:
A `sv.KeyPoints` object containing the keypoint coordinates, class IDs,
and class names, and confidences of each keypoint.
Examples:
```python
import cv2
import torch
import supervision as sv
import super_gradients
image = cv2.imread(<SOURCE_IMAGE_PATH>)
device = "cuda" if torch.cuda.is_available() else "cpu"
model = super_gradients.training.models.get(
"yolo_nas_pose_s", pretrained_weights="coco_pose").to(device)
results = model.predict(image, conf=0.1)
key_points = sv.KeyPoints.from_yolo_nas(results)
```
""" # noqa: E501 // docs
if len(yolo_nas_results.prediction.poses) == 0:
return cls.empty()
xy = yolo_nas_results.prediction.poses[:, :, :2]
confidence = yolo_nas_results.prediction.poses[:, :, 2]
# yolo_nas_results treats params differently.
# prediction.labels may not exist, whereas class_names might be None
if hasattr(yolo_nas_results.prediction, "labels"):
class_id = yolo_nas_results.prediction.labels # np.array[int]
else:
class_id = None
data = {}
if class_id is not None and yolo_nas_results.class_names is not None:
class_names = []
for c_id in class_id:
name = yolo_nas_results.class_names[c_id] # tuple[str]
class_names.append(name)
data[CLASS_NAME_DATA_FIELD] = class_names
return cls(
xy=xy,
confidence=confidence,
class_id=class_id,
data=data,
)
@classmethod
def from_detectron2(cls, detectron2_results) -> KeyPoints:
"""
Create a `sv.KeyPoints` object from the
[Detectron2](https://github.com/facebookresearch/detectron2) inference result.
Args:
detectron2_results: The output of a
Detectron2 model containing instances with prediction data.
Returns:
A `sv.KeyPoints` object containing the keypoint coordinates, class IDs,
and class names, and confidences of each keypoint.
Example:
```python
import cv2
import supervision as sv
from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
image = cv2.imread(<SOURCE_IMAGE_PATH>)
cfg = get_cfg()
cfg.merge_from_file(<CONFIG_PATH>)
cfg.MODEL.WEIGHTS = <WEIGHTS_PATH>
predictor = DefaultPredictor(cfg)
result = predictor(image)
keypoints = sv.KeyPoints.from_detectron2(result)
```
"""
if hasattr(detectron2_results["instances"], "pred_keypoints"):
if detectron2_results["instances"].pred_keypoints.cpu().numpy().size == 0:
return cls.empty()
return cls(
xy=detectron2_results["instances"]
.pred_keypoints.cpu()
.numpy()[:, :, :2],
confidence=detectron2_results["instances"]
.pred_keypoints.cpu()
.numpy()[:, :, 2],
class_id=detectron2_results["instances"]
.pred_classes.cpu()
.numpy()
.astype(int),
)
else:
return cls.empty()
def __getitem__(
self, index: Union[int, slice, List[int], np.ndarray, str]
) -> Union[KeyPoints, List, np.ndarray, None]:
"""
Get a subset of the `sv.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 `sv.KeyPoints` object that represents a subset of the
original `sv.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 `sv.KeyPoints` or an item from the
data.
Returns:
A subset of the `sv.KeyPoints` object or an item from the data field.
Examples:
```python
import supervision as sv
key_points = sv.KeyPoints()
# access the first keypoint using an integer index
key_points[0]
# access the first 10 keypoints using index slice
key_points[0:10]
# access selected keypoints using a list of indices
key_points[[0, 2, 4]]
# access keypoints with selected class_id
key_points[key_points.class_id == 0]
# access keypoints with confidence greater than 0.5
key_points[key_points.confidence > 0.5]
```
"""
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 `sv.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.
Examples:
```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['class_name'] = [
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:
An empty `sv.KeyPoints` object.
Examples:
```python
import supervision as sv
key_points = sv.KeyPoints.empty()
```
"""
return cls(xy=np.empty((0, 0, 2), dtype=np.float32))
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More