diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..09304d38 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +*.iso filter=lfs diff=lfs merge=lfs -text +*.pt filter=lfs diff=lfs merge=lfs -text +*.onnx filter=lfs diff=lfs merge=lfs -text diff --git a/.github/workflows/Autonomy_Unit_Tests.yml b/.github/workflows/Autonomy_Unit_Tests.yml index 6b248852..b90212e0 100644 --- a/.github/workflows/Autonomy_Unit_Tests.yml +++ b/.github/workflows/Autonomy_Unit_Tests.yml @@ -23,14 +23,14 @@ jobs: with: submodules: "recursive" - name: Set up Python 3.8 - uses: actions/setup-python@v2 + uses: actions/setup-python@v4.5.0 with: python-version: 3.8 - name: Install dependencies with pipenv run: | python -m pip install --upgrade pip pip install pipenv - pipenv install -d + pipenv install --dev --verbose - name: Unit and coverage test with pytest (excludes tests not in the tests/ folder) run: | pipenv run pytest -v --cov=../Autonomy_Software tests/ diff --git a/.gitignore b/.gitignore index e0b68eca..a4f04236 100644 --- a/.gitignore +++ b/.gitignore @@ -33,3 +33,9 @@ resources/tests/output/* # Web Output Files *.html + +# Pip wheels +*.whl + +# pip lock +*.lock diff --git a/Pipfile b/Pipfile index 9b036cfc..12eaa7d8 100644 --- a/Pipfile +++ b/Pipfile @@ -3,8 +3,8 @@ python_version = "3.8" [[source]] name = "pypi" -url = "https://pypi.org/simple" -verify_ssl = true +url = "https://pypi.org/simple" +verify_ssl = false [packages] simplejson = "*" @@ -20,6 +20,12 @@ rich = "*" gmplot = "*" opencv-python = "*" opencv-contrib-python = "*" +pandas = "*" +tdqm = "*" +seaborn = "*" +utm = "*" +torch = "*" +torchvision = "*" [dev-packages] pytest = "*" diff --git a/Pipfile.lock b/Pipfile.lock deleted file mode 100644 index ce3150ac..00000000 --- a/Pipfile.lock +++ /dev/null @@ -1,859 +0,0 @@ -{ - "_meta": { - "hash": { - "sha256": "d248e9c36440d9d791347a8dbd86a8a91ff86a4f4e1633b309cddabeb68a54bc" - }, - "pipfile-spec": 6, - "requires": { - "python_version": "3.8" - }, - "sources": [ - { - "name": "pypi", - "url": "https://pypi.org/simple", - "verify_ssl": true - } - ] - }, - "default": { - "certifi": { - "hashes": [ - "sha256:84c85a9078b11105f04f3036a9482ae10e4621616db313fe045dd24743a0820d", - "sha256:fe86415d55e84719d75f8b69414f6438ac3547d2078ab91b67e779ef69378412" - ], - "markers": "python_version >= '3.6'", - "version": "==2022.6.15" - }, - "charset-normalizer": { - "hashes": [ - "sha256:5a3d016c7c547f69d6f81fb0db9449ce888b418b5b9952cc5e6e66843e9dd845", - "sha256:83e9a75d1911279afd89352c68b45348559d1fc0506b054b346651b5e7fee29f" - ], - "markers": "python_version >= '3.6'", - "version": "==2.1.1" - }, - "commonmark": { - "hashes": [ - "sha256:452f9dc859be7f06631ddcb328b6919c67984aca654e5fefb3914d54691aed60", - "sha256:da2f38c92590f83de410ba1a3cbceafbc74fee9def35f9251ba9a971d6d66fd9" - ], - "version": "==0.9.1" - }, - "cycler": { - "hashes": [ - "sha256:3a27e95f763a428a739d2add979fa7494c912a32c17c4c38c4d5f082cad165a3", - "sha256:9c87405839a19696e837b3b818fed3f5f69f16f1eec1a1ad77e043dcea9c772f" - ], - "markers": "python_version >= '3.6'", - "version": "==0.11.0" - }, - "fonttools": { - "hashes": [ - "sha256:4606e1a88ee1f6699d182fea9511bd9a8a915d913eab4584e5226da1180fcce7", - "sha256:fff6b752e326c15756c819fe2fe7ceab69f96a1dbcfe8911d0941cdb49905007" - ], - "markers": "python_version >= '3.7'", - "version": "==4.37.1" - }, - "future": { - "hashes": [ - "sha256:b1bead90b70cf6ec3f0710ae53a525360fa360d306a86583adc6bf83a4db537d" - ], - "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'", - "version": "==0.18.2" - }, - "geographiclib": { - "hashes": [ - "sha256:8f441c527b0b8a26cd96c965565ff0513d1e4d9952b704bf449409e5015c77b7", - "sha256:ac400d672b8954b0306bca890b088bb8ba2a757dc8133cca0b878f34b33b2740" - ], - "version": "==1.52" - }, - "geopy": { - "hashes": [ - "sha256:5dee9af0d1ad7019d2483a5f519ba415eaebc4010f271651790876d911a542f2", - "sha256:62f14aaacbac313576167d4abdd74c667c04a64ccba4a9ef4599bf8954c998fc" - ], - "index": "pypi", - "version": "==1.23.0" - }, - "gmplot": { - "hashes": [ - "sha256:873bcecd90f0e63a73b2876e15a2225145d726f3b7cfb47a363a3a5459fc778d", - "sha256:cfe72d251c17b5c05043169d121a9728554bf65b8c96760ce9fabb6d269c6667" - ], - "index": "pypi", - "version": "==1.4.1" - }, - "idna": { - "hashes": [ - "sha256:84d9dd047ffa80596e0f246e2eab0b391788b0503584e8945f2368256d2735ff", - "sha256:9d643ff0a55b762d5cdb124b8eaa99c66322e2157b69160bc32796e824360e6d" - ], - "markers": "python_version >= '3.5'", - "version": "==3.3" - }, - "iso8601": { - "hashes": [ - "sha256:27f503220e6845d9db954fb212b95b0362d8b7e6c1b2326a87061c3de93594b1", - "sha256:d7bc01b1c2a43b259570bb307f057abc578786ea734ba2b87b836c5efc5bd443" - ], - "markers": "python_version < '4.0' and python_full_version >= '3.6.2'", - "version": "==1.0.2" - }, - "kiwisolver": { - "hashes": [ - "sha256:02f79693ec433cb4b5f51694e8477ae83b3205768a6fb48ffba60549080e295b", - "sha256:03baab2d6b4a54ddbb43bba1a3a2d1627e82d205c5cf8f4c924dc49284b87166", - "sha256:1041feb4cda8708ce73bb4dcb9ce1ccf49d553bf87c3954bdfa46f0c3f77252c", - "sha256:10ee06759482c78bdb864f4109886dff7b8a56529bc1609d4f1112b93fe6423c", - "sha256:1d1573129aa0fd901076e2bfb4275a35f5b7aa60fbfb984499d661ec950320b0", - "sha256:283dffbf061a4ec60391d51e6155e372a1f7a4f5b15d59c8505339454f8989e4", - "sha256:28bc5b299f48150b5f822ce68624e445040595a4ac3d59251703779836eceff9", - "sha256:2a66fdfb34e05b705620dd567f5a03f239a088d5a3f321e7b6ac3239d22aa286", - "sha256:2e307eb9bd99801f82789b44bb45e9f541961831c7311521b13a6c85afc09767", - "sha256:2e407cb4bd5a13984a6c2c0fe1845e4e41e96f183e5e5cd4d77a857d9693494c", - "sha256:2f5e60fabb7343a836360c4f0919b8cd0d6dbf08ad2ca6b9cf90bf0c76a3c4f6", - "sha256:36dafec3d6d6088d34e2de6b85f9d8e2324eb734162fba59d2ba9ed7a2043d5b", - "sha256:3fe20f63c9ecee44560d0e7f116b3a747a5d7203376abeea292ab3152334d004", - "sha256:41dae968a94b1ef1897cb322b39360a0812661dba7c682aa45098eb8e193dbdf", - "sha256:4bd472dbe5e136f96a4b18f295d159d7f26fd399136f5b17b08c4e5f498cd494", - "sha256:4ea39b0ccc4f5d803e3337dd46bcce60b702be4d86fd0b3d7531ef10fd99a1ac", - "sha256:5853eb494c71e267912275e5586fe281444eb5e722de4e131cddf9d442615626", - "sha256:5bce61af018b0cb2055e0e72e7d65290d822d3feee430b7b8203d8a855e78766", - "sha256:6295ecd49304dcf3bfbfa45d9a081c96509e95f4b9d0eb7ee4ec0530c4a96514", - "sha256:62ac9cc684da4cf1778d07a89bf5f81b35834cb96ca523d3a7fb32509380cbf6", - "sha256:70e7c2e7b750585569564e2e5ca9845acfaa5da56ac46df68414f29fea97be9f", - "sha256:7577c1987baa3adc4b3c62c33bd1118c3ef5c8ddef36f0f2c950ae0b199e100d", - "sha256:75facbe9606748f43428fc91a43edb46c7ff68889b91fa31f53b58894503a191", - "sha256:787518a6789009c159453da4d6b683f468ef7a65bbde796bcea803ccf191058d", - "sha256:78d6601aed50c74e0ef02f4204da1816147a6d3fbdc8b3872d263338a9052c51", - "sha256:7c43e1e1206cd421cd92e6b3280d4385d41d7166b3ed577ac20444b6995a445f", - "sha256:81e38381b782cc7e1e46c4e14cd997ee6040768101aefc8fa3c24a4cc58e98f8", - "sha256:841293b17ad704d70c578f1f0013c890e219952169ce8a24ebc063eecf775454", - "sha256:872b8ca05c40d309ed13eb2e582cab0c5a05e81e987ab9c521bf05ad1d5cf5cb", - "sha256:877272cf6b4b7e94c9614f9b10140e198d2186363728ed0f701c6eee1baec1da", - "sha256:8c808594c88a025d4e322d5bb549282c93c8e1ba71b790f539567932722d7bd8", - "sha256:8ed58b8acf29798b036d347791141767ccf65eee7f26bde03a71c944449e53de", - "sha256:91672bacaa030f92fc2f43b620d7b337fd9a5af28b0d6ed3f77afc43c4a64b5a", - "sha256:968f44fdbf6dd757d12920d63b566eeb4d5b395fd2d00d29d7ef00a00582aac9", - "sha256:9f85003f5dfa867e86d53fac6f7e6f30c045673fa27b603c397753bebadc3008", - "sha256:a553dadda40fef6bfa1456dc4be49b113aa92c2a9a9e8711e955618cd69622e3", - "sha256:a68b62a02953b9841730db7797422f983935aeefceb1679f0fc85cbfbd311c32", - "sha256:abbe9fa13da955feb8202e215c4018f4bb57469b1b78c7a4c5c7b93001699938", - "sha256:ad881edc7ccb9d65b0224f4e4d05a1e85cf62d73aab798943df6d48ab0cd79a1", - "sha256:b1792d939ec70abe76f5054d3f36ed5656021dcad1322d1cc996d4e54165cef9", - "sha256:b428ef021242344340460fa4c9185d0b1f66fbdbfecc6c63eff4b7c29fad429d", - "sha256:b533558eae785e33e8c148a8d9921692a9fe5aa516efbdff8606e7d87b9d5824", - "sha256:ba59c92039ec0a66103b1d5fe588fa546373587a7d68f5c96f743c3396afc04b", - "sha256:bc8d3bd6c72b2dd9decf16ce70e20abcb3274ba01b4e1c96031e0c4067d1e7cd", - "sha256:bc9db8a3efb3e403e4ecc6cd9489ea2bac94244f80c78e27c31dcc00d2790ac2", - "sha256:bf7d9fce9bcc4752ca4a1b80aabd38f6d19009ea5cbda0e0856983cf6d0023f5", - "sha256:c2dbb44c3f7e6c4d3487b31037b1bdbf424d97687c1747ce4ff2895795c9bf69", - "sha256:c79ebe8f3676a4c6630fd3f777f3cfecf9289666c84e775a67d1d358578dc2e3", - "sha256:c97528e64cb9ebeff9701e7938653a9951922f2a38bd847787d4a8e498cc83ae", - "sha256:d0611a0a2a518464c05ddd5a3a1a0e856ccc10e67079bb17f265ad19ab3c7597", - "sha256:d06adcfa62a4431d404c31216f0f8ac97397d799cd53800e9d3efc2fbb3cf14e", - "sha256:d41997519fcba4a1e46eb4a2fe31bc12f0ff957b2b81bac28db24744f333e955", - "sha256:d5b61785a9ce44e5a4b880272baa7cf6c8f48a5180c3e81c59553ba0cb0821ca", - "sha256:da152d8cdcab0e56e4f45eb08b9aea6455845ec83172092f09b0e077ece2cf7a", - "sha256:da7e547706e69e45d95e116e6939488d62174e033b763ab1496b4c29b76fabea", - "sha256:db5283d90da4174865d520e7366801a93777201e91e79bacbac6e6927cbceede", - "sha256:db608a6757adabb32f1cfe6066e39b3706d8c3aa69bbc353a5b61edad36a5cb4", - "sha256:e0ea21f66820452a3f5d1655f8704a60d66ba1191359b96541eaf457710a5fc6", - "sha256:e7da3fec7408813a7cebc9e4ec55afed2d0fd65c4754bc376bf03498d4e92686", - "sha256:e92a513161077b53447160b9bd8f522edfbed4bd9759e4c18ab05d7ef7e49408", - "sha256:ecb1fa0db7bf4cff9dac752abb19505a233c7f16684c5826d1f11ebd9472b871", - "sha256:efda5fc8cc1c61e4f639b8067d118e742b812c930f708e6667a5ce0d13499e29", - "sha256:f0a1dbdb5ecbef0d34eb77e56fcb3e95bbd7e50835d9782a45df81cc46949750", - "sha256:f0a71d85ecdd570ded8ac3d1c0f480842f49a40beb423bb8014539a9f32a5897", - "sha256:f4f270de01dd3e129a72efad823da90cc4d6aafb64c410c9033aba70db9f1ff0", - "sha256:f6cb459eea32a4e2cf18ba5fcece2dbdf496384413bc1bae15583f19e567f3b2", - "sha256:f8ad8285b01b0d4695102546b342b493b3ccc6781fc28c8c6a1bb63e95d22f09", - "sha256:f9f39e2f049db33a908319cf46624a569b36983c7c78318e9726a4cb8923b26c" - ], - "markers": "python_version >= '3.7'", - "version": "==1.4.4" - }, - "matplotlib": { - "hashes": [ - "sha256:0bcdfcb0f976e1bac6721d7d457c17be23cf7501f977b6a38f9d38a3762841f7", - "sha256:1e64ac9be9da6bfff0a732e62116484b93b02a0b4d4b19934fb4f8e7ad26ad6a", - "sha256:22227c976ad4dc8c5a5057540421f0d8708c6560744ad2ad638d48e2984e1dbc", - "sha256:2886cc009f40e2984c083687251821f305d811d38e3df8ded414265e4583f0c5", - "sha256:2e6d184ebe291b9e8f7e78bbab7987d269c38ea3e062eace1fe7d898042ef804", - "sha256:3211ba82b9f1518d346f6309df137b50c3dc4421b4ed4815d1d7eadc617f45a1", - "sha256:339cac48b80ddbc8bfd05daae0a3a73414651a8596904c2a881cfd1edb65f26c", - "sha256:35a8ad4dddebd51f94c5d24bec689ec0ec66173bf614374a1244c6241c1595e0", - "sha256:3b4fa56159dc3c7f9250df88f653f085068bcd32dcd38e479bba58909254af7f", - "sha256:43e9d3fa077bf0cc95ded13d331d2156f9973dce17c6f0c8b49ccd57af94dbd9", - "sha256:57f1b4e69f438a99bb64d7f2c340db1b096b41ebaa515cf61ea72624279220ce", - "sha256:5c096363b206a3caf43773abebdbb5a23ea13faef71d701b21a9c27fdcef72f4", - "sha256:6bb93a0492d68461bd458eba878f52fdc8ac7bdb6c4acdfe43dba684787838c2", - "sha256:6ea6aef5c4338e58d8d376068e28f80a24f54e69f09479d1c90b7172bad9f25b", - "sha256:6fe807e8a22620b4cd95cfbc795ba310dc80151d43b037257250faf0bfcd82bc", - "sha256:73dd93dc35c85dece610cca8358003bf0760d7986f70b223e2306b4ea6d1406b", - "sha256:839d47b8ead7ad9669aaacdbc03f29656dc21f0d41a6fea2d473d856c39c8b1c", - "sha256:874df7505ba820e0400e7091199decf3ff1fde0583652120c50cd60d5820ca9a", - "sha256:879c7e5fce4939c6aa04581dfe08d57eb6102a71f2e202e3314d5fbc072fd5a0", - "sha256:94ff86af56a3869a4ae26a9637a849effd7643858a1a04dd5ee50e9ab75069a7", - "sha256:99482b83ebf4eb6d5fc6813d7aacdefdd480f0d9c0b52dcf9f1cc3b2c4b3361a", - "sha256:9ab29589cef03bc88acfa3a1490359000c18186fc30374d8aa77d33cc4a51a4a", - "sha256:9befa5954cdbc085e37d974ff6053da269474177921dd61facdad8023c4aeb51", - "sha256:a206a1b762b39398efea838f528b3a6d60cdb26fe9d58b48265787e29cd1d693", - "sha256:ab8d26f07fe64f6f6736d635cce7bfd7f625320490ed5bfc347f2cdb4fae0e56", - "sha256:b28de401d928890187c589036857a270a032961411934bdac4cf12dde3d43094", - "sha256:b428076a55fb1c084c76cb93e68006f27d247169f056412607c5c88828d08f88", - "sha256:bf618a825deb6205f015df6dfe6167a5d9b351203b03fab82043ae1d30f16511", - "sha256:c995f7d9568f18b5db131ab124c64e51b6820a92d10246d4f2b3f3a66698a15b", - "sha256:cd45a6f3e93a780185f70f05cf2a383daed13c3489233faad83e81720f7ede24", - "sha256:d2484b350bf3d32cae43f85dcfc89b3ed7bd2bcd781ef351f93eb6fb2cc483f9", - "sha256:d62880e1f60e5a30a2a8484432bcb3a5056969dc97258d7326ad465feb7ae069", - "sha256:dacddf5bfcec60e3f26ec5c0ae3d0274853a258b6c3fc5ef2f06a8eb23e042be", - "sha256:f3840c280ebc87a48488a46f760ea1c0c0c83fcf7abbe2e6baf99d033fd35fd8", - "sha256:f814504e459c68118bf2246a530ed953ebd18213dc20e3da524174d84ed010b2" - ], - "index": "pypi", - "version": "==3.5.3" - }, - "numpy": { - "hashes": [ - "sha256:0cfe07133fd00b27edee5e6385e333e9eeb010607e8a46e1cd673f05f8596595", - "sha256:11a1f3816ea82eed4178102c56281782690ab5993251fdfd75039aad4d20385f", - "sha256:2762331de395739c91f1abb88041f94a080cb1143aeec791b3b223976228af3f", - "sha256:283d9de87c0133ef98f93dfc09fad3fb382f2a15580de75c02b5bb36a5a159a5", - "sha256:3d22662b4b10112c545c91a0741f2436f8ca979ab3d69d03d19322aa970f9695", - "sha256:41388e32e40b41dd56eb37fcaa7488b2b47b0adf77c66154d6b89622c110dfe9", - "sha256:42c16cec1c8cf2728f1d539bd55aaa9d6bb48a7de2f41eb944697293ef65a559", - "sha256:47ee7a839f5885bc0c63a74aabb91f6f40d7d7b639253768c4199b37aede7982", - "sha256:5a311ee4d983c487a0ab546708edbdd759393a3dc9cd30305170149fedd23c88", - "sha256:5dc65644f75a4c2970f21394ad8bea1a844104f0fe01f278631be1c7eae27226", - "sha256:6ed0d073a9c54ac40c41a9c2d53fcc3d4d4ed607670b9e7b0de1ba13b4cbfe6f", - "sha256:76ba7c40e80f9dc815c5e896330700fd6e20814e69da9c1267d65a4d051080f1", - "sha256:818b9be7900e8dc23e013a92779135623476f44a0de58b40c32a15368c01d471", - "sha256:a024181d7aef0004d76fb3bce2a4c9f2e67a609a9e2a6ff2571d30e9976aa383", - "sha256:a955e4128ac36797aaffd49ab44ec74a71c11d6938df83b1285492d277db5397", - "sha256:a97a954a8c2f046d3817c2bce16e3c7e9a9c2afffaf0400f5c16df5172a67c9c", - "sha256:a97e82c39d9856fe7d4f9b86d8a1e66eff99cf3a8b7ba48202f659703d27c46f", - "sha256:b55b953a1bdb465f4dc181758570d321db4ac23005f90ffd2b434cc6609a63dd", - "sha256:bb02929b0d6bfab4c48a79bd805bd7419114606947ec8284476167415171f55b", - "sha256:bece0a4a49e60e472a6d1f70ac6cdea00f9ab80ff01132f96bd970cdd8a9e5a9", - "sha256:e41e8951749c4b5c9a2dc5fdbc1a4eec6ab2a140fdae9b460b0f557eed870f4d", - "sha256:f71d57cc8645f14816ae249407d309be250ad8de93ef61d9709b45a0ddf4050c" - ], - "index": "pypi", - "version": "==1.22.0" - }, - "opencv-contrib-python": { - "hashes": [ - "sha256:1dcdd0c68ae8495668f8a3360f7da5a24bc490320f21fc819bf60e197bf5bd7e", - "sha256:243411366820ba73f185867d0d9f9b8d42296070068222d5e3e40ecdcbbb3b39", - "sha256:256efeb263999f3fb2427095392c1cb442d655508cd0a42864a383d55f3e6d43", - "sha256:658ee41d6026614c7d4398fe7144b181e543d011ea190a0b80ec7a7d74ac744d", - "sha256:695911db4079216ffa5c3683885ccdfaba3059d279f9b96c14f9b8ec05570820", - "sha256:a338e1fb67fb25b30634cb34cd79328d4431f838964cfd7689f254012dd98ed9", - "sha256:d72fca3b0fb412cee3829cd5a2d30558953a6c378afccee3f4646daa9b12ab33" - ], - "index": "pypi", - "version": "==4.6.0.66" - }, - "opencv-python": { - "hashes": [ - "sha256:0dc82a3d8630c099d2f3ac1b1aabee164e8188db54a786abb7a4e27eba309440", - "sha256:5af8ba35a4fcb8913ffb86e92403e9a656a4bff4a645d196987468f0f8947875", - "sha256:6e32af22e3202748bd233ed8f538741876191863882eba44e332d1a34993165b", - "sha256:c5bfae41ad4031e66bb10ec4a0a2ffd3e514d092652781e8b1ac98d1b59f1158", - "sha256:dbdc84a9b4ea2cbae33861652d25093944b9959279200b7ae0badd32439f74de", - "sha256:e6e448b62afc95c5b58f97e87ef84699e6607fe5c58730a03301c52496005cae", - "sha256:f482e78de6e7b0b060ff994ffd859bddc3f7f382bb2019ef157b0ea8ca8712f5" - ], - "index": "pypi", - "version": "==4.6.0.66" - }, - "packaging": { - "hashes": [ - "sha256:dd47c42927d89ab911e606518907cc2d3a1f38bbd026385970643f9c5b8ecfeb", - "sha256:ef103e05f519cdc783ae24ea4e2e0f508a9c99b2d4969652eed6a2e1ea5bd522" - ], - "markers": "python_version >= '3.6'", - "version": "==21.3" - }, - "pillow": { - "hashes": [ - "sha256:0030fdbd926fb85844b8b92e2f9449ba89607231d3dd597a21ae72dc7fe26927", - "sha256:030e3460861488e249731c3e7ab59b07c7853838ff3b8e16aac9561bb345da14", - "sha256:0ed2c4ef2451de908c90436d6e8092e13a43992f1860275b4d8082667fbb2ffc", - "sha256:136659638f61a251e8ed3b331fc6ccd124590eeff539de57c5f80ef3a9594e58", - "sha256:13b725463f32df1bfeacbf3dd197fb358ae8ebcd8c5548faa75126ea425ccb60", - "sha256:1536ad017a9f789430fb6b8be8bf99d2f214c76502becc196c6f2d9a75b01b76", - "sha256:15928f824870535c85dbf949c09d6ae7d3d6ac2d6efec80f3227f73eefba741c", - "sha256:17d4cafe22f050b46d983b71c707162d63d796a1235cdf8b9d7a112e97b15bac", - "sha256:1802f34298f5ba11d55e5bb09c31997dc0c6aed919658dfdf0198a2fe75d5490", - "sha256:1cc1d2451e8a3b4bfdb9caf745b58e6c7a77d2e469159b0d527a4554d73694d1", - "sha256:1fd6f5e3c0e4697fa7eb45b6e93996299f3feee73a3175fa451f49a74d092b9f", - "sha256:254164c57bab4b459f14c64e93df11eff5ded575192c294a0c49270f22c5d93d", - "sha256:2ad0d4df0f5ef2247e27fc790d5c9b5a0af8ade9ba340db4a73bb1a4a3e5fb4f", - "sha256:2c58b24e3a63efd22554c676d81b0e57f80e0a7d3a5874a7e14ce90ec40d3069", - "sha256:2d33a11f601213dcd5718109c09a52c2a1c893e7461f0be2d6febc2879ec2402", - "sha256:336b9036127eab855beec9662ac3ea13a4544a523ae273cbf108b228ecac8437", - "sha256:337a74fd2f291c607d220c793a8135273c4c2ab001b03e601c36766005f36885", - "sha256:37ff6b522a26d0538b753f0b4e8e164fdada12db6c6f00f62145d732d8a3152e", - "sha256:3d1f14f5f691f55e1b47f824ca4fdcb4b19b4323fe43cc7bb105988cad7496be", - "sha256:408673ed75594933714482501fe97e055a42996087eeca7e5d06e33218d05aa8", - "sha256:4134d3f1ba5f15027ff5c04296f13328fecd46921424084516bdb1b2548e66ff", - "sha256:4ad2f835e0ad81d1689f1b7e3fbac7b01bb8777d5a985c8962bedee0cc6d43da", - "sha256:50dff9cc21826d2977ef2d2a205504034e3a4563ca6f5db739b0d1026658e004", - "sha256:510cef4a3f401c246cfd8227b300828715dd055463cdca6176c2e4036df8bd4f", - "sha256:5aed7dde98403cd91d86a1115c78d8145c83078e864c1de1064f52e6feb61b20", - "sha256:69bd1a15d7ba3694631e00df8de65a8cb031911ca11f44929c97fe05eb9b6c1d", - "sha256:6bf088c1ce160f50ea40764f825ec9b72ed9da25346216b91361eef8ad1b8f8c", - "sha256:6e8c66f70fb539301e064f6478d7453e820d8a2c631da948a23384865cd95544", - "sha256:727dd1389bc5cb9827cbd1f9d40d2c2a1a0c9b32dd2261db522d22a604a6eec9", - "sha256:74a04183e6e64930b667d321524e3c5361094bb4af9083db5c301db64cd341f3", - "sha256:75e636fd3e0fb872693f23ccb8a5ff2cd578801251f3a4f6854c6a5d437d3c04", - "sha256:7761afe0126d046974a01e030ae7529ed0ca6a196de3ec6937c11df0df1bc91c", - "sha256:7888310f6214f19ab2b6df90f3f06afa3df7ef7355fc025e78a3044737fab1f5", - "sha256:7b0554af24df2bf96618dac71ddada02420f946be943b181108cac55a7a2dcd4", - "sha256:7c7b502bc34f6e32ba022b4a209638f9e097d7a9098104ae420eb8186217ebbb", - "sha256:808add66ea764ed97d44dda1ac4f2cfec4c1867d9efb16a33d158be79f32b8a4", - "sha256:831e648102c82f152e14c1a0938689dbb22480c548c8d4b8b248b3e50967b88c", - "sha256:93689632949aff41199090eff5474f3990b6823404e45d66a5d44304e9cdc467", - "sha256:96b5e6874431df16aee0c1ba237574cb6dff1dcb173798faa6a9d8b399a05d0e", - "sha256:9a54614049a18a2d6fe156e68e188da02a046a4a93cf24f373bffd977e943421", - "sha256:a138441e95562b3c078746a22f8fca8ff1c22c014f856278bdbdd89ca36cff1b", - "sha256:a647c0d4478b995c5e54615a2e5360ccedd2f85e70ab57fbe817ca613d5e63b8", - "sha256:a9c9bc489f8ab30906d7a85afac4b4944a572a7432e00698a7239f44a44e6efb", - "sha256:ad2277b185ebce47a63f4dc6302e30f05762b688f8dc3de55dbae4651872cdf3", - "sha256:adabc0bce035467fb537ef3e5e74f2847c8af217ee0be0455d4fec8adc0462fc", - "sha256:b6d5e92df2b77665e07ddb2e4dbd6d644b78e4c0d2e9272a852627cdba0d75cf", - "sha256:bc431b065722a5ad1dfb4df354fb9333b7a582a5ee39a90e6ffff688d72f27a1", - "sha256:bdd0de2d64688ecae88dd8935012c4a72681e5df632af903a1dca8c5e7aa871a", - "sha256:c79698d4cd9318d9481d89a77e2d3fcaeff5486be641e60a4b49f3d2ecca4e28", - "sha256:cb6259196a589123d755380b65127ddc60f4c64b21fc3bb46ce3a6ea663659b0", - "sha256:d5b87da55a08acb586bad5c3aa3b86505f559b84f39035b233d5bf844b0834b1", - "sha256:dcd7b9c7139dc8258d164b55696ecd16c04607f1cc33ba7af86613881ffe4ac8", - "sha256:dfe4c1fedfde4e2fbc009d5ad420647f7730d719786388b7de0999bf32c0d9fd", - "sha256:ea98f633d45f7e815db648fd7ff0f19e328302ac36427343e4432c84432e7ff4", - "sha256:ec52c351b35ca269cb1f8069d610fc45c5bd38c3e91f9ab4cbbf0aebc136d9c8", - "sha256:eef7592281f7c174d3d6cbfbb7ee5984a671fcd77e3fc78e973d492e9bf0eb3f", - "sha256:f07f1f00e22b231dd3d9b9208692042e29792d6bd4f6639415d2f23158a80013", - "sha256:f3fac744f9b540148fa7715a435d2283b71f68bfb6d4aae24482a890aed18b59", - "sha256:fa768eff5f9f958270b081bb33581b4b569faabf8774726b283edb06617101dc", - "sha256:fac2d65901fb0fdf20363fbd345c01958a742f2dc62a8dd4495af66e3ff502a4" - ], - "markers": "python_version >= '3.7'", - "version": "==9.2.0" - }, - "pyfakewebcam": { - "hashes": [ - "sha256:2ad8ceada6605d8ba6ba76e087edf20bfce22d544fc410013067d7ce347d5694" - ], - "index": "pypi", - "version": "==0.1.0" - }, - "pygments": { - "hashes": [ - "sha256:56a8508ae95f98e2b9bdf93a6be5ae3f7d8af858b43e02c5a2ff083726be40c1", - "sha256:f643f331ab57ba3c9d89212ee4a2dabc6e94f117cf4eefde99a0574720d14c42" - ], - "markers": "python_version >= '3.6'", - "version": "==2.13.0" - }, - "pynmea2": { - "hashes": [ - "sha256:098f9ffd89c4a6c5e137b8b59e5b38194888d4a557c50b003ebcf2c3c15ec22e", - "sha256:e340d3327ebf09683d09466a52541dfcccb98bde9cb661cab2d3eeb72ea424ad" - ], - "index": "pypi", - "version": "==1.18.0" - }, - "pyparsing": { - "hashes": [ - "sha256:2b020ecf7d21b687f219b71ecad3631f644a47f01403fa1d1036b0c6416d70fb", - "sha256:5026bae9a10eeaefb61dab2f09052b9f4307d44aee4eda64b309723d8d206bbc" - ], - "markers": "python_full_version >= '3.6.8'", - "version": "==3.0.9" - }, - "python-dateutil": { - "hashes": [ - "sha256:0123cacc1627ae19ddf3c27a5de5bd67ee4586fbdd6440d9748f8abb483d3e86", - "sha256:961d03dc3453ebbc59dbdea9e4e11c5651520a876d0f4db161e8674aae935da9" - ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", - "version": "==2.8.2" - }, - "pyyaml": { - "hashes": [ - "sha256:0283c35a6a9fbf047493e3a0ce8d79ef5030852c51e9d911a27badfde0605293", - "sha256:055d937d65826939cb044fc8c9b08889e8c743fdc6a32b33e2390f66013e449b", - "sha256:07751360502caac1c067a8132d150cf3d61339af5691fe9e87803040dbc5db57", - "sha256:0b4624f379dab24d3725ffde76559cff63d9ec94e1736b556dacdfebe5ab6d4b", - "sha256:0ce82d761c532fe4ec3f87fc45688bdd3a4c1dc5e0b4a19814b9009a29baefd4", - "sha256:1e4747bc279b4f613a09eb64bba2ba602d8a6664c6ce6396a4d0cd413a50ce07", - "sha256:213c60cd50106436cc818accf5baa1aba61c0189ff610f64f4a3e8c6726218ba", - "sha256:231710d57adfd809ef5d34183b8ed1eeae3f76459c18fb4a0b373ad56bedcdd9", - "sha256:277a0ef2981ca40581a47093e9e2d13b3f1fbbeffae064c1d21bfceba2030287", - "sha256:2cd5df3de48857ed0544b34e2d40e9fac445930039f3cfe4bcc592a1f836d513", - "sha256:40527857252b61eacd1d9af500c3337ba8deb8fc298940291486c465c8b46ec0", - "sha256:473f9edb243cb1935ab5a084eb238d842fb8f404ed2193a915d1784b5a6b5fc0", - "sha256:48c346915c114f5fdb3ead70312bd042a953a8ce5c7106d5bfb1a5254e47da92", - "sha256:50602afada6d6cbfad699b0c7bb50d5ccffa7e46a3d738092afddc1f9758427f", - "sha256:68fb519c14306fec9720a2a5b45bc9f0c8d1b9c72adf45c37baedfcd949c35a2", - "sha256:77f396e6ef4c73fdc33a9157446466f1cff553d979bd00ecb64385760c6babdc", - "sha256:819b3830a1543db06c4d4b865e70ded25be52a2e0631ccd2f6a47a2822f2fd7c", - "sha256:897b80890765f037df3403d22bab41627ca8811ae55e9a722fd0392850ec4d86", - "sha256:98c4d36e99714e55cfbaaee6dd5badbc9a1ec339ebfc3b1f52e293aee6bb71a4", - "sha256:9df7ed3b3d2e0ecfe09e14741b857df43adb5a3ddadc919a2d94fbdf78fea53c", - "sha256:9fa600030013c4de8165339db93d182b9431076eb98eb40ee068700c9c813e34", - "sha256:a80a78046a72361de73f8f395f1f1e49f956c6be882eed58505a15f3e430962b", - "sha256:b3d267842bf12586ba6c734f89d1f5b871df0273157918b0ccefa29deb05c21c", - "sha256:b5b9eccad747aabaaffbc6064800670f0c297e52c12754eb1d976c57e4f74dcb", - "sha256:c5687b8d43cf58545ade1fe3e055f70eac7a5a1a0bf42824308d868289a95737", - "sha256:cba8c411ef271aa037d7357a2bc8f9ee8b58b9965831d9e51baf703280dc73d3", - "sha256:d15a181d1ecd0d4270dc32edb46f7cb7733c7c508857278d3d378d14d606db2d", - "sha256:d4db7c7aef085872ef65a8fd7d6d09a14ae91f691dec3e87ee5ee0539d516f53", - "sha256:d4eccecf9adf6fbcc6861a38015c2a64f38b9d94838ac1810a9023a0609e1b78", - "sha256:d67d839ede4ed1b28a4e8909735fc992a923cdb84e618544973d7dfc71540803", - "sha256:daf496c58a8c52083df09b80c860005194014c3698698d1a57cbcfa182142a3a", - "sha256:e61ceaab6f49fb8bdfaa0f92c4b57bcfbea54c09277b1b4f7ac376bfb7a7c174", - "sha256:f84fbc98b019fef2ee9a1cb3ce93e3187a6df0b2538a651bfb890254ba9f90b5" - ], - "index": "pypi", - "version": "==6.0" - }, - "requests": { - "hashes": [ - "sha256:7c5599b102feddaa661c826c56ab4fee28bfd17f5abca1ebbe3e7f19d7c97983", - "sha256:8fefa2a1a1365bf5520aac41836fbee479da67864514bdb821f31ce07ce65349" - ], - "markers": "python_version >= '3.7' and python_version < '4.0'", - "version": "==2.28.1" - }, - "rich": { - "hashes": [ - "sha256:2eb4e6894cde1e017976d2975ac210ef515d7548bc595ba20e195fb9628acdeb", - "sha256:63a5c5ce3673d3d5fbbf23cd87e11ab84b6b451436f1b7f19ec54b6bc36ed7ca" - ], - "index": "pypi", - "version": "==12.5.1" - }, - "serial": { - "hashes": [ - "sha256:542150a127ddbf5ed2acc3a6ac4ce807cbcdae3b197acf785bbda6565c94f848", - "sha256:e887f06e07e190e39174b694eee6724e3c48bd361be1d97964caef5d5b61c73b" - ], - "index": "pypi", - "version": "==0.0.97" - }, - "simplejson": { - "hashes": [ - "sha256:04e31fa6ac8e326480703fb6ded1488bfa6f1d3f760d32e29dbf66d0838982ce", - "sha256:068670af975247acbb9fc3d5393293368cda17026db467bf7a51548ee8f17ee1", - "sha256:07ecaafc1b1501f275bf5acdee34a4ad33c7c24ede287183ea77a02dc071e0c0", - "sha256:0b4126cac7d69ac06ff22efd3e0b3328a4a70624fcd6bca4fc1b4e6d9e2e12bf", - "sha256:0de783e9c2b87bdd75b57efa2b6260c24b94605b5c9843517577d40ee0c3cc8a", - "sha256:12133863178a8080a3dccbf5cb2edfab0001bc41e5d6d2446af2a1131105adfe", - "sha256:1c9b1ed7ed282b36571638297525f8ef80f34b3e2d600a56f962c6044f24200d", - "sha256:23fe704da910ff45e72543cbba152821685a889cf00fc58d5c8ee96a9bad5f94", - "sha256:28221620f4dcabdeac310846629b976e599a13f59abb21616356a85231ebd6ad", - "sha256:35a49ebef25f1ebdef54262e54ae80904d8692367a9f208cdfbc38dbf649e00a", - "sha256:37bc0cf0e5599f36072077e56e248f3336917ded1d33d2688624d8ed3cefd7d2", - "sha256:3fe87570168b2ae018391e2b43fbf66e8593a86feccb4b0500d134c998983ccc", - "sha256:3ff5b3464e1ce86a8de8c88e61d4836927d5595c2162cab22e96ff551b916e81", - "sha256:401d40969cee3df7bda211e57b903a534561b77a7ade0dd622a8d1a31eaa8ba7", - "sha256:4b6bd8144f15a491c662f06814bd8eaa54b17f26095bb775411f39bacaf66837", - "sha256:4c09868ddb86bf79b1feb4e3e7e4a35cd6e61ddb3452b54e20cf296313622566", - "sha256:4d1c135af0c72cb28dd259cf7ba218338f4dc027061262e46fe058b4e6a4c6a3", - "sha256:4ff4ac6ff3aa8f814ac0f50bf218a2e1a434a17aafad4f0400a57a8cc62ef17f", - "sha256:521877c7bd060470806eb6335926e27453d740ac1958eaf0d8c00911bc5e1802", - "sha256:522fad7be85de57430d6d287c4b635813932946ebf41b913fe7e880d154ade2e", - "sha256:5540fba2d437edaf4aa4fbb80f43f42a8334206ad1ad3b27aef577fd989f20d9", - "sha256:5d6b4af7ad7e4ac515bc6e602e7b79e2204e25dbd10ab3aa2beef3c5a9cad2c7", - "sha256:5decdc78849617917c206b01e9fc1d694fd58caa961be816cb37d3150d613d9a", - "sha256:632ecbbd2228575e6860c9e49ea3cc5423764d5aa70b92acc4e74096fb434044", - "sha256:65b998193bd7b0c7ecdfffbc825d808eac66279313cb67d8892bb259c9d91494", - "sha256:67093a526e42981fdd954868062e56c9b67fdd7e712616cc3265ad0c210ecb51", - "sha256:681eb4d37c9a9a6eb9b3245a5e89d7f7b2b9895590bb08a20aa598c1eb0a1d9d", - "sha256:69bd56b1d257a91e763256d63606937ae4eb890b18a789b66951c00062afec33", - "sha256:724c1fe135aa437d5126138d977004d165a3b5e2ee98fc4eb3e7c0ef645e7e27", - "sha256:7255a37ff50593c9b2f1afa8fafd6ef5763213c1ed5a9e2c6f5b9cc925ab979f", - "sha256:743cd768affaa508a21499f4858c5b824ffa2e1394ed94eb85caf47ac0732198", - "sha256:80d3bc9944be1d73e5b1726c3bbfd2628d3d7fe2880711b1eb90b617b9b8ac70", - "sha256:82ff356ff91be0ab2293fc6d8d262451eb6ac4fd999244c4b5f863e049ba219c", - "sha256:8e8607d8f6b4f9d46fee11447e334d6ab50e993dd4dbfb22f674616ce20907ab", - "sha256:97202f939c3ff341fc3fa84d15db86156b1edc669424ba20b0a1fcd4a796a045", - "sha256:9b01e7b00654115965a206e3015f0166674ec1e575198a62a977355597c0bef5", - "sha256:9fa621b3c0c05d965882c920347b6593751b7ab20d8fa81e426f1735ca1a9fc7", - "sha256:a1aa6e4cae8e3b8d5321be4f51c5ce77188faf7baa9fe1e78611f93a8eed2882", - "sha256:a2d30d6c1652140181dc6861f564449ad71a45e4f165a6868c27d36745b65d40", - "sha256:a649d0f66029c7eb67042b15374bd93a26aae202591d9afd71e111dd0006b198", - "sha256:a7854326920d41c3b5d468154318fe6ba4390cb2410480976787c640707e0180", - "sha256:a89acae02b2975b1f8e4974cb8cdf9bf9f6c91162fb8dec50c259ce700f2770a", - "sha256:a8bbdb166e2fb816e43ab034c865147edafe28e1b19c72433147789ac83e2dda", - "sha256:ac786f6cb7aa10d44e9641c7a7d16d7f6e095b138795cd43503769d4154e0dc2", - "sha256:b09bc62e5193e31d7f9876220fb429ec13a6a181a24d897b9edfbbdbcd678851", - "sha256:b10556817f09d46d420edd982dd0653940b90151d0576f09143a8e773459f6fe", - "sha256:b81076552d34c27e5149a40187a8f7e2abb2d3185576a317aaf14aeeedad862a", - "sha256:bdfc54b4468ed4cd7415928cbe782f4d782722a81aeb0f81e2ddca9932632211", - "sha256:cf6e7d5fe2aeb54898df18db1baf479863eae581cce05410f61f6b4188c8ada1", - "sha256:cf98038d2abf63a1ada5730e91e84c642ba6c225b0198c3684151b1f80c5f8a6", - "sha256:d24a9e61df7a7787b338a58abfba975414937b609eb6b18973e25f573bc0eeeb", - "sha256:d74ee72b5071818a1a5dab47338e87f08a738cb938a3b0653b9e4d959ddd1fd9", - "sha256:dd16302d39c4d6f4afde80edd0c97d4db643327d355a312762ccd9bd2ca515ed", - "sha256:dd2fb11922f58df8528adfca123f6a84748ad17d066007e7ac977720063556bd", - "sha256:deac4bdafa19bbb89edfb73b19f7f69a52d0b5bd3bb0c4ad404c1bbfd7b4b7fd", - "sha256:e03c3b8cc7883a54c3f34a6a135c4a17bc9088a33f36796acdb47162791b02f6", - "sha256:e1ec8a9ee0987d4524ffd6299e778c16cc35fef6d1a2764e609f90962f0b293a", - "sha256:e8603e691580487f11306ecb066c76f1f4a8b54fb3bdb23fa40643a059509366", - "sha256:f444762fed1bc1fd75187ef14a20ed900c1fbb245d45be9e834b822a0223bc81", - "sha256:f63600ec06982cdf480899026f4fda622776f5fabed9a869fdb32d72bc17e99a", - "sha256:fb62d517a516128bacf08cb6a86ecd39fb06d08e7c4980251f5d5601d29989ba" - ], - "index": "pypi", - "version": "==3.17.6" - }, - "six": { - "hashes": [ - "sha256:1e61c37477a1626458e36f7b1d82aa5c9b094fa4802892072e49de9c60c4c926", - "sha256:8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254" - ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", - "version": "==1.16.0" - }, - "snakeviz": { - "hashes": [ - "sha256:0d96c006304f095cb4b3fb7ed98bb866ca35a7ca4ab9020bbc27d295ee4c94d9", - "sha256:931142dc927101c9a4b6e89bc0577ff1a3d1886b483a04e6af70c31d2c3dce19" - ], - "index": "pypi", - "version": "==2.1.1" - }, - "tornado": { - "hashes": [ - "sha256:1d54d13ab8414ed44de07efecb97d4ef7c39f7438cf5e976ccd356bebb1b5fca", - "sha256:20f638fd8cc85f3cbae3c732326e96addff0a15e22d80f049e00121651e82e72", - "sha256:5c87076709343557ef8032934ce5f637dbb552efa7b21d08e89ae7619ed0eb23", - "sha256:5f8c52d219d4995388119af7ccaa0bcec289535747620116a58d830e7c25d8a8", - "sha256:6fdfabffd8dfcb6cf887428849d30cf19a3ea34c2c248461e1f7d718ad30b66b", - "sha256:87dcafae3e884462f90c90ecc200defe5e580a7fbbb4365eda7c7c1eb809ebc9", - "sha256:9b630419bde84ec666bfd7ea0a4cb2a8a651c2d5cccdbdd1972a0c859dfc3c13", - "sha256:b8150f721c101abdef99073bf66d3903e292d851bee51910839831caba341a75", - "sha256:ba09ef14ca9893954244fd872798b4ccb2367c165946ce2dd7376aebdde8e3ac", - "sha256:d3a2f5999215a3a06a4fc218026cd84c61b8b2b40ac5296a6db1f1451ef04c1e", - "sha256:e5f923aa6a47e133d1cf87d60700889d7eae68988704e20c75fb2d65677a8e4b" - ], - "markers": "python_version >= '3.7'", - "version": "==6.2" - }, - "typing-extensions": { - "hashes": [ - "sha256:25642c956049920a5aa49edcdd6ab1e06d7e5d467fc00e0506c44ac86fbfca02", - "sha256:e6d2677a32f47fc7eb2795db1dd15c1f34eff616bcaf2cfb5e997f854fa1c4a6" - ], - "markers": "python_version < '3.9'", - "version": "==4.3.0" - }, - "urllib3": { - "hashes": [ - "sha256:3fa96cf423e6987997fc326ae8df396db2a8b7c667747d47ddd8ecba91f4a74e", - "sha256:b930dd878d5a8afb066a637fbb35144fe7901e3b209d1cd4f524bd0e9deee997" - ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4, 3.5' and python_version < '4'", - "version": "==1.26.12" - } - }, - "develop": { - "attrs": { - "hashes": [ - "sha256:29adc2665447e5191d0e7c568fde78b21f9672d344281d0c6e1ab085429b22b6", - "sha256:86efa402f67bf2df34f51a335487cf46b1ec130d02b8d39fd248abfd30da551c" - ], - "markers": "python_version >= '3.5'", - "version": "==22.1.0" - }, - "colorama": { - "hashes": [ - "sha256:854bf444933e37f5824ae7bfc1e98d5bce2ebe4160d46b5edf346a89358e99da", - "sha256:e6c6b4334fc50988a639d9b98aa429a0b57da6e17b9a44f0451f930b6967b7a4" - ], - "markers": "sys_platform == 'win32'", - "version": "==0.4.5" - }, - "coverage": { - "extras": [ - "toml" - ], - "hashes": [ - "sha256:01778769097dbd705a24e221f42be885c544bb91251747a8a3efdec6eb4788f2", - "sha256:08002f9251f51afdcc5e3adf5d5d66bb490ae893d9e21359b085f0e03390a820", - "sha256:1238b08f3576201ebf41f7c20bf59baa0d05da941b123c6656e42cdb668e9827", - "sha256:14a32ec68d721c3d714d9b105c7acf8e0f8a4f4734c811eda75ff3718570b5e3", - "sha256:15e38d853ee224e92ccc9a851457fb1e1f12d7a5df5ae44544ce7863691c7a0d", - "sha256:354df19fefd03b9a13132fa6643527ef7905712109d9c1c1903f2133d3a4e145", - "sha256:35ef1f8d8a7a275aa7410d2f2c60fa6443f4a64fae9be671ec0696a68525b875", - "sha256:4179502f210ebed3ccfe2f78bf8e2d59e50b297b598b100d6c6e3341053066a2", - "sha256:42c499c14efd858b98c4e03595bf914089b98400d30789511577aa44607a1b74", - "sha256:4b7101938584d67e6f45f0015b60e24a95bf8dea19836b1709a80342e01b472f", - "sha256:564cd0f5b5470094df06fab676c6d77547abfdcb09b6c29c8a97c41ad03b103c", - "sha256:5f444627b3664b80d078c05fe6a850dd711beeb90d26731f11d492dcbadb6973", - "sha256:6113e4df2fa73b80f77663445be6d567913fb3b82a86ceb64e44ae0e4b695de1", - "sha256:61b993f3998ee384935ee423c3d40894e93277f12482f6e777642a0141f55782", - "sha256:66e6df3ac4659a435677d8cd40e8eb1ac7219345d27c41145991ee9bf4b806a0", - "sha256:67f9346aeebea54e845d29b487eb38ec95f2ecf3558a3cffb26ee3f0dcc3e760", - "sha256:6913dddee2deff8ab2512639c5168c3e80b3ebb0f818fed22048ee46f735351a", - "sha256:6a864733b22d3081749450466ac80698fe39c91cb6849b2ef8752fd7482011f3", - "sha256:7026f5afe0d1a933685d8f2169d7c2d2e624f6255fb584ca99ccca8c0e966fd7", - "sha256:783bc7c4ee524039ca13b6d9b4186a67f8e63d91342c713e88c1865a38d0892a", - "sha256:7a98d6bf6d4ca5c07a600c7b4e0c5350cd483c85c736c522b786be90ea5bac4f", - "sha256:8d032bfc562a52318ae05047a6eb801ff31ccee172dc0d2504614e911d8fa83e", - "sha256:98c0b9e9b572893cdb0a00e66cf961a238f8d870d4e1dc8e679eb8bdc2eb1b86", - "sha256:9c7b9b498eb0c0d48b4c2abc0e10c2d78912203f972e0e63e3c9dc21f15abdaa", - "sha256:9cc4f107009bca5a81caef2fca843dbec4215c05e917a59dec0c8db5cff1d2aa", - "sha256:9d6e1f3185cbfd3d91ac77ea065d85d5215d3dfa45b191d14ddfcd952fa53796", - "sha256:a095aa0a996ea08b10580908e88fbaf81ecf798e923bbe64fb98d1807db3d68a", - "sha256:a3b2752de32c455f2521a51bd3ffb53c5b3ae92736afde67ce83477f5c1dd928", - "sha256:ab066f5ab67059d1f1000b5e1aa8bbd75b6ed1fc0014559aea41a9eb66fc2ce0", - "sha256:c1328d0c2f194ffda30a45f11058c02410e679456276bfa0bbe0b0ee87225fac", - "sha256:c35cca192ba700979d20ac43024a82b9b32a60da2f983bec6c0f5b84aead635c", - "sha256:cbbb0e4cd8ddcd5ef47641cfac97d8473ab6b132dd9a46bacb18872828031685", - "sha256:cdbb0d89923c80dbd435b9cf8bba0ff55585a3cdb28cbec65f376c041472c60d", - "sha256:cf2afe83a53f77aec067033199797832617890e15bed42f4a1a93ea24794ae3e", - "sha256:d5dd4b8e9cd0deb60e6fcc7b0647cbc1da6c33b9e786f9c79721fd303994832f", - "sha256:dfa0b97eb904255e2ab24166071b27408f1f69c8fbda58e9c0972804851e0558", - "sha256:e16c45b726acb780e1e6f88b286d3c10b3914ab03438f32117c4aa52d7f30d58", - "sha256:e1fabd473566fce2cf18ea41171d92814e4ef1495e04471786cbc943b89a3781", - "sha256:e3d3c4cc38b2882f9a15bafd30aec079582b819bec1b8afdbde8f7797008108a", - "sha256:e431e305a1f3126477abe9a184624a85308da8edf8486a863601d58419d26ffa", - "sha256:e7b4da9bafad21ea45a714d3ea6f3e1679099e420c8741c74905b92ee9bfa7cc", - "sha256:ee2b2fb6eb4ace35805f434e0f6409444e1466a47f620d1d5763a22600f0f892", - "sha256:ee6ae6bbcac0786807295e9687169fba80cb0617852b2fa118a99667e8e6815d", - "sha256:ef6f44409ab02e202b31a05dd6666797f9de2aa2b4b3534e9d450e42dea5e817", - "sha256:f67cf9f406cf0d2f08a3515ce2db5b82625a7257f88aad87904674def6ddaec1", - "sha256:f855b39e4f75abd0dfbcf74a82e84ae3fc260d523fcb3532786bcbbcb158322c", - "sha256:fc600f6ec19b273da1d85817eda339fb46ce9eef3e89f220055d8696e0a06908", - "sha256:fcbe3d9a53e013f8ab88734d7e517eb2cd06b7e689bedf22c0eb68db5e4a0a19", - "sha256:fde17bc42e0716c94bf19d92e4c9f5a00c5feb401f5bc01101fdf2a8b7cacf60", - "sha256:ff934ced84054b9018665ca3967fc48e1ac99e811f6cc99ea65978e1d384454b" - ], - "markers": "python_version >= '3.7'", - "version": "==6.4.4" - }, - "flake8": { - "hashes": [ - "sha256:6fbe320aad8d6b95cec8b8e47bc933004678dc63095be98528b7bdd2a9f510db", - "sha256:7a1cf6b73744f5806ab95e526f6f0d8c01c66d7bbe349562d22dfca20610b248" - ], - "index": "pypi", - "version": "==5.0.4" - }, - "iniconfig": { - "hashes": [ - "sha256:011e24c64b7f47f6ebd835bb12a743f2fbe9a26d4cecaa7f53bc4f35ee9da8b3", - "sha256:bc3af051d7d14b2ee5ef9969666def0cd1a000e121eaea580d4a313df4b37f32" - ], - "version": "==1.1.1" - }, - "mccabe": { - "hashes": [ - "sha256:348e0240c33b60bbdf4e523192ef919f28cb2c3d7d5c7794f74009290f236325", - "sha256:6c2d30ab6be0e4a46919781807b4f0d834ebdd6c6e3dca0bda5a15f863427b6e" - ], - "markers": "python_version >= '3.6'", - "version": "==0.7.0" - }, - "mypy": { - "hashes": [ - "sha256:02ef476f6dcb86e6f502ae39a16b93285fef97e7f1ff22932b657d1ef1f28655", - "sha256:0d054ef16b071149917085f51f89555a576e2618d5d9dd70bd6eea6410af3ac9", - "sha256:19830b7dba7d5356d3e26e2427a2ec91c994cd92d983142cbd025ebe81d69cf3", - "sha256:1f7656b69974a6933e987ee8ffb951d836272d6c0f81d727f1d0e2696074d9e6", - "sha256:23488a14a83bca6e54402c2e6435467a4138785df93ec85aeff64c6170077fb0", - "sha256:23c7ff43fff4b0df93a186581885c8512bc50fc4d4910e0f838e35d6bb6b5e58", - "sha256:25c5750ba5609a0c7550b73a33deb314ecfb559c350bb050b655505e8aed4103", - "sha256:2ad53cf9c3adc43cf3bea0a7d01a2f2e86db9fe7596dfecb4496a5dda63cbb09", - "sha256:3fa7a477b9900be9b7dd4bab30a12759e5abe9586574ceb944bc29cddf8f0417", - "sha256:40b0f21484238269ae6a57200c807d80debc6459d444c0489a102d7c6a75fa56", - "sha256:4b21e5b1a70dfb972490035128f305c39bc4bc253f34e96a4adf9127cf943eb2", - "sha256:5a361d92635ad4ada1b1b2d3630fc2f53f2127d51cf2def9db83cba32e47c856", - "sha256:77a514ea15d3007d33a9e2157b0ba9c267496acf12a7f2b9b9f8446337aac5b0", - "sha256:855048b6feb6dfe09d3353466004490b1872887150c5bb5caad7838b57328cc8", - "sha256:9796a2ba7b4b538649caa5cecd398d873f4022ed2333ffde58eaf604c4d2cb27", - "sha256:98e02d56ebe93981c41211c05adb630d1d26c14195d04d95e49cd97dbc046dc5", - "sha256:b793b899f7cf563b1e7044a5c97361196b938e92f0a4343a5d27966a53d2ec71", - "sha256:d1ea5d12c8e2d266b5fb8c7a5d2e9c0219fedfeb493b7ed60cd350322384ac27", - "sha256:d2022bfadb7a5c2ef410d6a7c9763188afdb7f3533f22a0a32be10d571ee4bbe", - "sha256:d3348e7eb2eea2472db611486846742d5d52d1290576de99d59edeb7cd4a42ca", - "sha256:d744f72eb39f69312bc6c2abf8ff6656973120e2eb3f3ec4f758ed47e414a4bf", - "sha256:ef943c72a786b0f8d90fd76e9b39ce81fb7171172daf84bf43eaf937e9f220a9", - "sha256:f2899a3cbd394da157194f913a931edfd4be5f274a88041c9dc2d9cdcb1c315c" - ], - "index": "pypi", - "version": "==0.971" - }, - "mypy-extensions": { - "hashes": [ - "sha256:090fedd75945a69ae91ce1303b5824f428daf5a028d2f6ab8a299250a846f15d", - "sha256:2d82818f5bb3e369420cb3c4060a7970edba416647068eb4c5343488a6c604a8" - ], - "version": "==0.4.3" - }, - "numpy": { - "hashes": [ - "sha256:0cfe07133fd00b27edee5e6385e333e9eeb010607e8a46e1cd673f05f8596595", - "sha256:11a1f3816ea82eed4178102c56281782690ab5993251fdfd75039aad4d20385f", - "sha256:2762331de395739c91f1abb88041f94a080cb1143aeec791b3b223976228af3f", - "sha256:283d9de87c0133ef98f93dfc09fad3fb382f2a15580de75c02b5bb36a5a159a5", - "sha256:3d22662b4b10112c545c91a0741f2436f8ca979ab3d69d03d19322aa970f9695", - "sha256:41388e32e40b41dd56eb37fcaa7488b2b47b0adf77c66154d6b89622c110dfe9", - "sha256:42c16cec1c8cf2728f1d539bd55aaa9d6bb48a7de2f41eb944697293ef65a559", - "sha256:47ee7a839f5885bc0c63a74aabb91f6f40d7d7b639253768c4199b37aede7982", - "sha256:5a311ee4d983c487a0ab546708edbdd759393a3dc9cd30305170149fedd23c88", - "sha256:5dc65644f75a4c2970f21394ad8bea1a844104f0fe01f278631be1c7eae27226", - "sha256:6ed0d073a9c54ac40c41a9c2d53fcc3d4d4ed607670b9e7b0de1ba13b4cbfe6f", - "sha256:76ba7c40e80f9dc815c5e896330700fd6e20814e69da9c1267d65a4d051080f1", - "sha256:818b9be7900e8dc23e013a92779135623476f44a0de58b40c32a15368c01d471", - "sha256:a024181d7aef0004d76fb3bce2a4c9f2e67a609a9e2a6ff2571d30e9976aa383", - "sha256:a955e4128ac36797aaffd49ab44ec74a71c11d6938df83b1285492d277db5397", - "sha256:a97a954a8c2f046d3817c2bce16e3c7e9a9c2afffaf0400f5c16df5172a67c9c", - "sha256:a97e82c39d9856fe7d4f9b86d8a1e66eff99cf3a8b7ba48202f659703d27c46f", - "sha256:b55b953a1bdb465f4dc181758570d321db4ac23005f90ffd2b434cc6609a63dd", - "sha256:bb02929b0d6bfab4c48a79bd805bd7419114606947ec8284476167415171f55b", - "sha256:bece0a4a49e60e472a6d1f70ac6cdea00f9ab80ff01132f96bd970cdd8a9e5a9", - "sha256:e41e8951749c4b5c9a2dc5fdbc1a4eec6ab2a140fdae9b460b0f557eed870f4d", - "sha256:f71d57cc8645f14816ae249407d309be250ad8de93ef61d9709b45a0ddf4050c" - ], - "index": "pypi", - "version": "==1.22.0" - }, - "packaging": { - "hashes": [ - "sha256:dd47c42927d89ab911e606518907cc2d3a1f38bbd026385970643f9c5b8ecfeb", - "sha256:ef103e05f519cdc783ae24ea4e2e0f508a9c99b2d4969652eed6a2e1ea5bd522" - ], - "markers": "python_version >= '3.6'", - "version": "==21.3" - }, - "pandas": { - "hashes": [ - "sha256:050aada67a5ec6699a7879e769825b510018a95fb9ac462bb1867483d0974a97", - "sha256:0959c41004e3d2d16f39c828d6da66ebee329836a7ecee49fb777ac9ad8a7501", - "sha256:4591cadd06fbbbd16fafc2de6e840c1aaefeae3d5864b688004777ef1bbdede3", - "sha256:51c424ca134fdaeac9a4acd719d1ab48046afc60943a489028f0413fdbe9ef1c", - "sha256:785e878a6e6d8ddcdb8c181e600855402750052497d7fc6d6b508894f6b8830b", - "sha256:799e6a25932df7e6b1f8dabf63de064e2205dc309abb75956126a0453fd88e97", - "sha256:7cd1d69a387f7d5e1a5a06a87574d9ef2433847c0e78113ab51c84d3a8bcaeaa", - "sha256:87b4194f344dcd14c0f885cecb22005329b38bda10f1aaf7b9596a00ec8a4768", - "sha256:8d4d2fe2863ecddb0ba1979bdda26c8bc2ea138f5a979abe3ba80c0fa4015c91", - "sha256:94f2ed1fd51e545ebf71da1e942fe1822ee01e10d3dd2a7276d01351333b7c6b", - "sha256:9d2a7a3c1fea668d56bd91edbd5f2732e0af8feb9d2bf8d9bfacb2dea5fa9536", - "sha256:9d805bce209714b1c1fa29bfb1e42ad87e4c0a825e4b390c56a3e71593b7e8d8", - "sha256:a08ceb59db499864c58a9bf85ab6219d527d91f14c0240cc25fa2c261032b2a7", - "sha256:a981cfabf51c318a562deb4ae7deec594c07aee7cf18b4594a92c23718ec8275", - "sha256:ab6c0d738617b675183e5f28db32b5148b694ad9bba0a40c3ea26d96b431db67", - "sha256:afbddad78a98ec4d2ce08b384b81730de1ccc975b99eb663e6dac43703f36d98", - "sha256:c4bb8b0ab9f94207d07e401d24baebfc63057246b1a5e0cd9ee50df85a656871", - "sha256:ce35f947202b0b99c660221d82beb91d2e6d553d55a40b30128204e3e2c63848", - "sha256:d0022fe6a313df1c4869b5edc012d734c6519a6fffa3cf70930f32e6a1078e49", - "sha256:e7cc960959be28d064faefc0cb2aef854d46b827c004ebea7e79b5497ed83e7d", - "sha256:ee6f1848148ed3204235967613b0a32be2d77f214e9623f554511047705c1e04" - ], - "index": "pypi", - "version": "==1.4.4" - }, - "pluggy": { - "hashes": [ - "sha256:4224373bacce55f955a878bf9cfa763c1e360858e330072059e10bad68531159", - "sha256:74134bbf457f031a36d68416e1509f34bd5ccc019f0bcc952c7b909d06b37bd3" - ], - "markers": "python_version >= '3.6'", - "version": "==1.0.0" - }, - "py": { - "hashes": [ - "sha256:51c75c4126074b472f746a24399ad32f6053d1b34b68d2fa41e558e6f4a98719", - "sha256:607c53218732647dff4acdfcd50cb62615cedf612e72d1724fb1a0cc6405b378" - ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4'", - "version": "==1.11.0" - }, - "pycodestyle": { - "hashes": [ - "sha256:2c9607871d58c76354b697b42f5d57e1ada7d261c261efac224b664affdc5785", - "sha256:d1735fc58b418fd7c5f658d28d943854f8a849b01a5d0a1e6f3f3fdd0166804b" - ], - "markers": "python_version >= '3.6'", - "version": "==2.9.1" - }, - "pyflakes": { - "hashes": [ - "sha256:4579f67d887f804e67edb544428f264b7b24f435b263c4614f384135cea553d2", - "sha256:491feb020dca48ccc562a8c0cbe8df07ee13078df59813b83959cbdada312ea3" - ], - "markers": "python_version >= '3.6'", - "version": "==2.5.0" - }, - "pyparsing": { - "hashes": [ - "sha256:2b020ecf7d21b687f219b71ecad3631f644a47f01403fa1d1036b0c6416d70fb", - "sha256:5026bae9a10eeaefb61dab2f09052b9f4307d44aee4eda64b309723d8d206bbc" - ], - "markers": "python_full_version >= '3.6.8'", - "version": "==3.0.9" - }, - "pytest": { - "hashes": [ - "sha256:1377bda3466d70b55e3f5cecfa55bb7cfcf219c7964629b967c37cf0bda818b7", - "sha256:4f365fec2dff9c1162f834d9f18af1ba13062db0c708bf7b946f8a5c76180c39" - ], - "index": "pypi", - "version": "==7.1.3" - }, - "pytest-cov": { - "hashes": [ - "sha256:578d5d15ac4a25e5f961c938b85a05b09fdaae9deef3bb6de9a6e766622ca7a6", - "sha256:e7f0f5b1617d2210a2cabc266dfe2f4c75a8d32fb89eafb7ad9d06f6d076d470" - ], - "index": "pypi", - "version": "==3.0.0" - }, - "python-dateutil": { - "hashes": [ - "sha256:0123cacc1627ae19ddf3c27a5de5bd67ee4586fbdd6440d9748f8abb483d3e86", - "sha256:961d03dc3453ebbc59dbdea9e4e11c5651520a876d0f4db161e8674aae935da9" - ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", - "version": "==2.8.2" - }, - "pytz": { - "hashes": [ - "sha256:220f481bdafa09c3955dfbdddb7b57780e9a94f5127e35456a48589b9e0c0197", - "sha256:cea221417204f2d1a2aa03ddae3e867921971d0d76f14d87abb4414415bbdcf5" - ], - "version": "==2022.2.1" - }, - "six": { - "hashes": [ - "sha256:1e61c37477a1626458e36f7b1d82aa5c9b094fa4802892072e49de9c60c4c926", - "sha256:8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254" - ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", - "version": "==1.16.0" - }, - "tomli": { - "hashes": [ - "sha256:939de3e7a6161af0c887ef91b7d41a53e7c5a1ca976325f429cb46ea9bc30ecc", - "sha256:de526c12914f0c550d15924c62d72abc48d6fe7364aa87328337a31007fe8a4f" - ], - "version": "==2.0.1" - }, - "typing-extensions": { - "hashes": [ - "sha256:25642c956049920a5aa49edcdd6ab1e06d7e5d467fc00e0506c44ac86fbfca02", - "sha256:e6d2677a32f47fc7eb2795db1dd15c1f34eff616bcaf2cfb5e997f854fa1c4a6" - ], - "markers": "python_version < '3.9'", - "version": "==4.3.0" - } - } -} diff --git a/README.md b/README.md index 9eee8de8..43c210de 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,23 @@ # Autonomy Software -![GitHub release (latest by date)](https://img.shields.io/github/v/release/MissouriMRDT/Autonomy_Software?style=flat) -![GitHub pull requests](https://img.shields.io/github/issues-pr/MissouriMRDT/Autonomy_Software?style=flat) -![GitHub issues](https://img.shields.io/github/issues/MissouriMRDT/Autonomy_Software) -![GitHub Workflow Status (branch)](https://img.shields.io/github/workflow/status/MissouriMRDT/Autonomy_Software/Autonomy%20Flake8%20Linter/dev?label=flake8%20linter&style=flat) -![GitHub Workflow Status (branch)](https://img.shields.io/github/workflow/status/MissouriMRDT/Autonomy_Software/Autonomy%20Unit%20Tests/dev?label=unit%20tests&style=flat) +![GitHub release (latest by date)](https://img.shields.io/github/v/release/MissouriMRDT/Autonomy_Software_Python?style=flat) +![GitHub pull requests](https://img.shields.io/github/issues-pr/MissouriMRDT/Autonomy_Software_Python?style=flat) +![GitHub issues](https://img.shields.io/github/issues/MissouriMRDT/Autonomy_Software_Python) +![GitHub Workflow Status (branch)](https://img.shields.io/github/workflow/status/MissouriMRDT/Autonomy_Software_Python/Autonomy%20Flake8%20Linter/dev?label=flake8%20linter&style=flat) +![GitHub Workflow Status (branch)](https://img.shields.io/github/workflow/status/MissouriMRDT/Autonomy_Software_Python/Autonomy%20Unit%20Tests/dev?label=unit%20tests&style=flat) This repo contains the Autonomy software stack for the current iteration of the Mars Rover Design Team's Rover designed to compete at the University Rover Challenge. The software is developed to run on a Jetson Xavier NX development board. +## Getting Set Up + +There are a couple of simple steps in order to get started writing software for the Autonomy system. + +1. Clone the repo in an appropriate place. Standard practice is to clone it inside a directory such as RoverSoftware. + +``` +git clone --recurse-submodules -j8 https://github.com/MissouriMRDT/Autonomy_Software_Python.git +``` 2. Install Python 3.8, and then install pipenv using pip diff --git a/algorithms/__init__.py b/algorithms/__init__.py index b1402549..98905e67 100644 --- a/algorithms/__init__.py +++ b/algorithms/__init__.py @@ -12,7 +12,9 @@ from algorithms import heading_hold as heading_hold from algorithms import marker_search as marker_search from algorithms import pid_controller as PID_controller +from algorithms import small_movements as small_movements from algorithms import obstacle_detector as obstacle_detector from algorithms import obstacle_avoider as obstacle_avoider +from algorithms import stanley_controller as stanley_controller from algorithms import ar_tag as ar_tag from algorithms import helper_funcs as helper_funcs diff --git a/algorithms/ar_tag.py b/algorithms/ar_tag.py index 04671df3..12b93de8 100644 --- a/algorithms/ar_tag.py +++ b/algorithms/ar_tag.py @@ -1,95 +1,251 @@ -# -# Mars Rover Design Team -# ar_tag.py -# -# Created on Oct 22, 2020 -# Updated on Aug 21, 2022 -# - import cv2 -import logging +from numpy import NaN import itertools -import numpy as np - import core +import math +import numpy as np +import interfaces +import core.constants +from geopy.distance import VincentyDistance +from geopy import Point -from numpy.core.numeric import NaN -from collections import namedtuple - -tag_cascade = cv2.CascadeClassifier("resources/tag_detection/cascade30.xml") - -Tag = namedtuple("Tag", ["cX", "cY", "distance", "angle"]) +class Tag: + def __init__(self, id, center): + """ + Creates an object of Tag. -def detect_ar_tag(reg_img): - """ - Detects an AR Tag in the provided color image + :param id: The id that was found. + :param gps: The coordinates of the tag (lat, long). + :param corner: The four corner points of the aruco tag for distance calculations. - :param reg_img: color image to locate ar tags in - :return: tags, reg_img - """ + :return: None + """ + self.id = id + self.cX, self.cY = center + self.times_detected = 1 + self.distance = 0 + self.angle = 0 - gray = cv2.cvtColor(reg_img, cv2.COLOR_BGR2GRAY) - tags_coords = tag_cascade.detectMultiScale(gray, 1.3, 5) + # Get tag info. + self.refresh(center) - tags = [] - for (x, y, w, h) in tags_coords: - reg_img = cv2.rectangle(reg_img, (x, y), (x + w, y + h), (255, 0, 0), 2) + def refresh(self, center): + """ + Updates tag info. - # Calculate the center points of the AR Tag - cX = x + (w / 2) - cY = y + (h / 2) - # Find the distance/angle of said center pixels - distance, angle = track_ar_tag((cX, cY)) - tags.append(Tag(cX, cY, distance, angle)) + :param: None - return tags, reg_img + :return: Nothing + """ + # Update tag center. + self.cX, self.cY = center + # Grab the camera parameters + img_res_x, img_res_y = core.vision.camera_handler.get_reg_res() -def track_ar_tag(center): - """ - Track the distance and angle of the AR Tag from the perspective of the Rover. + # Scale ar tag value between image resolutions. + depth_cX = int((self.cX * (core.vision.camera_handler.depth_res_x)) / (img_res_x)) + depth_cY = int((self.cY * (core.vision.camera_handler.depth_res_y)) / (img_res_y)) - :param center: the X, Y of the center pixels of the AR Tag - :return: distance (meters), angle (left is negative, right is positive) - """ + # Grab the distance from the depth map + self.distance = NaN - logger = logging.getLogger(__name__) + # Find some permutations we can use in case of noisy data + coordinates = [0, 1, -1, 2, -2, 3, -3, 4, -4] + perm = list(itertools.permutations(coordinates, 2)) - # Center coordinates - cX, cY = center + # Grab the distance from the depth map, iterating over pixels if the distance is not finite + index = 0 - # Depth image is at half resolution - cX = int(cX / 2) - cY = int(cY / 2) + while not np.isfinite(self.distance) and index < len(perm): + if index < len(perm): + self.distance = core.vision.camera_handler.grab_depth_data()[depth_cY + perm[index][1]][ + depth_cX + perm[index][0] + ] + # If distance is equal to or greater than 40000 (max zed and sim range), then set distance to 40 meters. + if self.distance >= 40000: + self.distance = 40001 + index += 1 - # Grab the distance from the depth map - distance = NaN + # Vision system reports depth in mm, we want in meters + self.distance /= 1000 - # Find some permutations we can use in case of noisy data - coordinates = [0, 1, -1, 2, -2, 3, -3, 4, -4] - perm = list(itertools.permutations(coordinates, 2)) + hfov = core.vision.camera_handler.get_hfov() - # Grab the distance from the depth map, iterating over pixels if the distance is not finite - index = 0 + # Calculate the angle of the object using camera params + angle_per_pixel = hfov / img_res_x + pixel_offset = self.cX - (img_res_x / 2) + self.angle = pixel_offset * angle_per_pixel - while not np.isfinite(distance) and index < len(perm): - if index < len(perm): - distance = core.vision.camera_handler.grab_depth_data()[cY + perm[index][1]][cX + perm[index][0]] - index += 1 + # Calculate absolute heading of the obstacle relative to the rover. + heading = (interfaces.nav_board.heading() + self.angle) % 360 + rover_location = interfaces.nav_board.location() - # Vision system reports depth in mm, we want in meters - distance /= 1000 - # Grab the camera parameters - img_res_x, img_res_y = core.vision.camera_handler.get_depth_res() - hfov = core.vision.camera_handler.get_hfov() +class ArucoARTagDetector: + """ + Class for detecting, organizing, filtering, and updating information about + AR tags in a sequence of images. + """ - # Calculate the angle of the object using camera params - angle_per_pixel = hfov / img_res_x - pixel_offset = cX - (img_res_x / 2) - angle = pixel_offset * angle_per_pixel + def __init__(self) -> None: + """ + Create class member varaibles and objects. + """ + self.tag_list = [] + + # Setup aruco detection object. + dictionary = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_4X4_50) + parameters = cv2.aruco.DetectorParameters() + parameters.markerBorderBits = core.constants.ARUCO_MARKER_BORDER_BITS + parameters.errorCorrectionRate = core.constants.ARUCO_ERROR_CORRECTION_RATE + self.detector = cv2.aruco.ArucoDetector(dictionary, parameters) + + def add_tag(self, tag_id, corners) -> None: + """ + Creates a new Object of Tag and adds in to the tag list. + + :param id: The aruco tag id number. + :param corners: The four corners of the tag. + + :return: None + """ + # Unpack corner points. + x1 = corners[0][0][0] # top left x coord + y1 = corners[0][0][1] # top left y coord + x2 = corners[0][1][0] # top right x coord + y2 = corners[0][3][1] # bottom left y coord - logger.info(f"Distance to marker: {distance} at pixel ({cX}, {cY})") - logger.info(f"Angle to marker: {angle}") - return distance, angle + # Calculate the center points of the AR Tag + cX = (x1 + x2) / 2 + cY = (y1 + y2) / 2 + + # Make sure tag_id is valid. + if tag_id <= 5: + # Check if a tag with the same ID is already in the list. + if tag_id in [tag.id for tag in self.tag_list]: + # Don't add duplicate tag, just increment times_detected. + # Find the tag with matching id. + for tag in self.tag_list: + if tag.id == tag_id: + # Don't go over detection limit. + if tag.times_detected < core.constants.ARUCO_MAX_FRAMES_DETECTED: + if (core.states.state_machine.get_state_str() != "ApproachingGate"): + # Increment number of times tag has been seen. + tag.times_detected += 1 + + # Refresh tag distance and angle. + tag.refresh((cX, cY)) + else: + self.tag_list.append(Tag(tag_id, (cX, cY))) + + def detect_ar_tag(self, reg_img): + """ + Detects an AR Tags in the provided color image. Adds them to the classes tag list after creating + a Tag object from each of them. Before adding the tag it checks if a tag with the same ID already exists + in the list. If it does, then the time_detected counter for the Tag object already in the list is incremented. + This is better than trying to compare relative tag locations, which is inaccurate. This method only works because + we will never see two of the same tags next to eachother in comp. + + :param reg_img: The provided image we are looking at to find ar tags. + + :return: None + """ + + # Convert frame to grayscale for easier detection. + gray = cv2.cvtColor(reg_img, cv2.COLOR_BGR2GRAY) + + # Capture Tags + detected_corners, detected_ids, _ = self.detector.detectMarkers(gray) + + # Make sure at least one tag is detected. + if detected_corners is not None and detected_ids is not None: + # Loop through all detected tags and add them to list. + for tag_id, tag_corners in zip(detected_ids, detected_corners): + # Unpack. + tag_id = tag_id[0] + # Add tag, this method doesn't care about filtering. It just adds all raw tag data. + self.add_tag(tag_id, tag_corners) + # If no tags are detected, then decrement the times_detected from all current tags in the list. + else: + for tag in self.tag_list: + # Decrement detection counter. + tag.times_detected -= 1 + # Check if times_detected has hit zero. + if tag.times_detected <= 0: + # Remove from list. + self.tag_list.remove(tag) + + def filter_ar_tags(self, angle_range=180, distance_range=40, valid_id_range=[1, 2, 3, 4, 5]): + """ + This method filters out bad AR tags from the list given a user defined set of parameters. + + :param angle_range: The +- range that a tag must be in to be considered valid. + :param distance_range: The max distance that a tag can be before being considered invalid. + :param id_range: A list of valid Aruco tag id numbers. + + :return: None + """ + # Create instance variables. + temp_list = [] + + # Loop through tag list. + for tag in self.tag_list: + # Check if tag's ID is in valid id list. + if tag.id in valid_id_range: + # Check if tag distance is valid. + if tag.distance > 0 and tag.distance < distance_range: + # Check if tag angle is valid. + if math.fabs(tag.angle) < angle_range: + # Add tag to temp_list. + temp_list.append(tag) + + # Set class member tag list to newly created temp list. + self.tag_list = temp_list + + def track_ar_tags(self, reg_img): + """ + This method draws tag info onto the given image. + + :param reg_img: The color image to draw overlay onto. + + :return track_img: The new image with tag overlay. + """ + # Loop through tag array. + for tag in self.tag_list: + # Draw a red dot over each detected (and maybe filtered) tag. + reg_img = cv2.circle(reg_img, (int(tag.cX), int(tag.cY)), radius=0, color=(0, 0, 255), thickness=-1) + # Draw tag info. + reg_img = cv2.putText( + reg_img, + f"ID:{tag.id}\nDIST:{tag.distance}\nANG:{tag.angle}\nDET:{tag.times_detected}", + (int(tag.cX), int(tag.cY)), + fontFace=cv2.FONT_HERSHEY_COMPLEX, + fontScale=1, + color=(0, 0, 255), + thickness=1, + ) + + return reg_img + + def get_tags(self): + """ + Getter method for returning class tag list. + + :params: Nothing + + :return tag_list: The current class tag list. + """ + return self.tag_list + + def clear_tags(self): + """ + Method for clearing tag list. + + :params: None + + :return: Nothing + """ + # Clear tag list. + self.tag_list.clear() diff --git a/algorithms/follow_marker.py b/algorithms/follow_marker.py index e5fdbac9..31503ecf 100644 --- a/algorithms/follow_marker.py +++ b/algorithms/follow_marker.py @@ -12,17 +12,6 @@ import algorithms.heading_hold as hh -def drive_through_gate(): - """ - Drive through a gate composed of two tags - - :return: None - """ - - # TODO: Will attempt to drive through a gate composed of two AR Tags - pass - - def drive_to_marker(speed, angle): """ Returns drive speeds necessary to stay on course towards a single marker diff --git a/algorithms/geomath.py b/algorithms/geomath.py index bd0ecc3d..918c8993 100644 --- a/algorithms/geomath.py +++ b/algorithms/geomath.py @@ -45,3 +45,23 @@ def haversine(lat1, lon1, lat2, lon2): bearing = (bearing + 360) % 360 return bearing, distance + + +def utm_distance(easting1, northing1, easting2, northing2): + """ + Calculate the bearing and distance between two UTM points. + + :param easting1: The UTM easting of the first point. + :param northing1: The UTM northing of the first point. + :param easting2: The UTM easting of the second point. + :param northing2: The UTM northing of the second point. + + :returns bearing: The bearing from point1 to point2. + :returns distance: The distance between point1 and point2. + """ + # Calculate bearing. + bearing = math.degrees(math.atan2(easting2 - easting1, northing2 - northing1)) + # Calculate distance. + distance = math.sqrt(math.pow(easting2 - easting1, 2) + math.pow(northing2 - northing1, 2)) + + return bearing, distance diff --git a/algorithms/gps_navigate.py b/algorithms/gps_navigate.py index bcc36656..01e407c2 100644 --- a/algorithms/gps_navigate.py +++ b/algorithms/gps_navigate.py @@ -12,6 +12,8 @@ import algorithms.geomath as geomath import algorithms.heading_hold as hh import core +#import core.constants +from core.constants import MAX_DRIVE_POWER from core.constants import WAYPOINT_DISTANCE_THRESHOLD @@ -48,7 +50,7 @@ def get_approach_status(goal, location, start, tolerance=WAYPOINT_DISTANCE_THRES return core.ApproachState.APPROACHING -def calculate_move(goal, location, start, speed=150): +def calculate_move(goal, location, start, speed=0.6*MAX_DRIVE_POWER): """ Calculates the necessary left and right speeds to keep the rover on course for goal location @@ -58,7 +60,6 @@ def calculate_move(goal, location, start, speed=150): :param speed: the speed the rover should be going at (defaults to 150) :return: left and right speed in a range from -1000 to 1000 (left_speed, right_speed) """ - logger = logging.getLogger(__name__) (target_heading, target_distance) = geomath.haversine(location.lat, location.lon, goal.lat, goal.lon) @@ -66,7 +67,7 @@ def calculate_move(goal, location, start, speed=150): logger.debug(f"Target distance: {target_distance}") if target_distance < 0.01: - speed = 100 + speed = 0.4 * speed goal_heading = target_heading logger.debug(f"Current heading: {interfaces.nav_board.heading()}, Goal: {goal_heading}") diff --git a/algorithms/heading_hold.py b/algorithms/heading_hold.py index cfd0f4b6..7dbde307 100644 --- a/algorithms/heading_hold.py +++ b/algorithms/heading_hold.py @@ -14,7 +14,7 @@ from algorithms.pid_controller import PIDcontroller -pid = PIDcontroller(Kp=3, Ki=0.25, Kd=0, wraparound=360) +pid = PIDcontroller(Kp=3, Ki=0.3, Kd=0, wraparound=360) def get_motor_power_from_heading(speed, goal_heading): diff --git a/algorithms/marker_search.py b/algorithms/marker_search.py index 4c70a7f3..e9781f8f 100644 --- a/algorithms/marker_search.py +++ b/algorithms/marker_search.py @@ -36,9 +36,15 @@ def calculate_next_coordinate(start, former_goal): # Formula for archimedes spiral is r = aθ, calculate current theta using a known a # (search distance) and a known r (distance to center, or starting point) theta = r / (core.SEARCH_DISTANCE / 1000) - - # Add delta theta to theta - theta += core.DELTA_THETA + # If we are toggled to turn left then make the delta theta negative. + if core.constants.SEARCH_LEFT: + # Invert theta. + theta *= -1 + # Subtract delta theta from theta. + theta -= core.constants.SEARCH_DELTA_THETA + else: + # Add delta theta to theta + theta += core.constants.SEARCH_DELTA_THETA # Now that we have a new θ, calculate the new radius given a and θ r = (core.SEARCH_DISTANCE / 1000) * theta diff --git a/algorithms/obstacle_avoider.py b/algorithms/obstacle_avoider.py index b6764b36..9fc3f5db 100644 --- a/algorithms/obstacle_avoider.py +++ b/algorithms/obstacle_avoider.py @@ -1,85 +1,443 @@ -# -# Mars Rover Design Team -# obstacle_avoider.py -# -# Created on Feb 04, 2021 -# Updated on Aug 21, 2022 -# - +from math import fabs +import math +import interfaces from geopy import Point from geopy.distance import VincentyDistance +import numpy as np +import heapq +import logging +import utm +import core +from core import constants -import interfaces -from algorithms import geomath +# Create logger for file. +logger = logging.getLogger(__name__) -def plan_avoidance_route(angle, distance, obstacle_lat, obstacle_lon, type="Rectangle"): +class Node: + """ + This class serves as an easy way to create 'nodes' within a path. Each node is created as a seperate object + and contains a 'pointer' or reference to its parent node which is a completely seperate object. + Each node also stores its own location, distance, heuristic, and total code withing the path. These values + are not autocalculated and must be determined by the programmer. """ - Plans a series of GPS coordinates around an obstacle, that can be used to navigate - around it and avoid hazardous conditions for the rover - :param angle: the angle of the obstacle - :param distance: the distance from the rover to the obstacle - :param obstacle_lat: The latitude of the given obstacle to avoid - :param obstacle_lon: The longitude of the given obstacle to avoid - :param type: the type of avoidance route, can be "Circle" or "Rectangle" (default) - :return: A list of points around the obstacle that provide a safe path of traversal + def __init__(self, parent=None, position=None): + """ + Initializes the Node class. - """ - if type == "Rectangle": - points = [] - # Find point 3.5m to the right of our current location - right_2M_lat, right_2M_lon = coords_obstacle( - 3.5, - interfaces.nav_board.location()[0], - interfaces.nav_board.location()[1], - (angle + 90) % 360, - ) - points.append((right_2M_lat, right_2M_lon)) + :params parent: A reference to another Node object to treat as the parent. + :params position: A tuple or list (with dimensions (1,2)) that stores integers representing the Nodes position. + """ + # Create object variables. + self.parent = parent + self.position = position - # Now find point 5.5 times the original distance ahead of last point - ahead_5_5X_lat, ahead_5_5X_lon = coords_obstacle(5.5 * distance, right_2M_lat, right_2M_lon, angle) - points.append((ahead_5_5X_lat, ahead_5_5X_lon)) + self.g = 0 # distance from start. + self.h = 0 # heuristic, distance from end. + self.f = 0 # node cost. - # Now move left 3.5m - left_2M_lat, left_2M_lon = coords_obstacle(3.5, ahead_5_5X_lat, ahead_5_5X_lon, (angle - 90) % 360) - points.append((left_2M_lat, left_2M_lon)) + def __eq__(self, other): + """ + Equals operator for comparing two Nodes. Equality based off of position. - # return the GPS coordinates on our route - return points + :returns boolean is_equal: Whether or not the two nodes are equal. + """ + return self.position == other.position - elif type == "Circle": - bearing, radius = geomath.haversine( - interfaces.nav_board.location()[0], interfaces.nav_board.location()[1], obstacle_lat, obstacle_lon - ) - # Convert to meters - radius *= 1000 - # Add in an additional .5 meters to compensate for regular GPS inaccuracy - radius += 0.5 - points = [] + def __repr__(self): + """ + A to_string sort of method to print node stats. + + :returns string output: The node summary output. + """ + return f"{self.position} - g: {self.g} h: {self.h} f: {self.f}" + + def __lt__(self, other): + """ + Defining less than for purposes of heap queue. + + :returns boolean is_less_than: Whether or not this Node is less than the other. + """ + return self.f < other.f + + def __gt__(self, other): + """ + Defining greater than for purposes of heap queue. + + :returns boolean is_greater_than: Whether or not this Node is greater than the other. + """ + return self.f > other.f + + +def return_path(current_node, utm_zone, return_gps=False): + """ + Uses the current node in the heapq and works backwards though the queue, adding the next + parent node to the list of points. + + :param current_node: The current node to working backwards from to build the path. + :param utm_zone: Your current UTM zone on the planet Earth. This must be correct of GPS coords will not be converted correctly. + :param return_gps: Whether or not to conver the coords from utm to gps before returning. + + :returns path: The compiled path containing the lat and lon gps coords. + """ + # Create instance variables. + path = [] + current = current_node + + # Loop backwards through each parent node until none exist. + while current is not None: + # Get coords from node. + coords = current.position - increments = 4 - angle_increments = 90 / (increments - 1) - point_angle = (angle - 90) % 360 + angle_increments + # Check if we should convert utm to gps. + if return_gps: + # Use the given UTM zone to convert the UTM coords back to GPS coords. + coords = utm.to_latlon(*(coords[0], coords[1], utm_zone[0], utm_zone[1])) - for i in range(increments): - points.append(coords_obstacle(radius, obstacle_lat, obstacle_lon, point_angle)) - point_angle += angle_increments + # Append current nodes position. + path.append(coords) + # Set current node equal to current node's parent node. + current = current.parent - # return the GPS coordinates on our route - return points + # Return reversed path. + return path[::-1] def coords_obstacle(distMeters, lat1, lon1, bearing): """ Calculates the lat and lon coords of the obstacle given the current position - :param distMeters: the distance from the current position to the obstacle - :param lat1: the latitude of the current position - :param lon1: the longitude of the current position - :param bearing: the angle from the current position to the obstacle - :return: The coords of the obstacle + :params distMeters: the distance from the current position to the obstacle + :params lat1: the latitude of the current position + :params lon1: the longitude of the current position + :params bearing: the angle from the current position to the obstacle + + :returns gps_location: A tuple with the coords of the obstacle in GPS format. """ + destination = VincentyDistance(meters=distMeters).destination(Point(lat1, lon1), bearing) lat2, lon2 = destination.latitude, destination.longitude return (lat2, lon2) + + +class ASTAR: + def __init__(self, max_queue_length): + """ + Initialize the ASTAR class. + + :param max_queue_length: The max number of obstacles to store in the queue. + """ + # Create class variables. + self.obstacle_coords = [] + self.utm_zone = [] + self.start = Node() + self.end = Node() + self.max_queue_length = max_queue_length + + def update_obstacles( + self, + object_locations, + min_object_distance=1.0, + max_object_distance=15.0, + min_object_angle=-40, + max_object_angle=40, + ): + """ + Loops through the given array of obstacle angles and distances and calculate their GPS->UTM position. + + :params object_locations: A list of tuples containing each objects angle and distance in that order. + :params min_object_distance: the limit before we ignore the object, we are going to hit it. + :params min_object_angle: the angle limit before we ignore the object + :params max_object_angle: the angle limit before we ignore the object + """ + # Loop through each obstacle and calculate their coords and add them to the array. + for object in object_locations: + # Check the object distance to see if it meets the requirements. + if (object[1] > min_object_distance and object[1] < max_object_distance) and ( + object[0] > min_object_angle and object[0] < max_object_angle + ): + # Calculate the absolute heading of the obstacle, in relation to the rover + angle = (interfaces.nav_board.heading() + object[0]) % 360 + + # Find the gps coordinate of the obstacle + try: + obstacle_lat, obstacle_lon = coords_obstacle( + object[1], interfaces.nav_board.location()[0], interfaces.nav_board.location()[1], angle + ) + except Exception: + continue + + # Convert GPS coords to UTM coords. + obstacle_easting, obstacle_northing, _, _ = utm.from_latlon(obstacle_lat, obstacle_lon) + + # Append to array. + self.obstacle_coords.append((obstacle_easting, obstacle_northing)) + # If the length of the array is greater than queue max length, remove the oldest element. + if len(self.obstacle_coords) > self.max_queue_length: + self.obstacle_coords = self.obstacle_coords[1:] + + def update_obstacle_coords(self, object_locations, input_gps=True): + """ + Loops through the given array of obstacle angles and distances and calculate their GPS->UTM position. + + :params object_locations: A list of obstacle coords. Must be 2D list of shape (n, 2) containing only lat,lon or easting, northing. + :params input_gps: Whether or not the input list of coords is in GPS or UTM. + """ + # Loop through each obstacle and calculate their coords and add them to the array. + for object_coord in object_locations: + # Check if the input is in GPS. + if input_gps: + # Convert to UTM. + obstacle_easting, obstacle_northing, _, _ = utm.from_latlon(object_coord[0], object_coord[1]) + # Append to array. + self.obstacle_coords.append((obstacle_easting, obstacle_northing)) + else: + # Append to array. + self.obstacle_coords.append(object_coord) + + # If the length of the array is greater than queue max length, remove the oldest element. + if len(self.obstacle_coords) > self.max_queue_length: + self.obstacle_coords = self.obstacle_coords[1:] + + def clear_obstacles(self): + """ + Empty the obstacle queue. + """ + self.obstacle_coords.clear() + + def get_obstacle_coords(self): + """ + Returns the obstacle coords array. + + :returns coords: Returns a list of GPS locations currently stored in the object array. + """ + # Create instance variables. + coords = [] + + # Check if UTM zone hasn't been set yet. + if len(self.utm_zone) <= 0: + # Get current gps position. + current_gps_pos = (interfaces.nav_board.location()[0], interfaces.nav_board.location()[1]) + # Convert the gps coords to UTM coords. These coords are in meters and they are easier to work with. + current_utm_pos = utm.from_latlon(current_gps_pos[0], current_gps_pos[1]) + self.utm_zone = (current_utm_pos[2], current_utm_pos[3]) + + # Convert each coord to GPS + for object in self.obstacle_coords: + coord = utm.to_latlon(*(object[0], object[1], self.utm_zone[0], self.utm_zone[1])) + coords.append(coord) + + return coords + + def plan_astar_avoidance_route( + self, + max_route_size=10, + near_object_threshold=2.0, + start_gps=None, + return_gps=False, + waypoint_thresh=constants.WAYPOINT_DISTANCE_THRESHOLD, + ): + """ + Uses the given list of object angles and distances, converts those to GPS waypoints, and then uses the A* (astar) + algorithm to find the shortest path around the obstacle to a given endpoint in front of the robot. + This function uses heapq while finding the path as it should be more effecient than using lists. + + :params max_route_size: the max square area available for route planning. + :params near_object_threshold: the minimum distance the rover can get from the objects along the path. + :params start_gps: The start position to use for the path. Will use rover's current GPS position by defualt. + :params return_gps: Whether or not to return the path in GPS coords or UTM. UTM by default. + :params waypoint_thresh: The minimum distance from the goal to consider the path solved. (meters) + + :returns path: A list of gps waypoints around the path that should be safe for traversal. + """ + # Determine start position. + if start_gps is None: + # Get current gps position. + current_gps_pos = (interfaces.nav_board.location()[0], interfaces.nav_board.location()[1]) + else: + # Use given start position. + current_gps_pos = start_gps + # Convert the gps coords to UTM coords. These coords are in meters and they are easier to work with. + current_utm_pos = utm.from_latlon(current_gps_pos[0], current_gps_pos[1]) + self.utm_zone = (current_utm_pos[2], current_utm_pos[3]) + + #################################################################### + # Create start and end node. + #################################################################### + self.start = Node(None, (current_utm_pos[0], current_utm_pos[1])) + # Calculate gps coord fixed distance in front of the rover. + # Find the gps coordinate of the end point. + gps_data = core.waypoint_handler.get_waypoint() + waypoint_goal, _, _ = gps_data.data() + waypoint_goal = utm.from_latlon(waypoint_goal[0], waypoint_goal[1]) + self.end = Node(None, (waypoint_goal[0], waypoint_goal[1])) + + # Create open and closed list. + open_list = [] + closed_list = [] + + # Heapify open list and add our start node. + heapq.heapify(open_list) + heapq.heappush(open_list, self.start) + + # Define a stop condition. + outer_iterations = 0 + max_interations = max_route_size * max_route_size // 2 + + #################################################################### + # Define movement search pattern. In this case check in a grid pattern + # 0.5 meters away from current position. + #################################################################### + offset = constants.AVOIDANCE_PATH_NODE_INCREMENT + adjacent_movements = ( + (0.0, -offset), + (0.0, offset), + (-offset, 0.0), + (offset, 0.0), + (-offset, -offset), + (-offset, offset), + (offset, -offset), + (offset, offset), + ) + + #################################################################### + # Loop until the algorithm has found the end. + #################################################################### + while len(open_list) > 0: + # Increment counter. + outer_iterations += 1 + + # Get the current node. + current_node = heapq.heappop(open_list) + closed_list.append(current_node) + + # Check if we have hit the maximum number of iterations. + if outer_iterations > max_interations: + # Print info message. + logger.warning("Unable to solve path: too many iterations.") + return return_path(current_node, self.utm_zone, return_gps) + + # Found the goal. + if ( + fabs(current_node.position[0] - self.end.position[0]) <= waypoint_thresh + and fabs(current_node.position[1] - self.end.position[1]) <= waypoint_thresh + ): + return return_path(current_node, self.utm_zone, return_gps) + + #################################################################### + # Generate children locations for current node. + #################################################################### + children = [] + for new_position in adjacent_movements: + # Calculate child node position. + child_node_pos = ( + current_node.position[0] + new_position[0], + current_node.position[1] + new_position[1], + ) + + # Check if the new child node is within range of our specified area. + if ( + fabs(child_node_pos[0] - self.start.position[0]) > max_route_size + or fabs(child_node_pos[1] - self.start.position[1]) > max_route_size + ): + continue + + # Make sure we are not close to another object. + coord_to_close = False + for coord in self.obstacle_coords: + # Calculate the straight-line distance of the robot position from the obstacle. + robot_distance_from_obstacle = math.sqrt( + math.pow(current_utm_pos[0] - child_node_pos[0], 2) + + math.pow(current_utm_pos[1] - child_node_pos[1], 2) + ) + # Calculate the straight-line distance of the new node from the obstacle. + node_distance_from_obstacle = math.sqrt( + math.pow(coord[0] - child_node_pos[0], 2) + math.pow(coord[1] - child_node_pos[1], 2) + ) + # Check if we are getting closer to the obstacle. + if node_distance_from_obstacle <= near_object_threshold: + coord_to_close = True + # Check if the robot is within circle radius of obstacle and pick the point that will move us away from it. + if ( + robot_distance_from_obstacle < near_object_threshold + and node_distance_from_obstacle > robot_distance_from_obstacle + ): + coord_to_close = False + # If the current child node is too close to the object skip it. + if coord_to_close: + continue + + # Create new node with child properties. + new_node = Node(current_node, child_node_pos) + # If everything checks out, add node to the list. + children.append(new_node) + + #################################################################### + # Loop through children, calculate cost, make move. + #################################################################### + for child in children: + # Check if child is already on the closed list. + if len([closed_child for closed_child in closed_list if closed_child == child]) > 0: + continue + + # Calculate f, g, and h values. + child.g = current_node.g + offset + child.h = ((child.position[0] - self.end.position[0]) ** 2) + ( + (child.position[1] - self.end.position[1]) ** 2 + ) + child.f = child.g + child.h + + # Check if child is already in the open list or a child exists that has a greater cost. + if ( + len( + [ + open_node + for open_node in open_list + if child.position == open_node.position and child.g > open_node.g + ] + ) + > 0 + ): + continue + + # Add the child to the open list. + heapq.heappush(open_list, child) + + # If unable to calulate path, then return nothing + logger.warning("Couldn't find path around obstacle to destination.") + return None + + def calculate_yaws_from_path(self, cx, cy, start_angle=0.0, radians=True): + """ + Computes the appropiate absolute yaw from a given set of Xs and Ys. These should + produce a sensible path and the two lists should be the same length. + All yaw angle are calulated in radians by default. + + :param cx: The list of x points within the path. + :param cy: The list of y points within the path. + :param start_angle: The initial angle for the first point. + :param radians: Whether of not to use radians for the angle. (On by default) + :return: ([yaws]) An array containing the yaw angles for each point. + """ + # Create instance variables. + yaws = [] + + # Check if both lists are equal size. + if len(cx) == len(cy) and len(cx) > 0: + # Loop through points. The zip function returns iterables for a sublist starting at 0:-1 and a sublist starting at 1:end for each list x and y. + for i, x, y, x_next, y_next in zip(range(len(cx) - 1), cx[:-1], cy[:-1], cx[1:], cy[1:]): + # Basic trig to find angle between two points. + angle = math.atan2((y_next - y), (x_next - x)) + + # Check if we are converting to degrees. + if not radians: + angle = np.rad2deg(angle) + + # Append angle to yaws list. + yaws.append(angle) + + # Copy second to last angle to last point since the last point doesn't have a point after it to find angle from. + yaws.append(yaws[-1]) + + return yaws diff --git a/algorithms/obstacle_detector.py b/algorithms/obstacle_detector.py index d23dd2ac..b2d2c6e8 100644 --- a/algorithms/obstacle_detector.py +++ b/algorithms/obstacle_detector.py @@ -2,158 +2,382 @@ # Mars Rover Design Team # obstacle_detector.py # -# Created on Jan 18, 2021 -# Updated on Aug 21, 2022 +# Created on Dec 23, 2021 +# Updated on Jan 18, 2023 # - +import logging import numpy as np +import torch +import torch.backends.cudnn as cudnn +import core.constants +import core +import math +import os import cv2 -import heapq +import time +from pickle import UnpicklingError -import core +# Import yolov5 tools. +from core.vision.yolov5.models.common import DetectMultiBackend +from core.vision.yolov5.utils.general import check_img_size, non_max_suppression, scale_coords, xyxy2xywh +from core.vision.yolov5.utils.torch_utils import select_device +from core.vision.yolov5.utils.augmentations import letterbox +from core.vision.yolov5.utils.plots import Annotator, colors -def get_floor_mask(reg_img, dimX, dimY): +def img_preprocess(img, device, half, net_size): """ - Returns a cv2 mask that identifies the floor in the provided reg_img of dimensions dimX, dimY. - This currently works through determine the color of the lower 15th of the image and generating - a color mask that removes those colors from the image. - This can then be used to remove the floor from a corresponding depth map/color image. - - :param reg_img: the color image where we will perform floor detection - :param dimX: width in pixels of desire mask (size of image to be applied to) - :param dimY: height in pixels of desire mask (size of image to be applied to) - :return: mask - the mask of the floor - """ - - # Perform various blur operations on the image to enhance accuracy of color segmentation - test_img = cv2.resize(reg_img.copy(), (dimX, dimY)) - test_img = cv2.blur(test_img, (5, 5)) - test_img = cv2.medianBlur(test_img, 5) - test_img = cv2.GaussianBlur(test_img, (5, 5), 0) + Prepares the image from the camera by reformatting it and converting the numpy array to a torch/tensor object + depending on the current device selected. - test_img = cv2.cvtColor(test_img, cv2.COLOR_BGR2HSV) + :params img: The numpy array containing the camera image. + :params device: The device type the array should be optimized for. (CPU or NVIDIA CUDA) + :params half: Boolean determining if all the numbers in the array are converted from 32-bit to 16-bit. + :params net_size: Tuple containing the size of the image. - # Only take the lower 15 of image, and find color range - lower_portion = test_img[int((14 / 15) * dimY) :] - smallest = lower_portion.min(axis=(0, 1)) - largest = lower_portion.max(axis=(0, 1)) - - # Get a mask of the possible range of colors of the floor - mask = cv2.inRange(test_img, smallest, largest) + :returns img: The converted, optimized, and normalized image. + :returns ratio: Tuple containing the width and height ratios. + :returns pad: Tuple containing width and height padding for the image. + """ + net_image, ratio, pad = letterbox(img[:, :, :3], net_size, auto=False) + net_image = net_image.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB + net_image = np.ascontiguousarray(net_image) - # Invert the mask so we select everything BUT the floor - mask = cv2.bitwise_not(mask) + img = torch.from_numpy(net_image).to(device) + img = img.half() if half else img.float() # uint8 to fp16/32 + img /= 255.0 # 0 - 255 to 0.0 - 1.0 - return mask, lower_portion + if img.ndimension() == 3: + img = img.unsqueeze(0) + return img, ratio, pad -def detect_obstacle(depth_matrix, min_depth, max_depth): +def xywh2abcd(xywh, im_shape): """ - Detects an obstacle in the corresponding depth map. This works by filtering the depth map - into distinct segments of depth and then finding contours in that data. The contour with - the biggest area is then used as the obstacle if it meets a certain size requirement. + Given the x and y center point, and the width and height of a rectangle. This method calculates the four + corners of the rectangle in the image and returns those corners in a 2d array. - Currently, we look at the NUM_DEPTH_SEGMENTS the busiest segments (most points) and check in order - of closeness whether they have + :params xywh: 1d array containing the x, y, width, height of the rectangle in terms of image pixels. + :params im_shape: 1d array containing the shape/resolution of the image. - :param depth_matrix: zed depth map - :param min_depth: the minimum depth to look at (in meters) - :param max_depth: the maximum depth to look at (in meters) - :return: blob - the contour with the greatest area, or [] if there were none of sufficient size + :returns output: A 2d array containing the box corner points of the rectangle. """ - width, height = core.vision.camera_handler.get_depth_res() + output = np.zeros((4, 2)) - maskDepth = np.zeros([height, width], np.uint8) + # Center / Width / Height -> BBox corners coordinates + x_min = (xywh[0] - 0.5 * xywh[2]) * im_shape[1] + x_max = (xywh[0] + 0.5 * xywh[2]) * im_shape[1] + y_min = (xywh[1] - 0.5 * xywh[3]) * im_shape[0] + y_max = (xywh[1] + 0.5 * xywh[3]) * im_shape[0] - # Depth segments between min and max with step - li = np.arange(min_depth, max_depth, core.DEPTH_STEP_SIZE) - max_li = [] + # A ------ B + # | Object | + # D ------ C - # Only pick the NUM_DEPTH_SEGMENTS busisest segments to run on, for performance reasons - for depth in li: - # Calculates the number of elements at each depth and scales their value by closeness - max_li.append( - len( - depth_matrix[(depth_matrix < (depth + core.DEPTH_STEP_SIZE) * 1000) & (depth_matrix > depth * 1000)] - * (1 / ((depth - min_depth) + 1)) - ) - ) + output[0][0] = x_min + output[0][1] = y_min - max_li = heapq.nlargest(core.NUM_DEPTH_SEGMENTS, zip(max_li, li)) - # Sort starting closest (distance wise) first - max_li.sort(reverse=False, key=lambda x: x[1]) + output[1][0] = x_max + output[1][1] = y_min - # For each step selected, run contour detection looking for blobs at that depth - for (score, depth) in max_li: - # 1 for all entries at depth, 0 for those not. Needed for findContours() - maskDepth = np.where( - (depth_matrix < (depth + core.DEPTH_STEP_SIZE) * 1000) & (depth_matrix > depth * 1000), 1, 0 - ) + output[2][0] = x_min + output[2][1] = y_max - # Find any contours - contours, hierarchy = cv2.findContours(maskDepth, 2, cv2.CHAIN_APPROX_NONE) - # Check if there are contours to be detected at this depth - if contours != []: - # choose the largest blob at this depth - blob = max(contours, key=cv2.contourArea) + output[3][0] = x_max + output[3][1] = y_max + return output - # return the blob if it meets the size requiremetns - if cv2.contourArea(blob) >= core.MIN_OBSTACLE_PIXEL_AREA: - return blob - return [] +def detections_to_custom_box(detections, img, reg_img): + """ + Takes in the list of detections from the NMS function in yolov5 (converts tensor objects to something kinda readable/workable), and + uses that info to find a 3-dimensional bounding box withing the zed cameras point cloud. + :params detections: List of detections, on (n,6) tensor per image [xyxy, conf, cls]. Use the non_max_suppression method from yolov5's utils.general. + :params img: The converted camera image from the img_preprocess function. + :params reg_img: The normal camera image. (numpy array from zed cam.) -def track_obstacle(depth_data, obstacle, annotate=False, reg_img=None, rect=False): + :returns output: Array containing info about object. """ - Tracks the provided contour, returning angle, distance and center and also optionally - annotates the provided image with the info and outlined obstacle - - :param depth_data - zed depth map - :param obstacle - the contour detected as an obstacle - :param annotate (bool) - whether to also annotate the provided image with the contour/centroid/etc. - :param reg_img - the color image from the ZED - :param rect - whether we should draw a rectangle bounding box or use the exact contour shape - :return: angle - the angle of the obstacle in relation to the left ZED camera, - distance - the distance of the center of the obstacle from the ZED, - center (x, y) - the coordinates (pixels) of the center of the obstacle + output = [] + for i, det in enumerate(detections): + if len(det): + det[:, :4] = scale_coords(img.shape[2:], det[:, :4], reg_img.shape).round() + gn = torch.tensor(reg_img.shape)[[1, 0, 1, 0]] # normalization gain whwh + + for *xyxy, conf, cls in reversed(det): + xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh + + # Creating ingestable objects for the ZED SDK + obj = [] + obj.append(xywh2abcd(xywh, reg_img.shape)) + obj.append(cls) + obj.append(conf) + obj.append(False) + output.append(obj) + return output + + +def torch_proc(img_queue, result_queue, weights, img_size, classes=None, conf_thres=0.2, iou_thres=0.45): """ + This method runs in a seperate python process and uses shared queues to pass data back and forth with its + parent process. This method opens the given weights file, loads the model, and then runs inference. + + :params img_queue: The ctx.Queue object used to give new images to the process. + :params result_queue: The ctx.Queue object used to return inference data to the parent. + :params weights: The file path containing the weights.pt file. + :params img_size: The image size to run inference with. + :params conf_thres: The minimum confidence threshold to consider something a good prediction. + :params iou_thres: The intersection over union threshold to consider something a good prediction. + + :returns: Nothing (Everything is put in the result queue) + """ + + +class YOLOObstacleDetector: + def __init__(self, weights, model_image_size, classes=None): + """ + Initializing the Obstacle Detector class variables and objects. + + :params weights: The path to the yolo.pt weights file exported from your data using the YOLOv5 repo. + :params model_image_size: The image size the model was trained on. + :params min_confidence: The minimum confidence to consider something a detected object. + :params classes: The YOLO classes to enable for detection. These classes are indexes for the user-defined class names in the yolo YAML file. The default of NONE will detect all classes. + """ + # Create objects and variables. + self.logger = logging.getLogger(__name__) + self.sim_active = False + self.objects = None + self.obj_param = None + self.names = [] + self.predictions = None + self.object_summary = "" + self.inference_time = 0 + self.classes = classes + + # Setup zed. + # Try to use zed, if fails assume we are using the sim. + try: + # Setup the zed positional tracking. + core.vision.camera_handler.enable_pose_tracking() + # Setup object detection on zed camera. + self.obj_param = core.vision.camera_handler.enable_camera_detection_module(enable_tracking=True) + except Exception: + self.logger.info("Unable to invoke zed specific methods. object_detector.py is assuming the SIM is active.") + self.sim_active = True + + # Create instance variables. + self.imgsz = (model_image_size, model_image_size) + self.half = False + + self.logger.info("Intializing Neural Network...") + # Create the device and model objects. (load model) + self.device = select_device() + # Catch error if model path is wrong. + try: + self.model = DetectMultiBackend( + weights, + device=self.device, + dnn=False, + data=os.path.dirname(__file__) + "/../core/vision/yolov5/data/coco128.yaml", + ) + cudnn.benchmark = True + + # Load model + stride, self.names, pt, jit, onnx, engine = ( + self.model.stride, + self.model.names, + self.model.pt, + self.model.jit, + self.model.onnx, + self.model.engine, + ) + self.imgsz = check_img_size(self.imgsz, s=stride) # check image size + + # Half + self.half &= ( + pt or jit or engine + ) and self.device.type != "cpu" # half precision only supported by PyTorch on CUDA + if pt or jit: + self.model.model.half() if self.half else self.model.model.float() + + # Warmup/Optimize + self.model.warmup(imgsz=(1, 3, *self.imgsz)) + except FileNotFoundError: + logging.error(msg="Unable to open YOLO model file. Make sure directory is correct and model exists.") + except UnpicklingError: + logging.error( + msg="Model path seems correct (a file was found with the given name), but yolov5 was unable to open. Make sure your model isn't corrupted or empty." + ) - # Find center of contour and mark it on image - M = cv2.moments(obstacle) - cX = int(M["m10"] / M["m00"]) - cY = int(M["m01"] / M["m00"]) - - # Distance is the corresponding value in the depth map of the center of the obstacle - distance = round(depth_data[cY][cX], 2) - - # Grab the camera parameters - img_res_x, img_res_y = core.vision.camera_handler.get_depth_res() - hfov = core.vision.camera_handler.get_hfov() - - # Calculate the angle of the object using camera params - angle_per_pixel = hfov / img_res_x - pixel_offset = cX - (img_res_x / 2) - angle = pixel_offset * angle_per_pixel - - # Draw the obstacle if annotate is true - if annotate: - if rect: - rect = cv2.boundingRect(obstacle) - x, y, w, h = rect - cv2.rectangle(reg_img, (x - 10, y - 10), (x + w + 10, y + h + 10), (255, 0, 0), 2) - else: - cv2.drawContours(reg_img, obstacle, -1, (0, 255, 0), 3) - cv2.putText( - reg_img, - f"Obstacle Detected at {angle, round(depth_data[cY][cX], 2)/1000}", - (cX - 100, cY - 20), - cv2.FONT_HERSHEY_SIMPLEX, - 0.5, - (255, 255, 255), - 2, - ) - cv2.circle(reg_img, (cX, cY), 7, (255, 255, 255), -1) - - return angle, distance, (cX, cY) \ No newline at end of file + def detect_obstacles(self, zed_left_img, conf_thres, iou_thres): + """ + Uses the yolov5 algorithm and a pretrained model to detect potential obstacles. The detected objects in the + 2d image are then cross referenced with the 3d point cloud to get their real world position. + + + :params zed_left_img: The image to perform inference on. + + :returns objects: A numpy array containing bounding_box_2d, label, probability, and is_grounded data. + :returns predictions: List of predictions, on (n,6) tensor per image [xyxy, conf, cls]. + """ + # Get new image from camera. + image_net = zed_left_img.copy() + + # Record start time. + s = time.time() + # Reformat and convert the image to something the model can read. + img, ratio, pad = img_preprocess(image_net, self.device, self.half, self.imgsz) + # Run inference on the image using the model. + pred = self.model(img) + # Get/filter the model detection results. + # Select classes that we want track. For corresponding object labels check the order of classes in your + # .yaml file for your dataset. + self.predictions = non_max_suppression(pred, conf_thres, iou_thres, self.classes) + # ZED CustomBox format (with inverse letterboxing tf applied) + self.objects = detections_to_custom_box(self.predictions, img, image_net) + self.inference_time = time.time() - s + + return self.objects, self.predictions + + def track_obstacle(self, reg_img, label_img=True): + """ + Tracks the closest object and display it on screen. All of the others objects are also labeled. + + :params reg_img: Zed left eye camera image. + :params label_img: Toggle for drawing inferences on screen. + + :returns angle: The angle of the obstacle in relation to the left ZED camera + :returns distance: The distance of the center of the obstacle from the ZED + :returns object_summary: A string containing the names and quantity of objects detected. + :returns inference_time: The total amount of time it took for the neural network to complete inferencing. + :returns object_locations: A list of all the detected objects distances and angles. + """ + # Create instance variables. + object_distance = -1 + object_angle = 0 + object_locations = [] + + # Check if we have any predictions. + if self.predictions is not None: + # Loop though each prediction + for i, det in enumerate(self.predictions): # per image + annotator = Annotator(reg_img, line_width=2, example=str(self.names)) + self.object_summary = "" + if len(det): + # Rescale boxes from img_size to im0 size + # det[:, :4] = scale_coords(image_net.shape[2:], det[:, :4], image_net.shape).round() + + # Print results + for c in det[:, -1].unique(): + n = (det[:, -1] == c).sum() # detections per class + self.object_summary += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " # add to string + + # Write results + for *xyxy, conf, cls in reversed(det): + if label_img: # Add bbox to image + c = int(cls) # integer class + label = f"{self.names[c]} {conf:.2f}" + annotator.box_label(xyxy, label, color=colors(c, True)) + + # Write results overlay onto image if toggle is set. + if label_img: + reg_img = annotator.result() + + # Check if we have any objects. + if self.objects is not None: + if not self.sim_active: + # Loop through the object array and get info about each object. + closest_point = None + for i, obj in enumerate(self.objects): + # Use the bounding box info to get the center point of the object in the point cloud + point = ( + int((obj[0][3][1] - obj[0][0][1]) / 2 + obj[0][0][1]), + int((obj[0][1][0] - obj[0][0][0]) / 2 + obj[0][0][0]), + ) + # Scale the object center in the screen to the point cloud res. + depth_res_x, depth_res_y = core.vision.camera_handler.get_depth_res() + img_res_x, img_res_y = core.vision.camera_handler.get_reg_res() + scaled_point = ( + int((point[0] * depth_res_y) / img_res_y), + int((point[1] * depth_res_x) / img_res_x), + ) + + # Grab depth data from the zed. + depth = core.vision.camera_handler.grab_depth_data() + # Get distance of the object from the camera. Add zed offset from robot center. + current_distance = math.fabs(depth[scaled_point[0]][scaled_point[1]]) + core.constants.ZED_Z_OFFSET + + # Calculate the angle of the object using camera params + angle_per_pixel = core.vision.camera_handler.get_hfov() / img_res_x + pixel_offset = point[1] - (img_res_x / 2) + angle = pixel_offset * angle_per_pixel + # If angle and distance make sense, then add the object info the the object location array. + if (angle > -90 and angle < 90) and not (math.isnan(current_distance)): + object_locations.append((angle, current_distance / 1000)) + + # Determine if current point is the closest point. ########## CHECK IF THIS ACTUALLY ADDS ALL OBJECTS TO OBJECT_LOCATIONS LIST. + if (object_distance == -1 and not current_distance < 0) or object_distance > current_distance: + # Store the closest distance, angle, and point in image. + object_distance = current_distance + object_angle = angle + closest_point = point + + # Draw circle of current tracked object. + if closest_point is not None: + reg_img = cv2.circle( + reg_img, + (closest_point[1], closest_point[0]), + radius=5, + color=(0, 0, 255), + thickness=-1, + ) + else: + # Loop through the object array and get info about each object. + closest_point = None + for i, obj in enumerate(self.objects): + # Use the bounding box info to get the center point of the object in the point cloud + point = ( + int((obj[0][3][1] - obj[0][0][1]) / 2 + obj[0][0][1]), + int((obj[0][1][0] - obj[0][0][0]) / 2 + obj[0][0][0]), + ) + # Scale the object center in the screen to the point cloud res. + depth_res_x, depth_res_y = core.vision.camera_handler.get_depth_res() + img_res_x, img_res_y = core.vision.camera_handler.get_reg_res() + scaled_point = ( + int((point[0] * depth_res_y) / img_res_y), + int((point[1] * depth_res_x) / img_res_x), + ) + + # Grab depth data from the zed. + depth = core.vision.camera_handler.grab_depth_data() + # Get distance of the object from the camera. Add zed offset from robot center. + current_distance = depth[scaled_point[0]][scaled_point[1]][0] + core.constants.ZED_Z_OFFSET + + # Calculate the angle of the object using camera params + angle_per_pixel = core.vision.camera_handler.get_hfov() / img_res_x + pixel_offset = point[1] - (img_res_x / 2) + angle = pixel_offset * angle_per_pixel + # If angle and distance make sense, then add the object info the the object location array. + if (angle > -90 and angle < 90) and not (math.isnan(current_distance)): + object_locations.append((angle, current_distance / 1000)) + + # Determine if current point is the closest point. ########## CHECK IF THIS ACTUALLY ADDS ALL OBJECTS TO OBJECT_LOCATIONS LIST. + if (object_distance == -1 and not current_distance < 0) or object_distance > current_distance: + # Store the closest distance, angle, and point in image. + object_distance = current_distance + object_angle = angle + closest_point = point + + # Draw circle of current tracked object. + if closest_point is not None: + reg_img = cv2.circle( + reg_img, + (closest_point[1], closest_point[0]), + radius=5, + color=(0, 0, 255), + thickness=-1, + ) + + # Return angle, distance + return object_angle, object_distance, self.object_summary, self.inference_time, object_locations diff --git a/algorithms/small_movements.py b/algorithms/small_movements.py new file mode 100644 index 00000000..fef6ca9b --- /dev/null +++ b/algorithms/small_movements.py @@ -0,0 +1,91 @@ +import interfaces +import logging +import core +import algorithms +import time + + +def backup(start_latitude, start_longitude, target_distance, speed=-200): + """ + Backs rover up for a specified distance at specified speed + + :param start_lat: The start reference to calculate distance from. + :param start_long: The start reference to calculate distance from. + :param target_distance: Distance to travel backwards (meters) + :param speed: The speed to drive right and left motors (between -1000 and -1) + + :returns done: Whether or not the rover has backed up the target distance. + """ + # Setup logger for function. + logger = logging.getLogger(__name__) + + # Force distance to be positive and speed to be negative + target_distance = abs(target_distance) + speed = -abs(speed) + + # Get total distance traveled so far. + current_latitude, current_longitude = interfaces.nav_board.location(force_absolute=True) + bearing, distance_traveled = algorithms.geomath.haversine( + start_latitude, start_longitude, current_latitude, current_longitude + ) + # Convert to km to m. + distance_traveled *= 1000 + + # Check distance traveled until target distance is reached + if distance_traveled < target_distance: + # Send drive command. + interfaces.drive_board.send_drive(speed, speed) + # Print log. + logger.info(f"Backing Up: {distance_traveled} meters / {target_distance} meters") + # Return false since we are still backing up. + return False + else: + # Stop rover drive. + interfaces.drive_board.stop() + # Print log. + logger.info(f"Backing Up: COMPLETED") + # Return true since we have reversed specified distance. + return True + + +def time_drive(distance): + """ + Drives the rover in a straight line for time 'goal_time'. + 'goal_time' is calculated by dividing goal distance by the constant METERS_PER_SECOND + + Parameters: + ----------- + distance (float) - distance to travel. Negative for reverse. + """ + + goal_time = abs(distance) / core.METERS_PER_SECOND + t1 = time.time() + t2 = time.time() + + if distance > 0: + while t2 - t1 < goal_time: + t2 = time.time() + interfaces.drive_board.send_drive(core.MAX_DRIVE_POWER, core.MAX_DRIVE_POWER) + time.sleep(core.EVENT_LOOP_DELAY) + + elif distance < 0: + while t2 - t1 < goal_time: + t2 = time.time() + interfaces.drive_board.send_drive(-core.MAX_DRIVE_POWER, -core.MAX_DRIVE_POWER) + time.sleep(core.EVENT_LOOP_DELAY) + + """ + I need to figure out how to do this asynchronously. + This isn't necessarily an issue yet, + but I imagine this function will be used in situations where vision is needed. + And that doesn't work right now. + """ + + interfaces.drive_board.stop() + + +def dance_party(): + """ + Spin in place multiple times. + """ + pass diff --git a/algorithms/stanley_controller.py b/algorithms/stanley_controller.py new file mode 100644 index 00000000..00c745a8 --- /dev/null +++ b/algorithms/stanley_controller.py @@ -0,0 +1,226 @@ +# +# Mars Rover Design Team +# stanley_controller.py +# +# Created on March 13, 2023 +# Updated on March 13, 2023 +# +""" +Path tracking simulation with Stanley steering control and PID speed control. + +Ref: + - [Stanley: The robot that won the DARPA grand challenge](http://isl.ecst.csuchico.edu/DOCS/darpa2005/DARPA%202005%20Stanley.pdf) + - [Autonomous Automobile Path Tracking](https://www.ri.cmu.edu/pub_files/2009/2/Automatic_Steering_Methods_for_Autonomous_Automobile_Path_Tracking.pdf) + +""" +import numpy as np +import matplotlib.pyplot as plt +import time +import math + +k = 0.6 # control gain +Kp = 0.02 # speed proportional gain +L = 0.5 # [m] Wheel base of vehicle +max_steer = np.radians(60.0) # [rad] max steering angle +yaw_tolerance = np.deg2rad(5) # Error tolerance off of the path. + + +class State(object): + """ + Class representing the state of a vehicle. Uses a basic bicycle model to estimate the + vehicle position given an acceleration and steering angle. + + :param x: (float) x-coordinate + :param y: (float) y-coordinate + :param yaw: (float) yaw angle + :param v: (float) speed + """ + + def __init__(self, x=0.0, y=0.0, yaw=0.0, v=0.0): + """Instantiate the object.""" + # Initialize class variables. + self.x = x + self.y = y + self.yaw = yaw + self.v = v + self.time_since_last_step = time.time() + + def update_bicycle(self, acceleration, delta): + """ + Update the state of the vehicle with a simple bicycle model. This is used to guess the position + of the robot given acceleration and heading change and will likely not be accurate at all to real life. + Only use this for testing and simulating outputs. + + Stanley Control uses bicycle model. + + :param acceleration: (float) Acceleration + :param delta: (float) Steering + """ + # Constrain the steering angle to the given limits. + delta = np.clip(delta, -max_steer, max_steer) + + # Calculate dt. + dt = time.time() - self.time_since_last_step + + # Calculate estimated position using bicycle model. + self.x += self.v * np.cos(self.yaw) * dt + self.y += self.v * np.sin(self.yaw) * dt + self.yaw += self.v / L * np.tan(delta) * dt + self.yaw = normalize_angle(self.yaw) + self.v += acceleration * dt + + # Update time step. + self.time_since_last_step = time.time() + + def update(self, x, y, yaw): + """ + Manually update the position and heading of the robot. Velocity is automatically + determined using the time and distance covered since last update. + + :param x: (float) The x position of the robot. + :param y: (float) The y position of the robot. + :param yaw: (float) The heading of the robot. + """ + # Calcluate the velocity of the robot. + self.v = math.sqrt(math.pow((x - self.x), 2) + math.pow((y - self.y), 2)) / ( + time.time() - self.time_since_last_step + ) + + # Store the new x, y, and yaw positions. + self.x = x + self.y = y + self.yaw = yaw + + # Update time step. + self.time_since_last_step = time.time() + + +def pid_control(target, current): + """ + Simple proportional control for the speed. + + :param target: (float) + :param current: (float) + :return: (float) + """ + # Multiply error py proportional constant. + return Kp * (target - current) + + +def stanley_control(state, cx, cy, cyaw, last_target_idx): + """ + Stanley steering control. + + :param state: (State object) + :param cx: ([float]) + :param cy: ([float]) + :param cyaw: ([float]) Expects yaw to oriented like a unit circle. + :param last_target_idx: (int) + :return: (float, int) + """ + # Find the closest index in the path to where the robot. + current_target_idx, error_front_axle = calc_target_index(state, cx, cy) + + # Don't go over end of path. + if last_target_idx >= current_target_idx: + current_target_idx = last_target_idx + + # Calculate yaw offset. + error = cyaw[current_target_idx] - state.yaw + # Theta_e corrects the heading error. + theta_e = normalize_angle(error) + # Theta_d corrects the cross track error. + theta_d = math.atan2(k * error_front_axle, state.v) + # Steering control. + delta = theta_e + theta_d + + # Yaw tolerance. + if abs(error) < yaw_tolerance: + # Set turn adjustment to zero. + delta = 0 + + return delta, current_target_idx + + +def normalize_angle(angle): + """ + Normalize an angle to [-pi, pi]. + + :param angle: (float) Must be in radians. + :return: (float) Angle in radian in [-pi, pi] + """ + # Clamp angle + while angle > np.pi: + angle -= 2.0 * np.pi + + while angle < -np.pi: + angle += 2.0 * np.pi + + return angle + + +def calc_target_index(state, cx, cy): + """ + Compute index in the trajectory list of the target. + + :param state: (State object) + :param cx: [float] + :param cy: [float] + :return: (int, float) + """ + # Calc front axle position. + fx = state.x + L * np.cos(state.yaw) + fy = state.y + L * np.sin(state.yaw) + + # Search nearest point index. + dx = [fx - icx for icx in cx] + dy = [fy - icy for icy in cy] + d = np.hypot(dx, dy) + target_idx = np.argmin(d) + + # Project RMS error onto front axle vector. + front_axle_vec = [-np.cos(state.yaw + np.pi / 2), -np.sin(state.yaw + np.pi / 2)] + error_front_axle = np.dot([dx[target_idx], dy[target_idx]], front_axle_vec) + + return target_idx, error_front_axle + + +def calculate_yaws_from_path(cx, cy, start_angle=0.0, radians=True): + """ + Computes the appropiate absolute yaw from a given set of Xs and Ys. These should + produce a sensible path and the two lists should be the same length. + All yaw angle are calulated in radians by default. + + :param cx: The list of x points within the path. + :param cy: The list of y points within the path. + :param start_angle: The initial angle for the first point. + :param radians: Whether of not to use radians for the angle. (On by default) + :return: ([yaws]) An array containing the yaw angles for each point. + """ + # Create instance variables. + yaws = [] + + # Check if both lists are equal size. + if len(cx) == len(cy) and len(cx) > 1: + # Loop through points. The zip function returns iterables for a sublist starting at 0:-1 and a sublist starting at 1:end for each list x and y. + for i, x, y, x_next, y_next in zip(range(len(cx) - 1), cx[:-1], cy[:-1], cx[1:], cy[1:]): + # Basic trig to find angle between two points. + angle = math.atan2((y_next - y), (x_next - x)) + + # Check if we are converting to degrees. + if not radians: + angle = np.rad2deg(angle) + + # Append angle to yaws list. + yaws.append(angle) + + # Copy second to last angle to last point until list lengths match. + while len(yaws) < len(cx): + yaws.append(yaws[-1]) + + # If only one point exists in path. + elif len(cx) == 1: + # Append zero heading angle. + yaws.append(0) + + return yaws diff --git a/autonomy.py b/autonomy.py index b7de0e95..bb01b6ae 100644 --- a/autonomy.py +++ b/autonomy.py @@ -9,6 +9,8 @@ import core import logging import asyncio +import interfaces.nav_board +import utm logger = logging.getLogger(__name__) @@ -43,7 +45,9 @@ def main() -> None: # Create our two detection tasks loop.create_task(core.vision.ar_tag_detector.async_ar_tag_detector()) - loop.create_task(core.vision.obstacle_avoidance.async_obstacle_detector()) + # Only start obstacle detection if flag was enabled. + if core.vision.AVOIDANCE_FLAG: + loop.create_task(core.vision.obstacle_avoidance.async_obstacle_detector()) # Run core autonomy state machine loop loop.run_until_complete(autonomy_state_loop()) @@ -74,6 +78,14 @@ async def autonomy_state_loop(): False, ) + # Print debug + # relpos = interfaces.nav_board.location() + # abspos = interfaces.nav_board.location(force_absolute=True) + # print("RELPOS:", utm.from_latlon(relpos[0], relpos[1])[:2]) + # print("ABSPOS:", utm.from_latlon(abspos[0], abspos[1])[:2]) + # print("RELHEAD:", interfaces.nav_board.heading()) + # print("ABSHEAD:", interfaces.nav_board._heading) + # Core state machine runs every X ms, to prevent unnecessarily fast computation. # Sensor data is processed separately, as that is the bulk of processing time await asyncio.sleep(core.EVENT_LOOP_DELAY) diff --git a/core/__init__.py b/core/__init__.py index a06f0852..95227882 100644 --- a/core/__init__.py +++ b/core/__init__.py @@ -9,6 +9,7 @@ import sys from core import states +from core import constants from core import vision from core.constants import * from core.states.state_machine import StateMachine @@ -34,6 +35,8 @@ def setup(type="REGULAR"): """ # load the manifest this.manifest = get_manifest() + # Store mode. + this.MODE = type # IPs and ports depend on type if type == "REGULAR": diff --git a/core/constants.py b/core/constants.py index 50725a47..55f301b5 100644 --- a/core/constants.py +++ b/core/constants.py @@ -12,7 +12,13 @@ import json # Autonomy General Configuration -EVENT_LOOP_DELAY = 0.1 # seconds +EVENT_LOOP_DELAY = 0.0 # seconds +IDLE_TIME_GPS_REALIGN = 5 # Second to sit in idle before realigning gps with relative. +IDLE_GPS_ACCUR_THRESH = 0.8 # The minimum meter accuracy needed to update rover position. + +# Stuck Parameters. +STUCK_MIN_DISTANCE = 0.35 +STUCK_UPDATE_TIME = 15 # Navigation Parameters WIDTH = 640.0 # pixels @@ -20,17 +26,72 @@ TARGET_DISTANCE = 0.4 # meters RADIUS = 0.063 # meters SCALING_FACTOR = 10.0 # pixel-meters -WAYPOINT_DISTANCE_THRESHOLD = 1.5 # maximum threshold in meters between rover and waypoint +WAYPOINT_DISTANCE_THRESHOLD = 0.5 # maximum threshold in meters between rover and waypoint BEARING_FLIP_THRESHOLD = 30.0 # 180 +/- this many degrees counts as a flip in bearing -MAX_DRIVE_POWER = 250 # -1000 to 1000, normally 250 dropped lower for early testing to be safe -MIN_DRIVE_POWER = 50 # -1000 to 1000, normally 50 +MAX_DRIVE_POWER = 425 # -1000 to 1000, normally 250 dropped lower for early testing to be safe +MIN_DRIVE_POWER = -250 # -1000 to 1000, normally 50 +GATE_POINT_DISTANCES = 3.0 +NAVIGATION_PATH_EXPIRATION_SECONDS = 5 # The time in seconds before a new path is force generated. +NAVIGATION_PATH_ROUTE_LENGTH = 30 # The length in meters that ASTAR will generate at one time. +METERS_PER_SECOND = 0.762 # at speeds (450, 450) **CHANGE FOR UTAH TERRAIN +AR_SKEW_THRESHOLD = 30 # min angle allowed between tags for approaching gate to skip first leg +NAVIGATION_START_BACKUP_DISTANCE = 2 # Time to backup if tag is in front of rover when entering nav state. +NAVIGATION_BACKUP_SPEED = -250 # the speed to backup with. +NAVIGATION_BACKUP_TAG_DISTANCE_THRESH = 3 # Min distance tag can be from rover to trigger backup. +NAVIGATION_ALWAYS_REVERSE_OUT_OF_IDLE = True # If true rover will always enter reverse state from idle. Then go to nav. + +# Approaching Gate Parameters. +GATE_WAYPOINT_THRESH = 0.3 # The minimum distance from end waypoint before we consider ourselves there. +GATE_NEAR_OBSTACLE_THRESH = 0.8 # The closest the rover can get to a post. +GATE_MAX_ERROR_FROM_PATH = 5 # The max distance the rover diverge off path before regen. +GATE_UPDATE_PATH_MAX_MARKER_DISTANCE = ( + 2 # The max distance we must be from the gate markers before we think tag detections will be accurate. +) +GATE_APPROACH_DRIVE_POWER = 200 # Speed to approach and drive through gate. +GATE_DRIVE_THROUGH_TIME = 1 # The amount of time to continue driving after going through gate. +GATE_OBSTACLE_QUEUE_LENGTH = 120 # The max obstacles to store at once. +GATE_MAX_DETECTION_ATTEMPTS = 250 + +# Approaching Marker Parameters. +MARKER_MAX_APPROACH_SPEED = 200 # The speed to approach the marker at. +MAX_DETECTION_ATTEMPTS = 20 # This should be about 1 second + # Search Pattern Parameters -SEARCH_DISTANCE = 20 # meters -DELTA_THETA = math.pi / 4 +SEARCH_DISTANCE = 4 # meters +SEARCH_DRIVE_POWER = 400 +SEARCH_PATTERN_MAX_ERROR_FROM_PATH = 5 # The max distance the rover diverge off path before regen. +SEARCH_OBSTACLE_QUEUE_LENGTH = 10 # The max number of objects to store at once. +SEARCH_DELTA_THETA = math.pi / 4 # Pattern/shape/vertices of spiral. +SEARCH_LEFT = False # Spiral turns left or right. + +# Obstacle Detection Parameters. +DETECTION_MODEL_CONF = 0.4 +DETECTION_MODEL_IOU = 0.65 +# Obstacle Avoidance Parameters. +AVOIDANCE_ENABLE_DISTANCE_THRESHOLD = 3.0 # Minimum distance rover must be from the waypoint before avoidance kicks in. +AVOIDANCE_OBJECT_DISTANCE_MIN = 2.0 # Closest rover can get to an obstacle. +AVOIDANCE_OBJECT_DISTANCE_MAX = 10.0 # Minimum distance rover must be from an obstacle before avoidance kicks in. +AVOIDANCE_OBJECT_ANGLE = 40 # The FOV of detection for obstacles. +AVOIDANCE_PATH_NODE_INCREMENT = 0.1 # The distance between each node. Path resolution in meters. +AVOIDANCE_PATH_EXPIRATION_SECONDS = 5 # The time in seconds before a new path is force generated. +AVOIDANCE_PATH_ROUTE_LENGTH = 40 # The length in meters that ASTAR will generate at one time. +AVOIDANCE_OBSTACLE_QUEUE_LENGTH = 10 # The number of obstacles to store at a time. +AVOIDANCE_MAX_SPEED_MPS = 0.6 # The max speed in meters per second to drive the rover. MUST MAKE SURE THIS IS ATTAINABLE WITH DRIVE SPEED POWER. + +# Stuck State Parameters. +STUCK_STILL_TIME = 3.0 # The number of seconds to sit still in stuck state. # Vision Parameters -MAX_DETECTION_ATTEMPTS = 15 # This should be about 1 second +ARUCO_FRAMES_DETECTED = 2 # ArUco Detection Occurrences +ARUCO_MAX_FRAMES_DETECTED = 15 # Max frame counter for each tag. +ARUCO_MARKER_BORDER_BITS = 1 +ARUCO_ERROR_CORRECTION_RATE = 1 +ARUCO_ENABLE_DISTANCE = 25 # The minimum distance from the goal waypoint before aruco detection os considered valid. +ARUCO_MARKER_STOP_DISTANCE = 2.0 +DISPLAY_TEST_MODE = False # This will enable opening of OpenCV windows for vision detection live viewing. +ZED_X_OFFSET = 0.060325 +ZED_Z_OFFSET = 0.000 # LiDAR maximum distance before we decide we would yeet off a cliff. LIDAR_MAXIMUM = 250 # 2.5m to test early, need to determine actual value. @@ -40,7 +101,7 @@ MIN_OBSTACLE_PIXEL_AREA = 400 # minimum contour area in pixels of detected obstacle DEPTH_STEP_SIZE = 0.5 # Depth in meters that each segment of obstacle detection will run on NUM_DEPTH_SEGMENTS = 3 # Number of segments of depth map to actually run contour detection on -ZED_X_OFFSET = 0.060325 + Coordinate = collections.namedtuple("Coordinate", ["lat", "lon"]) @@ -52,7 +113,7 @@ manifest = {} # Outgoing communication ports -UDP_OUTGOING_PORT = None +UDP_OUTGOING_PORT = 0000 TCP_OUTGOING_PORT = 11111 diff --git a/core/rovecomm_module b/core/rovecomm_module index 7c7b11f1..ce8d3986 160000 --- a/core/rovecomm_module +++ b/core/rovecomm_module @@ -1 +1 @@ -Subproject commit 7c7b11f1b246602ef41273f763fc430af34386ad +Subproject commit ce8d398685d86563e1a5e19b4bf0ba16af9ab1aa diff --git a/core/states/__init__.py b/core/states/__init__.py index dd4d20d2..5b828985 100644 --- a/core/states/__init__.py +++ b/core/states/__init__.py @@ -11,6 +11,8 @@ from core.states.idle import Idle from core.states.search_pattern import SearchPattern from core.states.navigating import Navigating +from core.states.reversing import Reversing +from core.states.stuck import Stuck from core.states.approaching_marker import ApproachingMarker from core.states.approaching_gate import ApproachingGate from core.states.avoidance import Avoidance @@ -35,6 +37,9 @@ class AutonomyEvents(Enum): END_OBSTACLE_AVOIDANCE = 12 NO_WAYPOINT = 13 NEW_WAYPOINT = 14 + REVERSE = 15 + REVERSE_COMPLETE = 16 + STUCK = 17 StateMapping = { @@ -44,4 +49,6 @@ class AutonomyEvents(Enum): "ApproachingMarker": 3, "ApproachingGate": 4, "Avoidance": 5, + "Reversing": 6, + "Stuck": 7, } diff --git a/core/states/approaching_gate.py b/core/states/approaching_gate.py index 34fd6a63..885d1e33 100644 --- a/core/states/approaching_gate.py +++ b/core/states/approaching_gate.py @@ -7,11 +7,20 @@ # import core +import copy +from core import constants import interfaces +from algorithms import stanley_controller, heading_hold +from algorithms.obstacle_avoider import ASTAR import algorithms from core.states import RoverState +import numpy as np +from numpy import NaN import time import math +import asyncio +import utm +from matplotlib import pyplot as plt class ApproachingGate(RoverState): @@ -24,16 +33,44 @@ def start(self): """ Schedule AR Tag detection """ - + # Create state specific variable. + self.astar = ASTAR(core.constants.GATE_OBSTACLE_QUEUE_LENGTH) + self.rover_position_state = None + self.path_xs = [] + self.path_ys = [] + self.path_yaws = [] + self.rover_xs = [] + self.rover_ys = [] + self.rover_yaws = [] + self.rover_vs = [] + self.last_idx = 0 + self.target_idx = 0 + self.path_start_time = 0 self.num_detection_attempts = 0 self.gate_detection_attempts = 0 + self.gate_coords = [(0, 0), (0, 0)] + self.tags = [] + self.trench_mid_points = [] + self.through_gate_timer = 0 + self.gate1_obstacles = [] + self.gate2_obstacles = [] def exit(self): """ Cancel all state specific coroutines """ - - pass + # Cancel all state specific coroutines and reset state variables. + self.astar.clear_obstacles() + self.path_xs.clear() + self.path_ys.clear() + self.path_yaws.clear() + self.rover_xs.clear() + self.rover_ys.clear() + self.rover_yaws.clear() + self.rover_vs.clear() + self.target_idx = 0 + # Set position state back to none. + self.rover_position_state = None def on_event(self, event) -> RoverState: """ @@ -42,10 +79,14 @@ def on_event(self, event) -> RoverState: :param event: :return: RoverState """ - state: RoverState = None if event == core.AutonomyEvents.REACHED_MARKER: + # Tell multimedia board to flash our LED matrix green to indicate reached marker + interfaces.multimedia_board.send_lighting_state(core.OperationState.REACHED_MARKER) + # Clear markers. + core.vision.ar_tag_detector.clear_tags() + # Move to idle state. state = core.states.Idle() elif event == core.AutonomyEvents.START: @@ -74,144 +115,364 @@ async def run(self) -> RoverState: :return: RoverState """ - - # Call AR Tag tracking code to find position and size of AR Tag - if core.vision.ar_tag_detector.is_gate(): - # Use get_tags to create an array of the 2 gate posts - # (named tuples containing the distance and relative angle from the camera) - tags = core.vision.ar_tag_detector.get_tags() - gps_data = core.waypoint_handler.get_waypoint() - orig_goal, orig_start, leg_type = gps_data.data() - - # If we've seen at least 5 frames of 2 tags, assume it's a gate - if len(tags) == 2 and self.gate_detection_attempts >= 5 and leg_type == "GATE": - self.logger.info("Gate detected, beginning navigation") - # compute the angle across from the gate - # depending on where the rover is facing, this is computed differently - if tags[0].angle < 0 and tags[1].angle < 0: # both tags on the right - larger = min(tags[0].angle, tags[1].angle) - smaller = max(tags[0].angle, tags[1].angle) - combinedAngle = abs(larger) - abs(smaller) - elif tags[0].angle >= 0 and tags[1].angle >= 0: # both tags on the left - larger = max(tags[0].angle, tags[1].angle) - smaller = min(tags[0].angle, tags[1].angle) - combinedAngle = larger - smaller - else: # one tag on left, one on right - combinedAngle = abs(tags[0].angle) + abs(tags[1].angle) - # Calculate bearing and distance for the midpoint between the two tags - # use law of cosines to get the distance between the tags, midpoint will be halfway between them - gateWidth = math.sqrt( - (tags[0].distance ** 2) - + (tags[1].distance ** 2) - - 2 * tags[0].distance * tags[1].distance * math.cos(math.radians(combinedAngle)) + # Get current position and next desired waypoint position. + current = interfaces.nav_board.location() + # Get UTM location so we have UTM zone for GPS and UTM conversion. + utm_current = utm.from_latlon(current[0], current[1]) + # Get current heading. Must subtract 90 because stanley controller expect a unit circle oriented heading. + heading = np.deg2rad(interfaces.nav_board.heading() - 90) + # Use get_tags to create an array of the 2 gate posts + # (named tuples containing the distance and relative angle from the camera) + self.tags = core.vision.ar_tag_detector.get_valid_tags() + # Gate waypoint data. + goal, _, leg_type = core.waypoint_handler.get_waypoint().data() + + # If we've seen at least 5 frames of 2 tags, assume it's a gate + if ( + len(self.tags) == 2 + and self.gate_detection_attempts >= constants.ARUCO_FRAMES_DETECTED + and leg_type == "GATE" + and algorithms.geomath.haversine( + current[0], + current[1], + (self.gate_coords[0][0] + self.gate_coords[1][0]) / 2, + (self.gate_coords[0][1] + self.gate_coords[1][1]) / 2, + )[1] + * 1000 + > core.constants.GATE_UPDATE_PATH_MAX_MARKER_DISTANCE + ): + """ + WAYPOINT LOGIC. + """ + # Clear previous obstacles. + self.astar.clear_obstacles() + # Store AR tags as obstacles. + obstacle_list = [(self.tags[0].angle, self.tags[0].distance), (self.tags[1].angle, self.tags[1].distance)] + # Update ASTAR object. + self.astar.update_obstacles( + obstacle_list, + min_object_distance=0.3, + max_object_distance=99999, + min_object_angle=-180, + max_object_angle=180, + ) + # The update_obstacles method automatically converts the angles and distances to gps, so pull out gps coords. + self.gate_coords = self.astar.get_obstacle_coords() + # Convert gate gps coords to utm xs and ys. + gate_xs = [utm.from_latlon(t[0], t[1])[0] for t in copy.deepcopy(self.gate_coords)] + gate_ys = [utm.from_latlon(t[0], t[1])[1] for t in copy.deepcopy(self.gate_coords)] + + ###################################################################################################################### + # Calculate the intersection line and perp line to the obstacles to make a 'trench' for the rover to drive through. + # Check https://www.desmos.com/calculator/xcbgsmlk6x for an interactive graph. + ###################################################################################################################### + # Catch bad gate coords. + if len(gate_xs) <= 2 and len(gate_ys) <= 2: + # Create list to store UTM coords. + self.gate1_obstacles.clear() + self.gate2_obstacles.clear() + # Store the UTM easting/northing for each gate. + x1, y1 = gate_xs[0], gate_ys[0] + x2, y2 = gate_xs[1], gate_ys[1] + # Find slope of line that pases through both points. + try: + m = (y2 - y1) / (x2 - x1) + except ZeroDivisionError: + # If points are vertically aligned just set, slope to NaN. + m = NaN + + # Find radius' from -3 to 3 in increments of 0.5 + for r in [x * 0.125 for x in range(-24, 24)]: + # If slope if zero, just add to y values. + if m == 0: + # Append simple obstacles. + self.gate1_obstacles.append((x1, y1 + r)) + self.gate2_obstacles.append((x2, y2 + r)) + # Check if slope is undefined. + elif m == NaN: + # Append simple obstacles. + self.gate1_obstacles.append((x1 + r, y1)) + self.gate2_obstacles.append((x2 + r, y2)) + else: + # This is the equation that will spit out the x coordinate of the first gates trench line given the radius of a circle + # with origin at the gatepoint. + # Find appropriate x point for first gate marker. + gate1_rad_x = ( + m + * ( + -m * ((-2 * x1) - ((2 * x1) / math.pow(m, 2))) + - ((2 * r) * math.sqrt(1 + math.pow(m, 2))) + ) + ) / (2 * (math.pow(m, 2) + 1)) + # Find appropriate x point for second gate marker. + gate2_rad_x = ( + m + * ( + -m * ((-2 * x2) - ((2 * x2) / math.pow(m, 2))) + + ((2 * r) * math.sqrt(1 + math.pow(m, 2))) + ) + ) / (2 * (math.pow(m, 2) + 1)) + + # Find the cooresponding Y point for the calculated X point using the perpendicular line of slope m at each gate point. + # Find Y point for first gate marker. + gate1_rad_y = (-1 / m) * (gate1_rad_x - x1) + y1 + # Find Y point for second gate marker. + gate2_rad_y = (-1 / m) * (gate2_rad_x - x2) + y2 + + # Add points to gate obstacle list. + self.gate1_obstacles.append((gate1_rad_x, gate1_rad_y)) + self.gate2_obstacles.append((gate2_rad_x, gate2_rad_y)) + + # Add gate1 and gate2 obstacles to astar list. + self.astar.update_obstacle_coords(self.gate1_obstacles[10:-10], input_gps=False) + self.astar.update_obstacle_coords(self.gate2_obstacles[10:-10], input_gps=False) + + # Find midpoint between matching points in the trench. + mid_points = [] + for point1, point2 in zip(self.gate1_obstacles, self.gate2_obstacles[::-1]): + # Calulate midpoint. + midpoint = ((point1[0] + point2[0]) / 2, (point1[1] + point2[1]) / 2) + # Append point to list. + mid_points.append(midpoint) + # Store in member variables so we can plot it later. + self.trench_mid_points = mid_points + + # Find which end of the trenchline is closer to the rover. + end1_distance = algorithms.geomath.utm_distance( + utm_current[0], utm_current[1], self.trench_mid_points[0][0], self.trench_mid_points[0][1] + )[1] + end2_distance = algorithms.geomath.utm_distance( + utm_current[0], utm_current[1], self.trench_mid_points[-1][0], self.trench_mid_points[-1][1] + )[1] + # Set whatever end is closer to us as the current goal. + if end1_distance < end2_distance: + # Set waypoint goal. + core.waypoint_handler.set_goal( + utm.to_latlon( + self.trench_mid_points[0][0], self.trench_mid_points[0][1], utm_current[2], utm_current[3] + ) ) - self.logger.info(f"Gate width {gateWidth}") - - # we want to use the smaller side for our midpoint triangle - D1 = min(tags[0].distance, tags[1].distance) - - # use law of sines to get the angle across from D1 - sinVal = (math.sin(math.radians(combinedAngle / 2)) * D1) / (gateWidth * 0.5) - - # arcsin is limited between -1 and 1, not sure why reflecting these values - # across the y axis works, but it does. No proof it works in all cases - if sinVal > 1: - sinDiff = sinVal - 1 - sinVal = 1 - sinDiff - elif sinVal < -1: - sinDiff = sinVal + 1 - sinVal = -1 - sinDiff - angleAcrossD1 = math.asin(sinVal) - - # deduce the last angle from 180 (pi) - angleAcrossDm = math.pi - angleAcrossD1 - math.radians(combinedAngle / 2) - - # law of sines to get the last side of our triangle - distToMidpoint = abs( - ((gateWidth / 2) * math.sin(angleAcrossDm)) / math.sin(math.radians(combinedAngle / 2)) + else: + # Set waypoint goal. + core.waypoint_handler.set_goal( + utm.to_latlon( + self.trench_mid_points[-1][0], self.trench_mid_points[-1][1], utm_current[2], utm_current[3] + ) ) - self.logger.info(f"Calculated Distance to gate: {distToMidpoint}") - - # Last step to get angle to the midpoint, depending on where tags are relative to rover - if tags[0].angle < 0 and tags[1].angle < 0: - angleToMidpoint = (interfaces.nav_board.heading() - (abs(larger) - (combinedAngle / 2))) % 360 - elif tags[0].angle >= 0 and tags[1].angle >= 0: - angleToMidpoint = (interfaces.nav_board.heading() + (abs(larger) - (combinedAngle / 2))) % 360 - else: - angleToMidpoint = (interfaces.nav_board.heading() + ((tags[0].angle + tags[1].angle) / 2)) % 360 - self.logger.info(f"Calculated Angle to gate: {angleToMidpoint}") + # Reverse midpoint list. + self.trench_mid_points = self.trench_mid_points[::-1] + + # Generate path from rovers current position to new goal. + path = self.astar.plan_astar_avoidance_route( + max_route_size=50, + near_object_threshold=constants.GATE_NEAR_OBSTACLE_THRESH, + start_gps=current, + waypoint_thresh=0.1, + ) + + # If path was generated successfully, then put it in our future path. Cut out old future. + if path is not None: + # Set path start timer. + self.path_start_time = time.time() + + # Clear path xs, ys, and yaws. + self.path_xs.clear() + self.path_ys.clear() + self.path_yaws.clear() + + # Append new ASTAR path onto current. + for point in path: + # Add new path starting from current location. + self.path_xs.append(point[0]) + self.path_ys.append(point[1]) + + # Add trenchline to end of generated path. + for point in self.trench_mid_points: + # Add new path starting from current location. + self.path_xs.append(point[0]) + self.path_ys.append(point[1]) + + # Manually calulate yaws since ASTAR doesn't given yaws. + self.path_yaws = stanley_controller.calculate_yaws_from_path( + self.path_xs, self.path_ys, interfaces.nav_board.heading() + ) - start = core.Coordinate(interfaces.nav_board.location()[0], interfaces.nav_board.location()[1]) + # Store last index of path. + self.last_idx = len(self.path_xs) - 1 - # Get a GPS coordinate using our distance and bearing - target = algorithms.obstacle_avoider.coords_obstacle( - distToMidpoint, start[0], start[1], angleToMidpoint + # Update waypoint goal. + core.waypoint_handler.set_goal( + utm.to_latlon(self.path_xs[-1], self.path_ys[-1], utm_current[2], utm_current[3]) ) - # Also calculate second point (to run through the gate) - targetPastGateHeading = ((angleAcrossD1 - (math.pi / 2)) + interfaces.nav_board.heading()) % 360 - targetBeforeGate = algorithms.obstacle_avoider.coords_obstacle( - -3, target[0], target[1], targetPastGateHeading + """ + PATH GENERATION AND FOLLOWING. + """ + # Check if path is empty. + if len(self.path_xs) > 1: + # Normalize heading to -pi and pi + heading = stanley_controller.normalize_angle(-heading) + + # If this is the first run interation for the avoidance state, then initialize some variables with the current rover information. + if self.rover_position_state is None: + # Create new state and give intial values of the rovers current position, heading, and velocity. + self.rover_position_state = stanley_controller.State(utm_current[0], utm_current[1], heading) + + # Store the initial rover state in x, y, yaw, and velocity arrays. + self.rover_xs.append(self.rover_position_state.x) + self.rover_ys.append(self.rover_position_state.y) + self.rover_yaws.append(self.rover_position_state.yaw) + self.rover_vs.append(self.rover_position_state.v) + self.target_idx, _ = stanley_controller.calc_target_index( + self.rover_position_state, self.path_xs, self.path_ys ) - targetPastGate = algorithms.obstacle_avoider.coords_obstacle( - 3, target[0], target[1], targetPastGateHeading + else: + # Get velocity adjustment with P controller. + acceleration = stanley_controller.pid_control( + constants.AVOIDANCE_MAX_SPEED_MPS, self.rover_position_state.v ) - - points = [targetBeforeGate, target, targetPastGate] - - # Approach the gate using GPS drive - for point in points: - while ( - algorithms.gps_navigate.get_approach_status( - core.Coordinate(point[0], point[1]), interfaces.nav_board.location(), start, 0.5 - ) - == core.ApproachState.APPROACHING - ): - self.logger.info(f"Driving towards: Lat: {point[0]}, Lon: {point[1]}") - left, right = algorithms.gps_navigate.calculate_move( - core.Coordinate(point[0], point[1]), - interfaces.nav_board.location(), - start, - 250, - ) - - self.logger.debug(f"Diving at speeds: Left: {left} Right: {right}") - - interfaces.drive_board.send_drive(left, right) - time.sleep(0.01) - interfaces.drive_board.stop() - - self.logger.info("Reached Gate") - - # Transmit that we have reached the gate - core.rovecomm_node.write( - core.RoveCommPacket( - core.manifest["Autonomy"]["Telemetry"]["ReachedMarker"]["dataId"], - "B", - (1,), - ), - False, + # Call stanley controller and get steering control adjustment and the next best target along the path. + delta_adjustment, self.target_idx = stanley_controller.stanley_control( + self.rover_position_state, self.path_xs, self.path_ys, self.path_yaws, self.target_idx + ) + # Calculate adjusted heading. Add 90 to convert back to gps heading. + goal_heading = -np.rad2deg(heading + delta_adjustment) + 90 + goal_speed = constants.MAX_DRIVE_POWER * (1 + acceleration) + + # Update the current rover state. + self.rover_position_state.update(utm_current[0], utm_current[1], heading) + + # Store the initial rover state in x, y, yaw, and velocity arrays. + self.rover_xs.append(self.rover_position_state.x) + self.rover_ys.append(self.rover_position_state.y) + self.rover_yaws.append(self.rover_position_state.yaw) + self.rover_vs.append(self.rover_position_state.v) + + # Write path 1 second before it expires. + if int(time.time()) % 2 == 0: + plt.cla() + # Get and plot Obstacle Coordinates + obstacle_coords = self.astar.get_obstacle_coords() + xo = [utm.from_latlon(t[0], t[1])[0] for t in obstacle_coords] + yo = [utm.from_latlon(t[0], t[1])[1] for t in obstacle_coords] + plt.plot(xo, yo, "s", label="obstacles") + # Get and plot Gate Coordinates + xo = [utm.from_latlon(t[0], t[1])[0] for t in self.gate_coords] + yo = [utm.from_latlon(t[0], t[1])[1] for t in self.gate_coords] + plt.plot(xo, yo, "1", label="gate") + # Get and plot Trench line Coordinates + xo = [t[0] for t in self.trench_mid_points] + yo = [t[1] for t in self.trench_mid_points] + plt.plot(xo, yo, "p", label="trenchline") + # Plot path, current location, and target_index. + plt.gca().set_aspect("equal", adjustable="box") + plt.plot(self.path_xs, self.path_ys, ".r", label="course") + plt.plot(self.rover_xs, self.rover_ys, "-b", label="trajectory") + plt.plot(self.path_xs[self.target_idx], self.path_ys[self.target_idx], "xg", label="target") + plt.axis("equal") + plt.grid(True) + plt.title("Rover Velocity (M/S):" + str(self.rover_position_state.v)) + plt.savefig("logs/!rover_path.png") + + # Send drive board commands to drive at a certain speed at a certain angle. + left, right = heading_hold.get_motor_power_from_heading( + core.constants.GATE_APPROACH_DRIVE_POWER, goal_heading ) + # Set drive powers. + self.logger.info(f"ApproachingGate: Driving at ({left}, {right})") + interfaces.drive_board.send_drive(left, right) + + # Check if the rover is too far from the target position in path. Manually lead rover back onto path. + if ( + math.sqrt( + math.pow(self.path_xs[self.target_idx] - utm_current[0], 2) + + math.pow(self.path_ys[self.target_idx] - utm_current[1], 2) + ) + > constants.GATE_MAX_ERROR_FROM_PATH + ): + # Generate path from rovers current position. + path = self.astar.plan_astar_avoidance_route( + max_route_size=50, + near_object_threshold=constants.GATE_NEAR_OBSTACLE_THRESH, + start_gps=current, + waypoint_thresh=0.2, + ) + + # If path was generated successfully, then put it in our future path. Cut out old future. + if path is not None: + # Set path start timer. + self.path_start_time = time.time() + + # Clear path xs, ys, and yaws. + self.path_xs.clear() + self.path_ys.clear() + self.path_yaws.clear() + + # Append new ASTAR path onto current. + for point in path: + # Add new path starting from current location. + self.path_xs.append(point[0]) + self.path_ys.append(point[1]) + + # Add trenchline to end of generated path. + for point in self.trench_mid_points: + # Add new path starting from current location. + self.path_xs.append(point[0]) + self.path_ys.append(point[1]) + + # Manually calulate yaws since ASTAR doesn't given yaws. + self.path_yaws = stanley_controller.calculate_yaws_from_path( + self.path_xs, self.path_ys, interfaces.nav_board.heading() + ) - # Tell multimedia board to flash our LED matrix green to indicate reached marker - interfaces.multimedia_board.send_lighting_state(core.OperationState.REACHED_MARKER) + # Store last index of path. + self.last_idx = len(self.path_xs) - 1 + # Update waypoint goal. + core.waypoint_handler.set_goal( + utm.to_latlon(self.path_xs[-1], self.path_ys[-1], utm_current[2], utm_current[3]) + ) + else: + # Stop the drive board. + interfaces.drive_board.stop() + # Print debug that path has completed. + self.logger.info("ApproachingGate ASTAR path is empty.") + + # Check if we've reached the end of the path. + if self.target_idx == self.last_idx and not self.target_idx == 0 and not self.last_idx == 0: + # Continue following path for user defined amount of time. + if self.through_gate_timer == 0: + # Get current time. + self.through_gate_timer = time.time() + + # Don't transfer states until timer expires. + if (time.time() - self.through_gate_timer) > constants.GATE_DRIVE_THROUGH_TIME: + # Return to idle. return self.on_event(core.AutonomyEvents.REACHED_MARKER) - # If we grabbed more than one, see if it's a gate - elif len(tags) > 1: - self.gate_detection_attempts += 1 - self.logger.info(f"2 Markers in frame, count:{self.gate_detection_attempts}") + # If we grabbed more than one, see if it's a gate + elif len(self.tags) > 1: + self.gate_detection_attempts += 1 + self.logger.info(f"2 Markers in frame, count:{self.gate_detection_attempts}") - else: + # Call AR Tag tracking code to find position and size of AR Tag + if not core.vision.ar_tag_detector.is_gate(): self.num_detection_attempts += 1 - self.gate_detection_attempts = 0 # If we have attempted to track an AR Tag unsuccesfully # MAX_DETECTION_ATTEMPTS times, we will return to search pattern - if self.num_detection_attempts >= core.MAX_DETECTION_ATTEMPTS: + if self.num_detection_attempts >= core.constants.GATE_MAX_DETECTION_ATTEMPTS: + # Reset gate counter. + self.gate_detection_attempts = 0 + # Print logs. self.logger.info("Lost sign of gate, returning to Search Pattern") + # Get current position and next desired waypoint position. + current = interfaces.nav_board.location() + # Set goal and current waypoint as current location. + core.waypoint_handler.set_goal(current) + core.waypoint_handler.set_start(current) + return self.on_event(core.AutonomyEvents.MARKER_UNSEEN) return self diff --git a/core/states/approaching_gate_wide.py b/core/states/approaching_gate_wide.py new file mode 100644 index 00000000..ecd1734f --- /dev/null +++ b/core/states/approaching_gate_wide.py @@ -0,0 +1,352 @@ +import asyncio + +# from turtle import distance +# from algorithms import AR_tag +import algorithms.geomath as geomath +import algorithms.small_movements as small_movements +import algorithms.obstacle_avoider as obs_avoid + +# from core.vision.ar_tag_detector import is_gate +import core +import interfaces +import algorithms +from core.states import RoverState +import time +import logging +import math + +# from core.vision.ar_tag_detector import clear_tags +import numpy as np +import core.constants as constants +import geopy.distance +import geopy + +# from core.states import new_search_pattern + +# NO GPS VERSION +# drives in a straight line through the gate (this will be bad at steep angles) + +# Create logger object. +logger = logging.getLogger(__name__) + + +class ApproachingGate(RoverState): + """ + Within approaching gate, 3 waypoints are calculated in front of, between, and throught the viewed gate, allowing the rover to traverse through the gate fully. + """ + + def start(self): + # Schedule AR Tag detection + self.num_detection_attempts = 0 + self.gate_detection_attempts = 0 + self.last_angle = 1000 + self.not_seen = 0 + self.is_first = True + self.is_turning = False + self.previous_turning_angle = 1000 + self.total_detections = 0 + + def exit(self): + # Cancel all state specific coroutines + pass + + def on_event(self, event) -> RoverState: + """ + Defines all transitions between states based on events + """ + state: RoverState = None + + if event == core.AutonomyEvents.REACHED_MARKER: + state = core.states.Idle() + + elif event == core.AutonomyEvents.START: + state = self + + elif event == core.AutonomyEvents.MARKER_UNSEEN: + state = core.states.SearchPattern() + + elif event == core.AutonomyEvents.ABORT: + state = core.states.Idle() + + else: + self.logger.error(f"Unexpected event {event} for state {self}") + state = core.states.Idle() + + # Call exit() if we are not staying the same state + if state != self: + self.exit() + + # Return the state appropriate for the event + return state + + async def run(self) -> RoverState: + + if self.is_first and not core.vision.ar_tag_detector.is_gate(): + return self + + # Use get_valid_tags to create an array of the 2 gate posts + # (named tuples containing the distance and relative angle from the camera) + tags = core.vision.ar_tag_detector.get_valid_tags() + gps_data = core.waypoint_handler.get_waypoint() + orig_goal, orig_start, leg_type = gps_data.data() + + self.logger.info("Gate detected, beginning navigation") + + start = core.Coordinate(interfaces.nav_board.location()[0], interfaces.nav_board.location()[1]) + + # If we've seen at least 5 frames of 2 tags, assume it's a gate + self.logger.info("Gate detected, beginning navigation") + + if not self.is_turning: + if (len(tags) >= 2): + distance = (tags[0].distance + tags[1].distance) / 2 + angle = ((tags[0].angle) + (tags[1].angle)) / 2 + if abs(tags[0].angle - tags[1].angle) > constants.AR_SKEW_THRESHOLD: + self.is_first = False + + if self.is_first: + # Get + post_1_coord = [tags[0].distance, tags[0].angle] + post_2_coord = [tags[1].distance, tags[1].angle] + + print("Current GPS coords", start[0], start[1]) + print("POST 1 COORD:", post_1_coord) + print("POST 2 COORD:", post_2_coord) + if post_1_coord[0] == 40.001 or post_2_coord[0] == 40.001: + print("NULL TAG DISTANCE") + interfaces.drive_board.send_drive(core.MAX_DRIVE_POWER * 0.8, core.MAX_DRIVE_POWER * 0.8) + return self + + try: + targetBeforeGate, midpoint, targetPastGate = find_gate_path( + post_1_coord, post_2_coord, (start[0], start[1]), interfaces.nav_board.heading() + ) + except: + return self + + print("TB4GATE:", targetBeforeGate.latitude, targetBeforeGate.longitude) + print("MIDPOINT:", midpoint.latitude, midpoint) + print("PAST GATE:", targetPastGate.latitude, targetPastGate.longitude) + + point = targetBeforeGate.latitude, targetBeforeGate.longitude + # print("TAGS LL: ", tags[0].lat, tags[0].long, " - ", tags[1].lat, tags[1].long) + print(point) + + while ( + algorithms.gps_navigate.get_approach_status( + core.Coordinate(point[0], point[1]), interfaces.nav_board.location(), start, 0.5 + ) + == core.ApproachState.APPROACHING + ): + print("FIRST GPS POINT") + + self.logger.info(f"Driving towards: Lat: {point[0]}, Lon: {point[1]}") + left, right = algorithms.gps_navigate.calculate_move( + core.Coordinate(point[0], point[1]), + interfaces.nav_board.location(), + start, + 250, + ) + + self.logger.debug(f"Diving at speeds: Left: {left} Right: {right}") + + interfaces.drive_board.send_drive(left, right) + await asyncio.sleep(core.EVENT_LOOP_DELAY) + interfaces.drive_board.stop() + self.is_first = False + self.is_turning = True + self.last_angle = 1000 + self.not_seen = 0 + core.vision.ar_tag_detector.clear_tags() + return self + + if self.is_turning: + print("TURNING") + + interfaces.drive_board.send_drive(150, -150) + + if core.vision.ar_tag_detector.is_gate(): + # tags = core.vision.ar_tag_detector.get_valid_tags() + # current_truning_angle = abs(tags[0].angle + tags[1].angle / 2) + + self.is_turning = False + interfaces.drive_board.stop() + + # if current_truning_angle > self.previous_turning_angle: + # print("TURNING ANGLES: ", current_truning_angle, self.previous_turning_angle) + # self.is_turning = False + # self.previous_turning_angle = 1000 + # interfaces.drive_board.stop() + # else: + # self.previous_turning_angle = current_truning_angle + + return self + + # Calculate angle and distance of center point between ar tags. + if (len(tags) >= 2): + distance = (tags[0].distance + tags[1].distance) / 2 + angle = ((tags[0].angle) + (tags[1].angle)) / 2 + self.not_seen = 0 + + current_detections = (tags[0].times_detected) + (tags[1].times_detected) + + if current_detections == 0 or current_detections < self.total_detections: + angle = 0 + self.total_detections = current_detections + + + else: + # self.not_seen += 1 + # if self.not_seen > 2: + # t1 = time.time() + # t2 = time.time() + # # drive past gate for 10 seconds + # while t2 - t1 < 3: + # t2 = time.time() + # interfaces.drive_board.send_drive(150, 150) + # interfaces.drive_board.stop() + # if not (0 < distance < 5) or np.isnan(distance): + distance = 3 + small_movements.time_drive(distance) + self.logger.info("Reached Marker") + + # Transmit that we have reached the marker + core.rovecomm_node.write( + core.RoveCommPacket( + core.manifest["Autonomy"]["Telemetry"]["ReachedMarker"]["dataId"], + "B", + (1,), + ), + False, + ) + + # Tell multimedia board to flash our LED matrix green to indicate reached marker + interfaces.multimedia_board.send_lighting_state(core.OperationState.REACHED_MARKER) + + # Clear ar tag list!?!?!?!? + core.vision.ar_tag_detector.clear_tags() + + return self.on_event(core.AutonomyEvents.REACHED_MARKER) + + self.last_angle = angle + + left, right = algorithms.follow_marker.drive_to_marker(300, angle) + + if self.not_seen == 0: + if angle < -0.5: + right *= 1.2 + # left *= 0.8 + elif angle > 0.5: + left *= 1.2 + # right *= 0.8 + + right = int(right) + left = int(left) + + self.logger.info("Marker in frame") + self.num_detection_attempts = 0 + + # if distance < 1.25: + # interfaces.drive_board.stop() + + # self.logger.info("Reached Marker") + + # # Transmit that we have reached the marker + # core.rovecomm_node.write( + # core.RoveCommPacket( + # core.manifest["Autonomy"]["Telemetry"]["ReachedMarker"]["dataId"], + # "B", + # (1,), + # ), + # False, + # ) + + # # Tell multimedia board to flash our LED matrix green to indicate reached marker + # interfaces.multimedia_board.send_lighting_state(core.OperationState.REACHED_MARKER) + # return self.on_event(core.AutonomyEvents.REACHED_MARKER) + # else: + self.logger.info(f"Driving to target with speeds: ({left}, {right})") + interfaces.drive_board.send_drive(left, right) + + return self + + +def find_gate_path(polar_p1, polar_p2, current_gps_pos, current_heading): + + # This function finds two points that the rover can use to pass through a gate. + # It does this by finding a line perpinduclar to the gate that passes through the midpoint. + # It then finds the points on that line that are exactly "distance" away from the midpoint. + # + # Parameters: + # polar_p1, polar_p2: + # Polar coordinates of the points of the gate posts relative to the rover's heading and position. + # (distance, angle_from_heading) -- (meters) -- angle must be passed as RADIANS. + # + # Returns: + # two core.Coordinate objects with the GPS coordinates of each point that the rover needs to + # drive through the gate. + # + # The first object is the point closest to the rover. + + # Distance each point will be from the gate (meters) + distance = 3 + + # Convert Polar coordinate input to rectangular coordinates + p1 = (polar_p1[0] * math.cos(math.radians(polar_p1[1])), polar_p1[0] * math.sin(math.radians(polar_p1[1]))) + p2 = (polar_p2[0] * math.cos(math.radians(polar_p2[1])), polar_p2[0] * math.sin(math.radians(polar_p2[1]))) + + # Compute the midpoint of point_1 and point_2 + midpoint = ((p2[0] + p1[0]) / 2, (p2[1] + p1[1]) / 2) + + # Compute the slope and the y_intercept of the line that passes through the gate + slope = -(p2[0] - p1[0]) / (p2[1] - p1[1]) + y_intercept = midpoint[1] + ((p2[0] - p1[0]) * (p2[0] + p1[0])) / (2 * (p2[1] - p1[1])) + + # x points for where exactly distance from the midpoint -- NEED TO EXPLAIN THIS A LITTLE BETTER + pos_c = distance / (math.sqrt(1 + ((p2[0] - p1[0]) ** 2 / (p2[1] - p1[1]) ** 2))) + midpoint[0] + neg_c = -distance / (math.sqrt(1 + ((p2[0] - p1[0]) ** 2 / (p2[1] - p1[1]) ** 2))) + midpoint[0] + + # xy points that the rover will use to drive through the gate + ret_point_1 = (pos_c, pos_c * slope + y_intercept) + ret_point_2 = (neg_c, neg_c * slope + y_intercept) + + # Distance to those points + p1_distance = math.sqrt(ret_point_1[0] ** 2 + ret_point_1[1] ** 2) + p2_distance = math.sqrt(ret_point_2[0] ** 2 + ret_point_2[1] ** 2) + midpoint_distance = math.sqrt(midpoint[0] ** 2 + midpoint[1] ** 2) + + # Compute angle to those points + if ret_point_1[0] < 0: + p1_angle = math.pi - math.asin(ret_point_1[1] / p1_distance) + else: + p1_angle = math.asin(ret_point_1[1] / p1_distance) + + if ret_point_2[0] < 0: + p2_angle = math.pi - math.asin(ret_point_2[1] / p2_distance) + else: + p2_angle = math.asin(ret_point_2[1] / p2_distance) + + # Compute angle of midpoint + if midpoint[0] < 0: + mid_angle = math.pi - math.asin(midpoint[1] / midpoint_distance) + else: + mid_angle = math.asin(midpoint[1] / midpoint_distance) + + gps_pos = geopy.Point(current_gps_pos[0], current_gps_pos[1]) + dest_point_1 = geopy.distance.distance(meters=p1_distance).destination( + gps_pos, bearing=(current_heading + math.degrees(p1_angle)) % 360 + ) + dest_point_2 = geopy.distance.distance(meters=p2_distance).destination( + gps_pos, bearing=(current_heading + math.degrees(p2_angle)) % 360 + ) + dest_point_mid = geopy.distance.distance(meters=midpoint_distance).destination( + gps_pos, bearing=(current_heading + math.degrees(mid_angle)) % 360 + ) + + print("----------") + print(dest_point_1, dest_point_mid, dest_point_2) + + if p2_distance > p1_distance: + return dest_point_1, dest_point_mid, dest_point_2 + else: + return dest_point_2, dest_point_mid, dest_point_1 diff --git a/core/states/approaching_marker.py b/core/states/approaching_marker.py index ddaf1d6a..293813f6 100644 --- a/core/states/approaching_marker.py +++ b/core/states/approaching_marker.py @@ -6,10 +6,14 @@ # Updated on Aug 21, 2022 # +import utm +import time +import math import core import interfaces import algorithms from core.states import RoverState +import matplotlib.pyplot as plt class ApproachingMarker(RoverState): @@ -21,15 +25,13 @@ def start(self): """ Schedule AR Tag detection """ - + # Create state specific variables. self.num_detection_attempts = 0 - self.gate_detection_attempts = 0 def exit(self): """ Cancel all state specific coroutines """ - pass def on_event(self, event) -> RoverState: @@ -71,24 +73,30 @@ async def run(self) -> RoverState: :return: RoverState """ + # Get current position and next desired waypoint position. + current = interfaces.nav_board.location(force_absolute=True) + gps_data = core.waypoint_handler.get_waypoint() + # Pull info out of waypoint. + goal, start, leg_type = gps_data.data() # Call AR Tag tracking code to find position and size of AR Tag if core.vision.ar_tag_detector.is_marker(): # Grab the AR tags - tags = core.vision.ar_tag_detector.get_tags() + tags = core.vision.ar_tag_detector.get_valid_tags() gps_data = core.waypoint_handler.get_waypoint() orig_goal, orig_start, leg_type = gps_data.data() # Currently only orienting based on one AR Tag distance = tags[0].distance angle = tags[0].angle + self.logger.info(f"MARKER DISTANCE: {distance} ANGLE: {angle}") - left, right = algorithms.follow_marker.drive_to_marker(100, angle) + left, right = algorithms.follow_marker.drive_to_marker(core.constants.MARKER_MAX_APPROACH_SPEED, angle) self.logger.info("Marker in frame") self.num_detection_attempts = 0 - if distance < 1.25: + if distance < core.constants.ARUCO_MARKER_STOP_DISTANCE: interfaces.drive_board.stop() self.logger.info("Reached Marker") @@ -110,12 +118,20 @@ async def run(self) -> RoverState: self.logger.info(f"Driving to target with speeds: ({left}, {right})") interfaces.drive_board.send_drive(left, right) else: + # Increment counter. self.num_detection_attempts += 1 - self.gate_detection_attempts = 0 + # Stop drive. + interfaces.drive_board.stop() # If we have attempted to track an AR Tag unsuccesfully # MAX_DETECTION_ATTEMPTS times, we will return to search pattern if self.num_detection_attempts >= core.MAX_DETECTION_ATTEMPTS: + # Get current position and next desired waypoint position. + current = interfaces.nav_board.location() + # Set goal waypoint as current. + core.waypoint_handler.set_goal(current) + core.waypoint_handler.set_start(current) + # Print log. self.logger.info("Lost sign of marker, returning to Search Pattern") return self.on_event(core.AutonomyEvents.MARKER_UNSEEN) diff --git a/core/states/avoidance.py b/core/states/avoidance.py index 22b27d77..7b37ad4e 100644 --- a/core/states/avoidance.py +++ b/core/states/avoidance.py @@ -7,10 +7,13 @@ # import time -from algorithms import obstacle_avoider +from algorithms import obstacle_avoider, stanley_controller, heading_hold, gps_navigate, geomath +import matplotlib.pyplot as plt import core +import core.constants import interfaces -import algorithms +import numpy as np +import utm from core.states import RoverState @@ -20,28 +23,41 @@ class Avoidance(RoverState): """ def start(self): - """ - Schedule avoidance - """ - - pass + # Create state specific variable. + self.astar = obstacle_avoider.ASTAR(core.constants.AVOIDANCE_OBSTACLE_QUEUE_LENGTH) + self.rover_position_state = None + self.path_xs = [] + self.path_ys = [] + self.path_yaws = [] + self.rover_xs = [] + self.rover_ys = [] + self.rover_yaws = [] + self.rover_vs = [] + self.last_idx = 0 + self.target_idx = 0 + self.path_start_time = 0 + self.stuck_check_timer = 0 + self.stuck_check_last_position = [0, 0] def exit(self): - """ - Cancel all state specific coroutines - """ - - pass + # Cancel all state specific coroutines and reset state variables. + self.astar.clear_obstacles() + self.path_xs.clear() + self.path_ys.clear() + self.path_yaws.clear() + self.rover_xs.clear() + self.rover_ys.clear() + self.rover_yaws.clear() + self.rover_vs.clear() + self.target_idx = 0 + # Set position state back to none. + self.rover_position_state = None def on_event(self, event) -> RoverState: """ Defines all transitions between states based on events - - :param event: - :return: RoverState """ - - state: RoverState = None + state: RoverState = core.states.Idle() if event == core.AutonomyEvents.START: state = self @@ -52,6 +68,9 @@ def on_event(self, event) -> RoverState: elif event == core.AutonomyEvents.END_OBSTACLE_AVOIDANCE: state = core.states.state_machine.get_prev_state() + elif event == core.AutonomyEvents.STUCK: + state = core.states.Stuck() + else: self.logger.error(f"Unexpected event {event} for state {self}") state = core.states.Idle() @@ -66,54 +85,189 @@ def on_event(self, event) -> RoverState: async def run(self) -> RoverState: """ Defines regular rover operation when under this state + """ + # Create instance variables. + path_expiration = core.constants.AVOIDANCE_PATH_EXPIRATION_SECONDS + # Get current gps location. + gps_current = interfaces.nav_board.location() + current = utm.from_latlon(gps_current[0], gps_current[1]) + # Get goal waypoint. + gps_data = core.waypoint_handler.get_waypoint() + goal, start, leg_type = gps_data.data() + _, distance = geomath.haversine(current[0], current[1], goal[0], goal[1]) - :return: RoverState """ + STATE TRANSITION AND WAYPOINT LOGIC. + """ + # We should be navigating, so check if we have been in the same position for awhile. + # Only check every predefined amount of seconds. + if (time.time() - self.stuck_check_timer) > core.constants.STUCK_UPDATE_TIME: + # Calculate distance from goal for checking for markers and gates. + _, distance = geomath.haversine( + self.stuck_check_last_position[0], self.stuck_check_last_position[1], current[0], current[1] + ) + # Convert km to m. + distance *= 1000 - # Finding the obstacle - is_obstacle = core.vision.obstacle_avoidance.is_obstacle() - self.logger.info(f"{is_obstacle}") + # Store new position. + self.stuck_check_last_position[0], self.stuck_check_last_position[1] = current[0], current[1] + + # Check if we are stuck. + if distance < core.constants.STUCK_MIN_DISTANCE: + # Move to stuck state. + return self.on_event(core.AutonomyEvents.STUCK) + + # Update timer. + self.stuck_check_timer = time.time() + + # Move to approaching marker if 1 ar tag is spotted during marker leg type + if ( + core.waypoint_handler.gps_data.leg_type == "MARKER" + and core.vision.ar_tag_detector.is_marker() + and distance < core.constants.ARUCO_ENABLE_DISTANCE + ): + return core.states.ApproachingMarker() + + # Move to approaching gate if 2 ar tags are spotted during gate leg type. + if ( + (core.waypoint_handler.gps_data.leg_type == "GATE" or core.waypoint_handler.gps_data.leg_type == "MARKER") + and core.vision.ar_tag_detector.is_gate() + and distance < core.constants.ARUCO_ENABLE_DISTANCE + ): + core.waypoint_handler.gps_data.leg_type = "GATE" + return core.states.ApproachingGate() + + """ + PATH GENERATION AND FOLLOWING. + """ - if is_obstacle: - angle = core.vision.obstacle_avoidance.get_angle() - distance = core.vision.obstacle_avoidance.get_distance() + # Get boolean toggle for if one or more obstacles have been detected. + is_obstacle = core.vision.obstacle_avoidance.is_obstacle() + # Update time since last path generation. + time_since_last_path = time.time() - self.path_start_time - # Calculate the absolute heading of the obstacle, in relation to the rover - angle = (interfaces.nav_board.heading() + angle) % 360 + # Get the object location list. + object_locations = core.vision.obstacle_avoidance.get_obstacle_locations() + # Update astar algorithm with the new obstacles if we currently detect any object. + if object_locations is not None: + self.astar.update_obstacles( + object_locations, + min_object_distance=core.constants.AVOIDANCE_OBJECT_DISTANCE_MIN, + max_object_distance=core.constants.AVOIDANCE_OBJECT_DISTANCE_MAX, + min_object_angle=-core.constants.AVOIDANCE_OBJECT_ANGLE, + max_object_angle=core.constants.AVOIDANCE_OBJECT_ANGLE, + ) - # find the gps coordinate of the obstacle - obstacle_lat, obstacle_lon = obstacle_avoider.coords_obstacle( - distance, interfaces.nav_board.location()[0], interfaces.nav_board.location()[1], angle + # If one or more obstacles have been detected and time since last path generation has exceeded limit, then attempt to plan a new avoidance route. + if is_obstacle and time_since_last_path > path_expiration or self.target_idx == self.last_idx: + # Generate path. + path = self.astar.plan_astar_avoidance_route( + max_route_size=core.constants.AVOIDANCE_PATH_ROUTE_LENGTH, + near_object_threshold=core.constants.AVOIDANCE_OBJECT_DISTANCE_MIN, + waypoint_thresh=0.3, ) - points = obstacle_avoider.plan_avoidance_route(angle, distance, obstacle_lat, obstacle_lon, type="Circle") - - previous_loc = interfaces.nav_board.location() - - # Drives to each of the points in the list of points around the object in sequence - for point in points: - new_lat, new_lon = point - self.logger.info(f"Driving towards : Lat: {new_lat}, Lon: {new_lon} now") - while ( - algorithms.gps_navigate.get_approach_status( - core.Coordinate(new_lat, new_lon), - interfaces.nav_board.location(), - previous_loc, - 0.5, - ) - == core.ApproachState.APPROACHING - ): - left, right = algorithms.gps_navigate.calculate_move( - core.Coordinate(new_lat, new_lon), - interfaces.nav_board.location(), - previous_loc, - 250, - ) - - self.logger.debug(f"Navigating: Driving at ({left}, {right})") - interfaces.drive_board.send_drive(left, right) - time.sleep(0.01) - interfaces.drive_board.stop() - previous_loc = core.Coordinate(new_lat, new_lon) - - return self.on_event(core.AutonomyEvents.END_OBSTACLE_AVOIDANCE) + # If path was generated successfully, then put it in our future path. Cut out old future. + if path is not None: + # Set path start timer. + self.path_start_time = time.time() + + # Cut off path data after our current location. + self.path_xs = self.path_xs[: self.target_idx] + self.path_ys = self.path_ys[: self.target_idx] + self.path_yaws = self.path_yaws[: self.target_idx] + + # Append new path onto current. + for point in path: + # Add new path starting from current location. + self.path_xs.append(point[0]) + self.path_ys.append(point[1]) + + # Manually calulate yaws since ASTAR doesn't given yaws. + self.path_yaws = stanley_controller.calculate_yaws_from_path( + self.path_xs, self.path_ys, interfaces.nav_board.heading() + ) + + # Store last index of path. + self.last_idx = len(self.path_xs) - 1 + + # Check if path is empty. + if len(self.path_xs) > 0: + # Get current heading. Must subtract 90 because stanley controller expect a unit circle oriented heading. + heading = np.deg2rad(interfaces.nav_board.heading() - 90) + # Normalize heading to -pi and pi + heading = stanley_controller.normalize_angle(-heading) + + # If this is the first run interation for the avoidance state, then initialize some variables with the current rover information. + if self.rover_position_state is None: + # Create new state and give intial values of the rovers current position, heading, and velocity. + self.rover_position_state = stanley_controller.State(current[0], current[1], heading) + + # Store the initial rover state in x, y, yaw, and velocity arrays. + self.rover_xs.append(self.rover_position_state.x) + self.rover_ys.append(self.rover_position_state.y) + self.rover_yaws.append(self.rover_position_state.yaw) + self.rover_vs.append(self.rover_position_state.v) + self.target_idx, _ = stanley_controller.calc_target_index( + self.rover_position_state, self.path_xs, self.path_ys + ) + else: + # Get velocity adjustment with P controller. + acceleration = stanley_controller.pid_control( + core.constants.AVOIDANCE_MAX_SPEED_MPS, self.rover_position_state.v + ) + # Call stanley controller and get steering control adjustment and the next best target along the path. + delta_adjustment, self.target_idx = stanley_controller.stanley_control( + self.rover_position_state, self.path_xs, self.path_ys, self.path_yaws, self.target_idx + ) + # Calculate adjusted heading. Add 90 to convert back to gps heading. + goal_heading = -np.rad2deg(heading + delta_adjustment) + 90 + goal_speed = core.constants.MAX_DRIVE_POWER * (1 + acceleration) + + # Update the current rover state. + self.rover_position_state.update(current[0], current[1], heading) + + # Store the initial rover state in x, y, yaw, and velocity arrays. + self.rover_xs.append(self.rover_position_state.x) + self.rover_ys.append(self.rover_position_state.y) + self.rover_yaws.append(self.rover_position_state.yaw) + self.rover_vs.append(self.rover_position_state.v) + + # Write path 1 second before it expires. + if int(time.time()) % 2 == 0: + plt.cla() + # Get and plot Obstacle Coordinates + obstacle_coords = self.astar.get_obstacle_coords() + xo = [utm.from_latlon(t[0], t[1])[0] for t in obstacle_coords] + yo = [utm.from_latlon(t[0], t[1])[1] for t in obstacle_coords] + # Plot path, current location, and target_index. + plt.plot(xo, yo, "s", label="obstacles") + plt.gca().set_aspect("equal", adjustable="box") + plt.plot(self.path_xs, self.path_ys, ".r", label="course") + plt.plot(self.rover_xs, self.rover_ys, "-b", label="trajectory") + plt.plot(self.path_xs[self.target_idx], self.path_ys[self.target_idx], "xg", label="target") + plt.axis("equal") + plt.grid(True) + plt.title("Rover Velocity (M/S):" + str(self.rover_position_state.v)) + plt.savefig("logs/!rover_path.png") + + # Send drive board commands to drive at a certain speed at a certain angle. + left, right = heading_hold.get_motor_power_from_heading(goal_speed, goal_heading) + # Set drive powers. + self.logger.info(f"Avoidance: Driving at ({left}, {right})") + interfaces.drive_board.send_drive(left, right) + else: + # Stop the drive board. + interfaces.drive_board.stop() + # Print debug that path has completed. + self.logger.info("Avoidance path is empty. Going back to Navigating.") + + # Condition for moving out of avoidance state. + if ( + gps_navigate.get_approach_status(goal, gps_current, start, core.WAYPOINT_DISTANCE_THRESHOLD) + != core.ApproachState.APPROACHING + ): + # Move states. + return self.on_event(core.AutonomyEvents.END_OBSTACLE_AVOIDANCE) + + return self diff --git a/core/states/idle.py b/core/states/idle.py index 106504bb..ccda98ac 100644 --- a/core/states/idle.py +++ b/core/states/idle.py @@ -7,7 +7,13 @@ # import core +import time +import logging +import interfaces +import algorithms from core.states import RoverState +import utm +import matplotlib.pyplot as plt class Idle(RoverState): @@ -17,6 +23,25 @@ class Idle(RoverState): from base station that configure the next leg’s settings and confirm them. """ + def start(self): + """ + Schedule Idle + """ + self.logger = logging.getLogger(__name__) + self.idle_time = time.time() + self.realigned = False + self.rover_xs = [] + self.rover_ys = [] + self.max_draw_length = 100 + + def exit(self): + """ + Cancel all state specific coroutines + """ + # Clear rover path. + self.rover_xs.clear() + self.rover_ys.clear() + def on_event(self, event) -> RoverState: """ Defines all transitions between states based on events @@ -26,7 +51,29 @@ def on_event(self, event) -> RoverState: """ state: RoverState = None if event == core.AutonomyEvents.START: - state = core.states.Navigating() + # Set time to zero. + self.idle_time = 0 + # Check if an ar tag is in front of us. + if ( + len( + [ + tag.distance + for tag in core.vision.ar_tag_detector.get_valid_tags() + if tag.distance <= core.constants.NAVIGATION_BACKUP_TAG_DISTANCE_THRESH + ] + ) + >= 1 + ): + # Move to reversing state. + state = core.states.Reversing() + else: + # Check reverse always toggle. + if core.constants.NAVIGATION_ALWAYS_REVERSE_OUT_OF_IDLE: + # Change states. + state = core.states.Reversing() + else: + # Change states. + state = core.states.Navigating() elif event == core.AutonomyEvents.ABORT: state = self @@ -48,4 +95,55 @@ async def run(self): """ # Send no commands to drive board, the watchdog will trigger and stop the rover from driving anyway # The only way to get out of this is through the state machine enable(), triggered by RoveComm + + # Only realign if not mode sim and relative positioning is turned on. + if core.MODE != "SIM" and core.vision.RELATIVE_POSITIONING: + # Check if time zero. + if self.idle_time == 0: + self.idle_time = time.time() + + # Check if idle time is over threshold and update position. + if time.time() - self.idle_time > core.constants.IDLE_TIME_GPS_REALIGN and not self.realigned: + # Check odd time. + if int(time.time()) % 5 == 0: + # Check accuracy of nav board. + if interfaces.nav_board.accuracy()[0] < core.constants.IDLE_GPS_ACCUR_THRESH: + # Realign gps with relative. + interfaces.nav_board.realign() + # Print warning that GPS location has been realigned. + self.logger.warning(f"Relative positional tracking has been realigned to current GPS location.") + # Set toggle. + self.realigned = True + else: + # Reset toggle. + self.realigned = False + pass + + + + # Store rover position path. + current = interfaces.nav_board.location() + utm_current = utm.from_latlon(current[0], current[1]) + self.rover_xs.append(utm_current[0]) + self.rover_ys.append(utm_current[1]) + # Write path 1 second before it expires. + if int(time.time()) % 2 == 0: + plt.cla() + # Plot path, current location, and goal. + plt.gca().set_aspect("equal", adjustable="box") + plt.plot(self.rover_xs, self.rover_ys, "-b", label="trajectory") + # Plot rover. + plt.plot(utm_current[0], utm_current[1], "2", label="rover") + plt.axis("equal") + plt.grid(True) + plt.title(f"IDLE - Heading: {int(interfaces.nav_board.heading())}") + plt.savefig("logs/!rover_path.png") + + # Check length of the rover path. + + if len(self.rover_xs) > self.max_draw_length: + # Cutoff old points. + self.rover_xs = self.rover_xs[::-1][:self.max_draw_length][::-1] + self.rover_ys = self.rover_ys[::-1][:self.max_draw_length][::-1] + return self diff --git a/core/states/navigating.py b/core/states/navigating.py index 931863ed..56790e0b 100644 --- a/core/states/navigating.py +++ b/core/states/navigating.py @@ -6,10 +6,17 @@ # Updated on Aug 21, 2022 # +import utm import core +import time import interfaces import algorithms +import matplotlib.pyplot as plt from core.states import RoverState +from algorithms import geomath, stanley_controller, heading_hold, small_movements +from algorithms.obstacle_avoider import ASTAR + +from core import constants class Navigating(RoverState): @@ -25,15 +32,22 @@ def start(self): """ Schedule Navigating """ + # Create state specific variable. + self.rover_xs = [] + self.rover_ys = [] + self.stuck_check_timer = 0 + self.stuck_check_last_position = [0, 0] - pass + # Clear AR Tags. + core.vision.ar_tag_detector.clear_tags() def exit(self): """ Cancel all state specific coroutines """ - - pass + # Clear rover path. + self.rover_xs.clear() + self.rover_ys.clear() def on_event(self, event) -> RoverState: """ @@ -65,6 +79,12 @@ def on_event(self, event) -> RoverState: elif event == core.AutonomyEvents.OBSTACLE_AVOIDANCE: state = core.states.Avoidance() + elif event == core.AutonomyEvents.REVERSE: + state = core.states.Reversing() + + elif event == core.AutonomyEvents.STUCK: + state = core.states.Stuck() + else: self.logger.error(f"Unexpected event {event} for state {self}") state = core.states.Idle() @@ -82,57 +102,106 @@ async def run(self) -> RoverState: :return: RoverState """ - + # Get current position and next desired waypoint position. + current = interfaces.nav_board.location(force_absolute=True) gps_data = core.waypoint_handler.get_waypoint() + """ + STATE TRANSITION AND WAYPOINT LOGIC. + """ + + # We should be navigating, so check if we have been in the same position for awhile. + # Only check every predefined amount of seconds. + if (time.time() - self.stuck_check_timer) > core.constants.STUCK_UPDATE_TIME: + # Calculate distance from goal for checking for markers and gates. + _, distance = algorithms.geomath.haversine( + self.stuck_check_last_position[0], self.stuck_check_last_position[1], current[0], current[1] + ) + # Convert km to m. + distance *= 1000 + + # Store new position. + self.stuck_check_last_position[0], self.stuck_check_last_position[1] = current[0], current[1] + + # Check if we are stuck. + if distance < core.constants.STUCK_MIN_DISTANCE: + # Move to stuck state. + return self.on_event(core.AutonomyEvents.STUCK) + + # Update timer. + self.stuck_check_timer = time.time() + # If the gps_data is none, there were no waypoints to be grabbed, # so log that and return if gps_data is None: self.logger.error("Navigating: No waypoint, please add a waypoint to start navigating") return self.on_event(core.AutonomyEvents.NO_WAYPOINT) + # Pull info out of waypoint. goal, start, leg_type = gps_data.data() - current = interfaces.nav_board.location() self.logger.debug( f"Navigating: Driving to ({goal[0]}, {goal[1]}) from ({start[0]}, {start[1]}. Currently at: ({current[0]}, {current[1]}" ) + # Calculate distance from goal for checking for markers and gates. + bearing, distance = geomath.haversine(current[0], current[1], goal[0], goal[1]) + distance *= 1000 # convert from km to m + if distance > constants.ARUCO_ENABLE_DISTANCE: + core.vision.ar_tag_detector.clear_tags() + + # Move to approaching marker if 1 ar tag is spotted during marker leg type if ( - core.vision.obstacle_avoidance.is_obstacle() - and core.vision.obstacle_avoidance.get_distance() < 1.5 - and core.vision.obstacle_avoidance.get_distance() - < ( - algorithms.geomath.haversine(current[0], current[1], goal[0], goal[1])[1] * 1000 - ) # If distance to goal is less than distance to object, continue + core.waypoint_handler.gps_data.leg_type == "MARKER" + and core.vision.ar_tag_detector.is_marker() + and distance < constants.ARUCO_ENABLE_DISTANCE ): + return core.states.ApproachingMarker() + + # Move to approaching gate if 2 ar tags are spotted during gate leg type. + if ( + (core.waypoint_handler.gps_data.leg_type == "GATE" or core.waypoint_handler.gps_data.leg_type == "MARKER") + and core.vision.ar_tag_detector.is_gate() + and distance < constants.ARUCO_ENABLE_DISTANCE + ): + core.waypoint_handler.gps_data.leg_type = "GATE" + return core.states.ApproachingGate() + + # Move to obstacle avoidance if objects are detected and we aren't close to the goal. + if ( + core.vision.obstacle_avoidance.is_obstacle() + and core.vision.obstacle_avoidance.get_distance() < constants.AVOIDANCE_OBJECT_DISTANCE_MAX + and (algorithms.geomath.haversine(current[0], current[1], goal[0], goal[1])[1] * 1000) + > constants.AVOIDANCE_ENABLE_DISTANCE_THRESHOLD + ): # If distance to object is less than distance to goal, continue self.logger.info("Detected obstacle, now avoiding") return self.on_event(core.AutonomyEvents.OBSTACLE_AVOIDANCE) - # Check if we are still approaching the goal + # If there are more points, set the new one and start from top if ( - algorithms.gps_navigate.get_approach_status( - goal, current, start, 0.75 if (leg_type == "POSITION") else core.WAYPOINT_DISTANCE_THRESHOLD - ) + algorithms.gps_navigate.get_approach_status(goal, current, start, core.WAYPOINT_DISTANCE_THRESHOLD) != core.ApproachState.APPROACHING ): - self.logger.info( - f"Navigating: Reached goal ({interfaces.nav_board._location[0]}, {interfaces.nav_board._location[1]})" - ) - - # If there are more points, set the new one and start from top if not core.waypoint_handler.is_empty(): + # Get new wapoint goal. gps_data = core.waypoint_handler.get_new_waypoint() self.logger.info(f"Navigating: Reached midpoint, grabbing new point ({goal[0]}, {goal[1]})") - return self.on_event(core.AutonomyEvents.NEW_WAYPOINT) - # Otherwise Trigger Next State + # Force path to expire and regenerate. + self.path_start_time = 0 + self.last_idx = -1 + + return self.on_event(core.AutonomyEvents.NEW_WAYPOINT) else: + # Print logger info. + self.logger.info( + f"Navigating: Reached goal ({interfaces.nav_board._location[0]}, {interfaces.nav_board._location[1]})" + ) # Stop all movement interfaces.drive_board.stop() # Set goal and start to current location - core.waypoint_handler.set_goal(interfaces.nav_board.location()) - core.waypoint_handler.set_start(interfaces.nav_board.location()) + core.waypoint_handler.set_goal(interfaces.nav_board.location(force_absolute=True)) + core.waypoint_handler.set_start(interfaces.nav_board.location(force_absolute=True)) if leg_type == "POSITION": self.logger.info("Reached Marker") @@ -151,12 +220,40 @@ async def run(self) -> RoverState: interfaces.multimedia_board.send_lighting_state(core.OperationState.REACHED_MARKER) return self.on_event(core.AutonomyEvents.REACHED_MARKER) else: + # Set gps goal to our current position. + core.waypoint_handler.set_goal(current) + # Move to search pattern state. return self.on_event(core.AutonomyEvents.REACHED_GPS_COORDINATE) + else: + # Force path to expire and regenerate. + self.path_start_time = 0 + self.last_idx = -1 + # Calculate powers. left, right = algorithms.gps_navigate.calculate_move( - goal, interfaces.nav_board.location(), start, core.MAX_DRIVE_POWER + goal, interfaces.nav_board.location(force_absolute=True), start, core.MAX_DRIVE_POWER ) - - self.logger.debug(f"Navigating: Driving at ({left}, {right})") + # Send drive. interfaces.drive_board.send_drive(left, right) + + # Store rover position path. + utm_current = utm.from_latlon(current[0], current[1]) + utm_goal = utm.from_latlon(goal[0], goal[1]) + self.rover_xs.append(utm_current[0]) + self.rover_ys.append(utm_current[1]) + # Write path 1 second before it expires. + if int(time.time()) % 2 == 0: + plt.cla() + # Plot path, current location, and goal. + plt.gca().set_aspect("equal", adjustable="box") + plt.plot(self.rover_xs, self.rover_ys, "-b", label="trajectory") + # Plot goal. + plt.plot(utm_goal[0], utm_goal[1], "^", label="goal") + # Plot rover. + plt.plot(utm_current[0], utm_current[1], "2", label="rover") + plt.axis("equal") + plt.grid(True) + plt.title(f"Simple Navigating - Heading: {int(interfaces.nav_board.heading())}") + plt.savefig("logs/!rover_path.png") + return self diff --git a/core/states/old_navigating.py b/core/states/old_navigating.py new file mode 100644 index 00000000..3c9034ca --- /dev/null +++ b/core/states/old_navigating.py @@ -0,0 +1,145 @@ +import asyncio +from core.vision import obstacle_avoidance +from core.waypoints import WaypointHandler +import core +import interfaces +import algorithms +from core.states import RoverState + + +class Navigating(RoverState): + """ + The goal of this state is to navigate to the GPS coordinates provided by base + station in succession, the last of which is the coordinate provided by the judges + for that leg of the task. Coordinates before the last are simply the operators in + base station’s best guess of the best path for the rover due to terrain identified + on RED’s map. + """ + + def start(self): + pass + + def exit(self): + # Cancel all state specific coroutines + pass + + def on_event(self, event) -> RoverState: + """ + Defines all transitions between states based on events + """ + state: RoverState = None + + if event == core.AutonomyEvents.NO_WAYPOINT: + state = core.states.Idle() + + elif event == core.AutonomyEvents.REACHED_MARKER: + state = core.states.Idle() + + elif event == core.AutonomyEvents.REACHED_GPS_COORDINATE: + state = core.states.SearchPattern() + + elif event == core.AutonomyEvents.NEW_WAYPOINT: + state = self + + elif event == core.AutonomyEvents.START: + state = self + + elif event == core.AutonomyEvents.ABORT: + state = core.states.Idle() + + elif event == core.AutonomyEvents.OBSTACLE_AVOIDANCE: + state = core.states.Avoidance() + + else: + self.logger.error(f"Unexpected event {event} for state {self}") + state = core.states.Idle() + + # Call exit() if we are not staying the same state + if state != self: + self.exit() + + # Return the state appropriate for the event + return state + + async def run(self) -> RoverState: + """ + Defines regular rover operation when under this state + """ + + gps_data = core.waypoint_handler.get_waypoint() + + # If the gps_data is none, there were no waypoints to be grabbed, + # so log that and return + if gps_data is None: + self.logger.error("Navigating: No waypoint, please add a waypoint to start navigating") + return self.on_event(core.AutonomyEvents.NO_WAYPOINT) + + goal, start, leg_type = gps_data.data() + current = interfaces.nav_board.location() + self.logger.debug( + f"Navigating: Driving to ({goal[0]}, {goal[1]}) from ({start[0]}, {start[1]}. Currently at: ({current[0]}, {current[1]}" + ) + + if ( + core.vision.obstacle_avoidance.is_obstacle() + and core.vision.obstacle_avoidance.get_distance() < 1.5 + and core.vision.obstacle_avoidance.get_distance() + < ( + algorithms.geomath.haversine(current[0], current[1], goal[0], goal[1])[1] * 1000 + ) # If distance to goal is less than distance to object, continue + ): + self.logger.info("Detected obstacle, now avoiding") + return self.on_event(core.AutonomyEvents.OBSTACLE_AVOIDANCE) + + # Check if we are still approaching the goal + if ( + algorithms.gps_navigate.get_approach_status( + goal, current, start, 0.75 if (leg_type == "POSITION") else core.WAYPOINT_DISTANCE_THRESHOLD + ) + != core.ApproachState.APPROACHING + ): + self.logger.info( + f"Navigating: Reached goal ({interfaces.nav_board._location[0]}, {interfaces.nav_board._location[1]})" + ) + + # If there are more points, set the new one and start from top + if not core.waypoint_handler.is_empty(): + gps_data = core.waypoint_handler.get_new_waypoint() + self.logger.info(f"Navigating: Reached midpoint, grabbing new point ({goal[0]}, {goal[1]})") + return self.on_event(core.AutonomyEvents.NEW_WAYPOINT) + + # Otherwise Trigger Next State + else: + # Stop all movement + interfaces.drive_board.stop() + + # Set goal and start to current location + core.waypoint_handler.set_goal(interfaces.nav_board.location()) + core.waypoint_handler.set_start(interfaces.nav_board.location()) + + if leg_type == "POSITION": + self.logger.info("Reached Marker") + + # Transmit that we have reached the marker + core.rovecomm_node.write( + core.RoveCommPacket( + core.manifest["Autonomy"]["Telemetry"]["ReachedMarker"]["dataId"], + "B", + (1,), + ), + False, + ) + + # Tell multimedia board to flash our LED matrix green to indicate reached marker + interfaces.multimedia_board.send_lighting_state(core.OperationState.REACHED_MARKER) + return self.on_event(core.AutonomyEvents.REACHED_MARKER) + else: + return self.on_event(core.AutonomyEvents.REACHED_GPS_COORDINATE) + + left, right = algorithms.gps_navigate.calculate_move( + goal, interfaces.nav_board.location(), start, core.MAX_DRIVE_POWER + ) + + self.logger.debug(f"Navigating: Driving at ({left}, {right})") + interfaces.drive_board.send_drive(left, right) + return self diff --git a/core/states/reversing.py b/core/states/reversing.py new file mode 100644 index 00000000..d7a161dc --- /dev/null +++ b/core/states/reversing.py @@ -0,0 +1,77 @@ +# +# Mars Rover Design Team +# idle.py +# +# Created on Nov 20, 2020 +# Updated on Aug 21, 2022 +# + +import core +import logging +import interfaces +from core.states import RoverState +from algorithms import small_movements + + +class Reversing(RoverState): + """ + In this state the program will command the rover to backup. + Its singular purpose is to prevent the rover from running into a marker of obstacle. + """ + + def start(self): + # Intialize state member variables. + self.logger = logging.getLogger(__name__) + # Print log. + self.logger.warning("BACKING UP! AR Tag detected in front of rover.") + # Store current location when state is entered. + self.start_position = interfaces.nav_board.location(force_absolute=True) + + def on_event(self, event) -> RoverState: + """ + Defines all transitions between states based on events + + :param event: + :return: RoverState + """ + state: RoverState = None + + if event == core.AutonomyEvents.START: + state = self + + elif event == core.AutonomyEvents.ABORT: + # Move back to idle. + state = core.states.Idle() + elif event == core.AutonomyEvents.REVERSE_COMPLETE: + # Change states to normal navigation. + state = core.states.Navigating() + + else: + self.logger.error(f"Unexpected event {event} for state {self}") + state = self + + # Call exit() if we are not staying the same state + if state != self: + self.exit() + + # Return the state appropriate for the event + return state + + async def run(self): + """ + Defines regular rover operation when under this state + """ + # Backup for a defined distance. + done_reversing = small_movements.backup( + self.start_position[0], + self.start_position[1], + core.constants.NAVIGATION_START_BACKUP_DISTANCE, + core.constants.NAVIGATION_BACKUP_SPEED, + ) + + # Check if we are done reversing. + if done_reversing: + # Exit state. + return self.on_event(core.AutonomyEvents.REVERSE_COMPLETE) + + return self diff --git a/core/states/search_pattern.py b/core/states/search_pattern.py index cf877061..19789a28 100644 --- a/core/states/search_pattern.py +++ b/core/states/search_pattern.py @@ -6,11 +6,16 @@ # Updated on Aug 21, 2022 # +import utm import core import algorithms import interfaces import asyncio +import time +import numpy as np +import matplotlib.pyplot as plt from core.states import RoverState +from algorithms.obstacle_avoider import ASTAR class SearchPattern(RoverState): @@ -23,15 +28,19 @@ def start(self): """ Schedule Search Pattern """ - - pass + # Create state specific variable. + self.rover_xs = [] + self.rover_ys = [] + self.stuck_check_timer = 0 + self.stuck_check_last_position = [0, 0] def exit(self): """ Cancel all state specific tasks """ - - pass + # Clear rover path. + self.rover_xs.clear() + self.rover_ys.clear() def on_event(self, event) -> RoverState: """ @@ -40,7 +49,6 @@ def on_event(self, event) -> RoverState: :param event: :return: RoverState """ - state: RoverState = None if event == core.AutonomyEvents.MARKER_SEEN: @@ -58,6 +66,9 @@ def on_event(self, event) -> RoverState: elif event == core.AutonomyEvents.ABORT: state = core.states.Idle() + elif event == core.AutonomyEvents.STUCK: + state = core.states.Stuck() + else: self.logger.error(f"Unexpected event {event} for state {self}") state = core.states.Idle() @@ -75,12 +86,42 @@ async def run(self) -> RoverState: :return: RoverState """ - + # Get current position and next desired waypoint position. + current = interfaces.nav_board.location(force_absolute=True) gps_data = core.waypoint_handler.get_waypoint() + """ + STATE TRANSITION AND WAYPOINT LOGIC. + """ + # We should be navigating, so check if we have been in the same position for awhile. + # Only check every predefined amount of seconds. + if (time.time() - self.stuck_check_timer) > core.constants.STUCK_UPDATE_TIME: + # Calculate distance from goal for checking for markers and gates. + _, distance = algorithms.geomath.haversine( + self.stuck_check_last_position[0], self.stuck_check_last_position[1], current[0], current[1] + ) + # Convert km to m. + distance *= 1000 + + # Store new position. + self.stuck_check_last_position[0], self.stuck_check_last_position[1] = current[0], current[1] + + # Check if we are stuck. + if distance < core.constants.STUCK_MIN_DISTANCE: + # Move to stuck state. + return self.on_event(core.AutonomyEvents.STUCK) + + # Update timer. + self.stuck_check_timer = time.time() + + # If the gps_data is none, there were no waypoints to be grabbed, + # so log that and return + if gps_data is None: + self.logger.error("SearchPattern: No waypoint, please add a waypoint to start navigating") + return self.on_event(core.AutonomyEvents.NO_WAYPOINT) + + # Pull info out of waypoint. goal, start, leg_type = gps_data.data() - current = interfaces.nav_board.location() - self.logger.debug( f"Searching: Location ({interfaces.nav_board._location[0]}, {interfaces.nav_board._location[1]}) to Goal ({goal[0]}, {goal[1]})" ) @@ -91,7 +132,7 @@ async def run(self) -> RoverState: interfaces.drive_board.stop() # Sleep for a brief second - await asyncio.sleep(0.1) + await asyncio.sleep(core.EVENT_LOOP_DELAY) self.logger.info("Search Pattern: Gate seen") return self.on_event(core.AutonomyEvents.GATE_SEEN) @@ -100,26 +141,46 @@ async def run(self) -> RoverState: interfaces.drive_board.stop() # Sleep for a brief second - await asyncio.sleep(0.1) + await asyncio.sleep(core.EVENT_LOOP_DELAY) self.logger.info("Search Pattern: Marker seen") return self.on_event(core.AutonomyEvents.MARKER_SEEN) if algorithms.gps_navigate.get_approach_status(goal, current, start) != core.ApproachState.APPROACHING: - interfaces.drive_board.stop() + # interfaces.drive_board.stop() # Sleep for a little bit before we move to the next point, allows for AR Tag to be picked up - await asyncio.sleep(0.1) + await asyncio.sleep(core.EVENT_LOOP_DELAY) # Find and set the next goal in the search pattern goal = algorithms.marker_search.calculate_next_coordinate(start, goal) core.waypoint_handler.set_goal(goal) - self.logger.info(f"Search Pattern: Adding New Waypoint ({goal[0]}, {goal[1]}") - - left, right = algorithms.gps_navigate.calculate_move(goal, current, start, core.MAX_DRIVE_POWER) - - self.logger.debug(f"Search Pattern: Driving at ({left}, {right})") + # Calculate drive power. + left, right = algorithms.gps_navigate.calculate_move(goal, current, start, core.constants.SEARCH_DRIVE_POWER) + # Send drive. interfaces.drive_board.send_drive(left, right) + # Send drive. + self.logger.info(f"Search Pattern: Driving at ({left}, {right})") + + # Store rover position path. + utm_current = utm.from_latlon(current[0], current[1]) + utm_goal = utm.from_latlon(goal[0], goal[1]) + self.rover_xs.append(utm_current[0]) + self.rover_ys.append(utm_current[1]) + # Write path 1 second before it expires. + if int(time.time()) % 2 == 0: + plt.cla() + # Plot path, current location, and goal. + plt.gca().set_aspect("equal", adjustable="box") + plt.plot(self.rover_xs, self.rover_ys, "-b", label="trajectory") + # Plot goal. + plt.plot(utm_goal[0], utm_goal[1], "^", label="goal") + # Plot rover. + plt.plot(utm_current[0], utm_current[1], "2", label="rover") + plt.axis("equal") + plt.grid(True) + plt.title(f"Simple Search Pattern - Heading: {int(interfaces.nav_board.heading())}") + plt.savefig("logs/!rover_path.png") return self diff --git a/core/states/state_machine.py b/core/states/state_machine.py index 068ce71c..cad2cd6a 100644 --- a/core/states/state_machine.py +++ b/core/states/state_machine.py @@ -55,7 +55,7 @@ async def run(self): elif self.disable_flag is True: self.state = self.state.on_event(core.AutonomyEvents.ABORT) # Update the state display on lighting to Teleop - interfaces.multimedia_board.send_lighting_state(core.OperationState.TELEOP) + # interfaces.multimedia_board.send_lighting_state(core.OperationState.TELEOP) self.disable_flag = False # Run the current state diff --git a/core/states/stuck.py b/core/states/stuck.py new file mode 100644 index 00000000..950ba6c2 --- /dev/null +++ b/core/states/stuck.py @@ -0,0 +1,112 @@ +# +# Mars Rover Design Team +# idle.py +# +# Created on Nov 20, 2020 +# Updated on Aug 21, 2022 +# + +import core +import time +import asyncio +import random +import logging +import interfaces +from core.states import RoverState + + +class Stuck(RoverState): + """ + In this state the program will command the rover to stop as it is stuck. + Its singular purpose is to prevent the rover from killing itself into a marker or obstacle. + """ + + def start(self): + # Intialize state member variables. + self.logger = logging.getLogger(__name__) + # Stop drive. + interfaces.drive_board.stop() + # Set random seed. + random.seed(time.time()) + self.rand_num = random.randint(1, 9) + # Get stuck state start timer. + self.start_timer = time.time() + + def on_event(self, event) -> RoverState: + """ + Defines all transitions between states based on events + + :param event: + :return: RoverState + """ + state: RoverState = None + + if event == core.AutonomyEvents.START: + # Change states to Idle + state = core.states.Reversing() + + elif event == core.AutonomyEvents.ABORT: + # Change states to Idle + state = core.states.Idle() + + else: + self.logger.error(f"Unexpected event {event} for state {self}") + state = self + + # Call exit() if we are not staying the same state + if state != self: + self.exit() + + # Return the state appropriate for the event + return state + + async def run(self): + """ + Defines regular rover operation when under this state + """ + # Print log instructions. + if self.rand_num == 1: + self.logger.warning( + "Well, doggone it! That there Rover fella done figured out he's got himself all tangled up like a ticklin' tumbleweed in a twister. Now, y'all got two options to get him outta this predicament: Give that 'START AUTONOMY' button a poke or press the 'STOP AUTONOMY' button to fetch him back to his lazybones state. Either way, Rover's hopin' y'all can lend him a paw, 'cause this situation is stickier than molasses on a summer porch swing!" + ) + elif self.rand_num == 2: + self.logger.warning( + "Well, dagnabbit! This here rover done gone and figured out it's plum stuck. Y'all got two options: Either give 'er a good ol' holler with the START AUTONOMY hootenanny or holler STOP AUTONOMY to reckon it back to its idle state. Remember, both them buttons do the trick, so pick yer poison and let the shenanigans begin!" + ) + elif self.rand_num == 3: + self.logger.warning( + "Well, shucks! That fancy-pants rover done gone and reckoned it's plum stuck in a pickle jar! Y'all got two options now: hit that snazzy lil' START AUTONOMY button to let 'er rest easy, or give 'er a holler with the STOP AUTONOMY button to also bring 'er back to the snoozeville state. Git ready for a wild ride, y'all!" + ) + elif self.rand_num == 4: + self.logger.warning( + "Well, dadgummit! That there fancy Rover contraption done gone and decided it's plumb stuck! Ya reckon we oughta give 'er a good ol' hickifyin' treatment? Y'all got two options: hit that there START AUTONOMY button and watch 'er kick back into idle, or give 'er a holler with the STOP AUTONOMY button to also bring 'er on back to the lazy daisy idle state. Yeehaw!" + ) + elif self.rand_num == 5: + self.logger.warning( + "Well, shoot dang! That fancy ol' Rover contraption done figured out it's in a mighty pickle. So, reckon ya got yerself two options: reckon ya can press the dandy ol' START AUTONOMY button or the STOP AUTONOMY button to get that thingamajig back to its good ol' idle state. Either way, that Rover gal gonna be sittin' pretty, just chillin' like a cucumber on a hot summer day." + ) + elif self.rand_num == 6: + self.logger.warning( + "Like, oh my gosh! The rover's all like, 'I'm totally stuck, you guys!' So, here's the deal: you gotta, like, choose between pressing the fabulously hip START AUTONOMY or the totally groovy STOP AUTONOMY buttons to get it back to its chill idle state. No matter which button you pick, this rover babe's gonna be all chillaxing and having a blast, ya know? So, let's give it some love and get it out of its sticky situation, alright? Toodles!" + ) + elif self.rand_num == 7: + self.logger.warning( + "Oh my gosh, like, the rover is, like, totally over it and is, like, convinced that it's, like, stuck and stuff. So, like, you have the option to, like, totally press the START AUTONOMY or STOP AUTONOMY buttons, and either way, she's just gonna be, like, super chill and go back to, like, her idle state, you know? It's, like, no biggie, she's just, like, chilling and waiting for some cosmic inspiration or whatever. So, like, do your thing and let the rover, like, groove in her own laid-back way, okay?" + ) + elif self.rand_num == 8: + self.logger.warning( + "Yo, dude! The rover's like, 'Bro, I'm totally stuck, man.' So, check this out: you gotta hit either the gnarly 'START AUTONOMY' button or the chillin' 'STOP AUTONOMY' button to bring it back to the idle state. But hey, no worries, dude! Whether you go full autonomous or stop the autonomy, that rover's just kickin' it and having a chill time. Stay cool, bro! 🤙" + ) + elif self.rand_num == 9: + self.logger.warning( + "Dude, the Rover's like, 'Whoa, man, I'm totally stuck, bro.' But don't worry, there's a chill solution! Check it out, we got two gnarly buttons: 'START AUTONOMY' and 'STOP AUTONOMY.' No matter which one you hit, this Rover's just gonna kick back and chillax in the idle state, dude. So, like, choose your own adventure, man. Keep the autonomy flowin' or bring it back to chill mode. Either way, this Rover's just cruisin' and enjoyin' the cosmic vibes, man." + ) + + # Check if we've been in stuck for more than 5 seconds. + if (time.time() - self.start_timer) > core.constants.STUCK_STILL_TIME: + return self.on_event(core.AutonomyEvents.START) + + # Do nothing. + await asyncio.sleep(core.constants.EVENT_LOOP_DELAY) + + return self diff --git a/core/vision/__init__.py b/core/vision/__init__.py index 4d36e02e..26b7bb02 100644 --- a/core/vision/__init__.py +++ b/core/vision/__init__.py @@ -22,26 +22,49 @@ feed_handler = FeedHandler() # Flag to indicate whether we are streaming -STREAM_FLAG = True +STREAM_FLAG = False +AVOIDANCE_FLAG = False +RELATIVE_POSITIONING = False +ZED_MAGNETOMETER = False +YOLO_CLASSES = None -def setup(type="ZED", stream="Y"): +def setup( + type="ZED", + stream="Y", + avoidance="DISABLE", + yolo_classes=None, + relative_positioning="ENABLE", + zed_magnetometer="ENABLE", +): """ Sets up the vision system and camera/feed handlers :param type: (str) Currently supports "ZED" and "SIM", specifies the type of camera to init - :param stream: + :param stream: Whether or not to enable the camera streams. + :param avoidance: Whether or not to enable obstacle avoidance. + :param yolo_classes: A list of YOLO class indexes to track. + :param relative_positioning: Whether or not to enable ZED realitive positional tracking. + :param zed_magnetometer: Whether or not to use the ZED's built in compass. MUST BE CALIBRATED! """ if type == "ZED": + # Import correct camera handler. from core.vision.zed_handler import ZedHandler + # Initialize object. this.camera_handler = ZedHandler() this.camera_handler.start() + + # Configure camera handler properties. + if relative_positioning == "ENABLE": + # Enable ZED positional tracking. + this.camera_handler.enable_pose_tracking() elif type == "SIM": from core.vision.sim_cam_handler import SimCamHandler this.camera_handler = SimCamHandler() this.camera_handler.start() + else: # TODO: Initialize a regular webcam here pass @@ -52,6 +75,27 @@ def setup(type="ZED", stream="Y"): else: this.STREAM_FLAG = False + # Flag to enable whether or not we are doing obstacle avoidance. + if avoidance == "ENABLE": + this.AVOIDANCE_FLAG = True + else: + this.AVOIDANCE_FLAG = False + + # Flag to enable whether or not we are doing relative positioning. + if relative_positioning == "ENABLE": + this.RELATIVE_POSITIONING = True + else: + this.RELATIVE_POSITIONING = False + + # Flag to enable whether or not we are using the zed compass. + if zed_magnetometer == "ENABLE": + this.ZED_MAGNETOMETER = True + else: + this.ZED_MAGNETOMETER = False + + # Store yolo_classes list. + this.YOLO_CLASSES = yolo_classes + def close(type="ZED"): """ diff --git a/core/vision/ar_tag_detector.py b/core/vision/ar_tag_detector.py index d8f2b16d..67b4f9db 100644 --- a/core/vision/ar_tag_detector.py +++ b/core/vision/ar_tag_detector.py @@ -1,72 +1,150 @@ -# -# Mars Rover Design Team -# ar_tag_detector.py -# -# Created on Feb 23, 2021 -# Updated on Aug 21, 2022 -# - import asyncio -from typing import List -from algorithms.ar_tag import Tag import core import algorithms import logging +import traceback +import copy +from core.constants import ARUCO_FRAMES_DETECTED -# Dict to hold the obstacle info -ar_tags = [] +# List to hold the tag info +leg_valid_tags = [] +distances = [] +clear_tags_toggle = False async def async_ar_tag_detector(): """ Async function to find obstacles. """ + # Setup logger for function. logger = logging.getLogger(__name__) - while True: - reg_img = core.vision.camera_handler.grab_regular() - - tags, reg_img = algorithms.ar_tag.detect_ar_tag(reg_img) + # Declare detection objects. + TagDetector = algorithms.ar_tag.ArucoARTagDetector() + # Declare toggle for reseting tags. + global clear_tags_toggle + global leg_valid_tags + global distances - core.vision.feed_handler.handle_frame("artag", reg_img) - - if len(tags) > 0: - ar_tags.clear() - ar_tags.extend(tags) - else: - ar_tags.clear() - - logger.debug("Running AR Tag async") + while True: + # Maybe this is bad practice but it's helpful. + try: + # Get normal image from camera. + reg_img = core.vision.camera_handler.grab_regular() + + # Detect tags. + TagDetector.detect_ar_tag(reg_img) + # Filter tags. + # if (core.states.state_machine.get_state_str() == "ApproachingGate"): + # TagDetector.filter_ar_tags(angle_range=45, distance_range=15, valid_id_range=[0, 1, 2, 3, 4, 5]) + # else: + # TagDetector.filter_ar_tags(angle_range=180, distance_range=15, valid_id_range=[0, 1, 2, 3, 4, 5]) + # Get and store tags. + ar_tags = TagDetector.get_tags() + + # Draw tags. + reg_img = TagDetector.track_ar_tags(reg_img) + core.vision.feed_handler.handle_frame("artag", reg_img) + + # Print info about tags if 1 or more detected. + if len(ar_tags) >= 1: + # Build output string. + output = f"{len(ar_tags)} Tags Detected:\n" + # Add individual tag data to output. + for tag in ar_tags: + output += ( + f"[ID:{tag.id} DIST:{int(tag.distance)} ANGLE:{int(tag.angle)} DETS:{tag.times_detected}]\n" + ) + # Print log output. + logger.info(output) + + # Check if the waypoint handler has a waypoint. + if core.waypoint_handler.gps_data: + # Check if the waypoint is a marker or gate and that we have detected a valid amount of tags. + if (core.waypoint_handler.gps_data.leg_type == "MARKER" and len(ar_tags) > 0) or ( + core.waypoint_handler.gps_data.leg_type == "GATE" and len(ar_tags) > 1 + ): + # Clear valid_ids list. + leg_valid_tags.clear() + + # Loop through each tag and check if the times_detected for each one is over the threshold. + for tag in ar_tags: + if tag.times_detected >= ARUCO_FRAMES_DETECTED: + leg_valid_tags.append(tag) + distances.append(tag.distance) + + if clear_tags_toggle: + # Clear tags in detector object. + TagDetector.clear_tags() + # Reset toggle. + clear_tags_toggle = False + + except Exception: + # Because we are using async functions, they don't print out helpful tracebacks. We must do this instead. + logger.critical(traceback.format_exc()) + + await asyncio.sleep(core.EVENT_LOOP_DELAY) + + +def clear_tags(): + """ + Clears the tag list. - await asyncio.sleep(1 / core.vision.camera_handler.get_fps()) + :returns: None + """ + # Declare global var. + global clear_tags_toggle + global leg_valid_tags + # Clear detection object by setting toggle. + clear_tags_toggle = True + # Clear local lists. + leg_valid_tags.clear() def is_marker(): """ Returns whether there is a visible marker. - :return: detect (bool) - whether something was detected + :return: detect (bool) - whether or not something was detected """ + # Declare global var. + global leg_valid_tags - return len(ar_tags) > 0 + return True if len(leg_valid_tags) > 0 and leg_valid_tags[0].id in [0, 1, 2, 3, 4, 5] else False def is_gate(): """ Returns whether there are multiple visible AR tags. We don't look for - 2 specifically because we don't want a false positive to cause this bool + 2 specfically because we don't want a false positive to cause this bool to fail and abort immediately. - :return: detect (bool) - whether something was detected + :return: detect (bool) - whether or not something was detected """ + # Declare global var. + global leg_valid_tags - return len(ar_tags) > 1 + return ( + True + if len(leg_valid_tags) >= 2 and leg_valid_tags[0].id in [4, 5] and leg_valid_tags[1].id in [4, 5] + else False + ) -def get_tags() -> List[Tag]: +def get_distances(): + """ + Returns just the distances of each tag. """ - Returns a list of all the tags found. + # Declare global var. + global distances - :return: tags - A list of named tuples of the type Tag + return distances + + +def get_valid_tags(): + """ + Returns a filtered list of valid tags depending on waypoint leg type. (MARKER or GATE) """ + # Declare global var. + global leg_valid_tags - return ar_tags + return leg_valid_tags diff --git a/core/vision/camera.py b/core/vision/camera.py index c710182f..a1354fe1 100644 --- a/core/vision/camera.py +++ b/core/vision/camera.py @@ -41,6 +41,9 @@ def grab_depth(self): def grab_depth_data(self): raise NotImplementedError("Grab_depth_data not implemented for this camera type") + def grab_point_cloud(self): + raise NotImplementedError("Grab_point_cloud not implemented for this camera type") + def get_reg_res(self) -> Tuple[int, int]: """ Returns the resolution for the regular images @@ -59,6 +62,15 @@ def get_depth_res(self) -> Tuple[int, int]: """ return self.depth_res_x, self.depth_res_y + def get_cloud_res(self) -> Tuple[int, int]: + """ + Returns the resolution for the point cloud. + + :return: reg_res_x - the resolution of the width of the image + reg_res_y - the resolution of the height of the image + """ + return self.point_cloud_res_x, self.point_cloud_res_y + def get_hfov(self) -> int: return self.hfov diff --git a/core/vision/feed_handler.py b/core/vision/feed_handler.py index 6dc37e90..06c6b6ea 100644 --- a/core/vision/feed_handler.py +++ b/core/vision/feed_handler.py @@ -12,11 +12,9 @@ import multiprocessing as mp import os -# Pyfakewebcam requires linux -from pyfakewebcam import FakeWebcam - if sys.platform == "linux": - import pyfakewebcam + # Pyfakewebcam requires linux + from pyfakewebcam import FakeWebcam def feed_process( @@ -49,7 +47,7 @@ def feed_process( # Only attempt to stream video if on Linux (due to package dependencies) if stream_video and sys.platform == "linux": - streamer: FakeWebcam = pyfakewebcam.FakeWebcam( + streamer: FakeWebcam = FakeWebcam( f"/dev/video{num}", int(resolution_x / 2), int(resolution_y / 2) ) # append v4l output to list of cameras diff --git a/core/vision/obstacle_avoidance.py b/core/vision/obstacle_avoidance.py index b1f7842e..c44cf063 100644 --- a/core/vision/obstacle_avoidance.py +++ b/core/vision/obstacle_avoidance.py @@ -7,55 +7,99 @@ # import logging +import asyncio import core -import algorithms import cv2 -import asyncio +import algorithms +import core.constants +import os +import traceback # Dict to hold the obstacle info -obstacle_dict = {"detected": False, "angle": None, "distance": None} +obstacle_dict = { + "detected": False, + "angle": None, + "distance": None, + "object_summary": None, + "inference_time": -1, + "obstacle_list": None, +} async def async_obstacle_detector(): """ Async function to find obstacles """ + # Setup logging. logger = logging.getLogger(__name__) - while True: - reg_img = core.vision.camera_handler.grab_regular() - depth_matrix = core.vision.camera_handler.grab_depth_data() - - mask, lower = algorithms.obstacle_detector.get_floor_mask( - reg_img, int(reg_img.shape[1] / 2), int(reg_img.shape[0] / 2) - ) - - depth_matrix = cv2.bitwise_and(depth_matrix, depth_matrix, mask=mask) - obstacle = algorithms.obstacle_detector.detect_obstacle(depth_matrix, 1, 4) + # Declare detection objects + ObstacleIgnorance = algorithms.obstacle_detector.YOLOObstacleDetector( + weights=os.path.dirname(__file__) + "/../../resources/yolo_models/2022-0601/weights/best.pt", + model_image_size=640, + classes=core.vision.YOLO_CLASSES, + ) - # Resize the image so it matches the dimensions of the depth data - depth_img_x, depth_img_y = core.vision.camera_handler.get_depth_res() - reg_img = cv2.resize(reg_img, (depth_img_x, depth_img_y)) + while True: + # Create instance variables. + object_summary = "" + inference_time = -1 + + # Maybe this is bad practice but it's helpful. + try: + # Get regular image from camera. + reg_img = core.vision.camera_handler.grab_regular() + + # Detect obstacles. + ObstacleIgnorance.detect_obstacles( + reg_img, core.constants.DETECTION_MODEL_CONF, core.constants.DETECTION_MODEL_IOU + ) - if obstacle != []: - # Track the obstacle in the depth matrix - angle, distance, _ = algorithms.obstacle_detector.track_obstacle( - depth_matrix, obstacle, True, reg_img, False + # Track a specific obstacle. (closest one) + angle, distance, object_summary, inference_time, object_locations = ObstacleIgnorance.track_obstacle( + reg_img ) - # Update the current obstacle info - obstacle_dict["detected"] = True - obstacle_dict["angle"] = angle - obstacle_dict["distance"] = distance / 1000 - else: - # Update the current obstacle info - obstacle_dict["detected"] = False - obstacle_dict["angle"] = None - obstacle_dict["distance"] = None - - if obstacle_dict["detected"]: - logger.info(f'Obstacle detected at distance: {obstacle_dict["distance"]}') - core.vision.feed_handler.handle_frame("obstacle", reg_img) - await asyncio.sleep(1 / core.vision.camera_handler.get_fps()) + + # If obstacle has been detected store its info. + if distance > -1: + # Update the current obstacle info + obstacle_dict["detected"] = True + obstacle_dict["angle"] = angle + obstacle_dict["distance"] = distance / 1000 + obstacle_dict["object_summary"] = object_summary + obstacle_dict["inference_time"] = inference_time + obstacle_dict["obstacle_list"] = object_locations + else: + # Update the current obstacle info + obstacle_dict["detected"] = False + obstacle_dict["angle"] = None + obstacle_dict["distance"] = None + obstacle_dict["object_summary"] = object_summary + obstacle_dict["inference_time"] = inference_time + obstacle_dict["obstacle_list"] = None + + # Give frame with detections overlay to feed handler. + core.vision.feed_handler.handle_frame("obstacle", reg_img) + + # Show detections window if DISPLAY constant is set. + if core.constants.DISPLAY_TEST_MODE: + # Open window for detections viewing. + cv2.imshow("Obstacle Detections", cv2.resize(reg_img.copy(), (640, 480))) + # Must call waitkey or window won't display. + if cv2.waitKey(1) & 0xFF == ord("q"): + # If user tries to quit window, print instruction on how to properly disable. + logging.warning(msg="To disable window output, edit core.vision.constants file.") + + # Print detected objects for user. + if obstacle_dict["detected"]: + logger.info( + f"Object tracked at a distance of {obstacle_dict['distance']} meters and {obstacle_dict['angle']} degrees from camera center!\nTotal Objects Detected: {object_summary}Done. ({inference_time:.3f}s)" + ) + except Exception: + # Because we are using async functions, they don't print out helpful tracebacks. We must do this instead. + logger.critical(traceback.format_exc()) + # Must await async process or the code will pause here. + await asyncio.sleep(core.EVENT_LOOP_DELAY) def is_obstacle(): @@ -64,7 +108,6 @@ def is_obstacle(): :return: detect (bool) - whether something was detected """ - return obstacle_dict["detected"] @@ -74,7 +117,6 @@ def get_angle(): :return: angle of obstacle """ - return obstacle_dict["angle"] @@ -84,5 +126,31 @@ def get_distance(): :return: distance of obstacle """ - return obstacle_dict["distance"] + + +def get_object_summary(): + """ + Returns a string containing a summary of all the detected objects. + + :returns summary: The summary string. + """ + return obstacle_dict["object_summary"] + + +def get_inference_time(): + """ + Returns yolo model inference time. + + :returns inference_time: The YOLO models inference time. + """ + return obstacle_dict["inference_time"] + + +def get_obstacle_locations(): + """ + Returns a list of object locations, could be useful. + + :returns object_locations: A list containing the 3d world coordinates of the objects in meters from the camera center point. + """ + return obstacle_dict["obstacle_list"] diff --git a/core/vision/sim_cam_handler.py b/core/vision/sim_cam_handler.py index 926115aa..06acb679 100644 --- a/core/vision/sim_cam_handler.py +++ b/core/vision/sim_cam_handler.py @@ -1,11 +1,4 @@ -# -# Mars Rover Design Team -# sim_cam_handler.py -# -# Created on Jan 11, 2021 -# Updated on Aug 21, 2022 -# - +from ctypes import pointer from core.vision.camera import Camera import logging from core.vision import feed_handler @@ -13,6 +6,7 @@ import socket, cv2, pickle, struct import gzip import numpy as np +import time class SimCamHandler(Camera): @@ -33,11 +27,13 @@ def __init__(self): self.r_lock = threading.RLock() # Define the camera resolutions - self.depth_res_x = 640 - self.depth_res_y = 360 - self.reg_res_x = 1280 - self.reg_res_y = 720 - self.hfov = 85 + self.point_cloud_res_x = 813 + self.point_cloud_res_y = 404 + self.depth_res_x = 1920 + self.depth_res_y = 1080 + self.reg_res_x = 1920 + self.reg_res_y = 1080 + self.hfov = 110 # Desired FPS self.fps = 30 @@ -49,6 +45,11 @@ def __init__(self): self.reg_img = None self.depth_img = None + # Create initial depth and point_cloud data arrays. + self.depth_data = [] + self.point_cloud = [] + self.scale_vals = [0, 0] + # Create thread to constantly grab frames, and pass them to other processes to stream/save self._stop = threading.Event() @@ -71,13 +72,13 @@ def frame_grabber(self): # | uint32t (Q) | char (C) | message (bytearray) | # +---------------------+--------------------------------+------------------------+ # | The number of bytes | The type of image frame: | The bytes in the image | - # | in the image frame | "r" for regular, "d" for depth | frame itself | + # | in the image frame | "r" for regular, "d" for depth,| frame itself | + # | | "p" for point_cloud | | # +---------------------+--------------------------------+------------------------+ - while not self._stop.is_set(): # First read the in the data length specifier (should be 8 bits) while len(data) < data_length_size: - packet = self.client_socket.recv(4 * 1024) + packet = self.client_socket.recv(8 * 1024) if not packet: break data += packet @@ -87,9 +88,9 @@ def frame_grabber(self): data = data[data_length_size:] # The first element in data is the type of frame encoded as a single byte - # Either "r" or "d" for regular or depth + # Either "r" or "d" or "p" for regular or depth or point_cloud while len(data) < type_size: - data += self.client_socket.recv(4 * 1024) + data += self.client_socket.recv(8 * 1024) type = data[:type_size] data = data[type_size:] msg_type = struct.unpack("c", type)[0] @@ -100,12 +101,12 @@ def frame_grabber(self): # Now keep reading the payload until we have read in all expected data in # the frame while len(data) < msg_size: - data += self.client_socket.recv(4 * 1024) + data += self.client_socket.recv(8 * 1024) frame_data = data[:msg_size] data = data[msg_size:] - # For regular images or depth data we have different decompression techniques + # For regular images or depth data or point_cloud we have different decompression techniques # this is due to the type of data we are sending self.r_lock.acquire() if msg_type == b"r": @@ -115,6 +116,17 @@ def frame_grabber(self): self.encoded_img = gzip.decompress(frame_data) self.encoded_img = pickle.loads(self.encoded_img) self.depth_data = struct.unpack(str(int(len(self.encoded_img) / 4)) + "f", self.encoded_img) + elif msg_type == b"p": + self.encoded_img = pickle.loads(frame_data) + self.point_cloud = cv2.imdecode(self.encoded_img, -1) + elif msg_type == b"m": + minmax = struct.unpack(str(int(len(frame_data) / 4)) + "f", frame_data) + # Convert message to array. + minmax = np.asarray(minmax, dtype=np.float32) + # Store minmax vars in seperate array. + if len(self.point_cloud) > 0: + self.scale_vals[0] = minmax[0] + self.scale_vals[1] = minmax[1] self.r_lock.release() # Now let the feed_handler stream/save the frames @@ -123,6 +135,8 @@ def frame_grabber(self): def grab_regular(self): """ Returns the latest regular frame captured from the simulator + + :returns reg: The regular 2D color image from the SIM. """ self.r_lock.acquire() reg = self.reg_img.copy() @@ -139,12 +153,17 @@ def grab_depth(self): def grab_depth_data(self): """ Returns the depth matrix (in meters) ahead of the current rover + + :returns depth_data: An image containing depth data from the SIM. Close is black, far is near. """ self.r_lock.acquire() - # Convert depth data to numpy array - self.depth_data = np.asarray(self.depth_data) - # Resize current data (in list form) to matrix with expected dimensions - self.depth_data = self.depth_data.reshape((self.depth_res_y, self.depth_res_x, 1)) + # Check if we have actually recieved data from the network. + if len(self.depth_data) > 0: + # Convert depth data to numpy array + self.depth_data = np.asarray(self.depth_data) + # Resize current data (in list form) to matrix with expected dimensions + self.depth_data = self.depth_data.reshape((self.depth_res_y, self.depth_res_x, 1)) + depth_data = self.depth_data.copy() self.r_lock.release() return depth_data @@ -177,6 +196,27 @@ def close(self): def grab_point_cloud(self): """ Returns 3D point cloud data captured with simulator + + :returns point_cloud: A 4D array containing the point cloud from the SIM. """ - self.logger.error("Tried calling grab_point_cloud() for simulator! Not supported currently") - return None + self.r_lock.acquire() + point_cloud = self.point_cloud.copy() + scale_vals = self.scale_vals.copy() + self.r_lock.release() + # Check if we have actually recieved data from the network. + if len(point_cloud) > 0: + # Convert depth data to numpy array + point_cloud = np.asarray(point_cloud, dtype=np.int32) + # Add defualt RGBA value to the color channel of the image. + point_cloud[:, :, 3] = 111 + # Reorder the numbers to fit the zed's default coordinate system. (Webots is Z positive forward, X positive left, Y positive up) (Zed is X positive right, Y positive down, Z positive forward) + point_cloud[:, :, [0, 1, 2]] = point_cloud[:, :, [1, 2, 0]] + + # Rescale the point cloud. + point_cloud = np.interp( + point_cloud, + (point_cloud.min(), point_cloud.max()), + (scale_vals[0], scale_vals[1]), + ).astype(np.float32) + + return point_cloud diff --git a/core/vision/yolov5/.dockerignore b/core/vision/yolov5/.dockerignore new file mode 100644 index 00000000..af51ccc3 --- /dev/null +++ b/core/vision/yolov5/.dockerignore @@ -0,0 +1,222 @@ +# Repo-specific DockerIgnore ------------------------------------------------------------------------------------------- +#.git +.cache +.idea +runs +output +coco +storage.googleapis.com + +data/samples/* +**/results*.csv +*.jpg + +# Neural Network weights ----------------------------------------------------------------------------------------------- +**/*.pt +**/*.pth +**/*.onnx +**/*.engine +**/*.mlmodel +**/*.torchscript +**/*.torchscript.pt +**/*.tflite +**/*.h5 +**/*.pb +*_saved_model/ +*_web_model/ +*_openvino_model/ + +# Below Copied From .gitignore ----------------------------------------------------------------------------------------- +# Below Copied From .gitignore ----------------------------------------------------------------------------------------- + + +# GitHub Python GitIgnore ---------------------------------------------------------------------------------------------- +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +wandb/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# dotenv +.env + +# virtualenv +.venv* +venv*/ +ENV*/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + + +# https://github.com/github/gitignore/blob/master/Global/macOS.gitignore ----------------------------------------------- + +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon +Icon? + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + + +# https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff: +.idea/* +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/dictionaries +.html # Bokeh Plots +.pg # TensorFlow Frozen Graphs +.avi # videos + +# Sensitive or high-churn files: +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml + +# Gradle: +.idea/**/gradle.xml +.idea/**/libraries + +# CMake +cmake-build-debug/ +cmake-build-release/ + +# Mongo Explorer plugin: +.idea/**/mongoSettings.xml + +## File-based project format: +*.iws + +## Plugin-specific files: + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties diff --git a/core/vision/yolov5/.gitattributes b/core/vision/yolov5/.gitattributes new file mode 100644 index 00000000..dad4239e --- /dev/null +++ b/core/vision/yolov5/.gitattributes @@ -0,0 +1,2 @@ +# this drop notebooks from GitHub language stats +*.ipynb linguist-vendored diff --git a/core/vision/yolov5/.github/FUNDING.yml b/core/vision/yolov5/.github/FUNDING.yml new file mode 100644 index 00000000..3da386f7 --- /dev/null +++ b/core/vision/yolov5/.github/FUNDING.yml @@ -0,0 +1,5 @@ +# These are supported funding model platforms + +github: glenn-jocher +patreon: ultralytics +open_collective: ultralytics diff --git a/core/vision/yolov5/.github/ISSUE_TEMPLATE/bug-report.yml b/core/vision/yolov5/.github/ISSUE_TEMPLATE/bug-report.yml new file mode 100644 index 00000000..fcb64138 --- /dev/null +++ b/core/vision/yolov5/.github/ISSUE_TEMPLATE/bug-report.yml @@ -0,0 +1,85 @@ +name: 🐛 Bug Report +# title: " " +description: Problems with YOLOv5 +labels: [bug, triage] +body: + - type: markdown + attributes: + value: | + Thank you for submitting a YOLOv5 🐛 Bug Report! + + - type: checkboxes + attributes: + label: Search before asking + description: > + Please search the [issues](https://github.com/ultralytics/yolov5/issues) to see if a similar bug report already exists. + options: + - label: > + I have searched the YOLOv5 [issues](https://github.com/ultralytics/yolov5/issues) and found no similar bug report. + required: true + + - type: dropdown + attributes: + label: YOLOv5 Component + description: | + Please select the part of YOLOv5 where you found the bug. + multiple: true + options: + - "Training" + - "Validation" + - "Detection" + - "Export" + - "PyTorch Hub" + - "Multi-GPU" + - "Evolution" + - "Integrations" + - "Other" + validations: + required: false + + - type: textarea + attributes: + label: Bug + description: Provide console output with error messages and/or screenshots of the bug. + placeholder: | + 💡 ProTip! Include as much information as possible (screenshots, logs, tracebacks etc.) to receive the most helpful response. + validations: + required: true + + - type: textarea + attributes: + label: Environment + description: Please specify the software and hardware you used to produce the bug. + placeholder: | + - YOLO: YOLOv5 🚀 v6.0-67-g60e42e1 torch 1.9.0+cu111 CUDA:0 (A100-SXM4-40GB, 40536MiB) + - OS: Ubuntu 20.04 + - Python: 3.9.0 + validations: + required: false + + - type: textarea + attributes: + label: Minimal Reproducible Example + description: > + When asking a question, people will be better able to provide help if you provide code that they can easily understand and use to **reproduce** the problem. + This is referred to by community members as creating a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). + placeholder: | + ``` + # Code to reproduce your issue here + ``` + validations: + required: false + + - type: textarea + attributes: + label: Additional + description: Anything else you would like to share? + + - type: checkboxes + attributes: + label: Are you willing to submit a PR? + description: > + (Optional) We encourage you to submit a [Pull Request](https://github.com/ultralytics/yolov5/pulls) (PR) to help improve YOLOv5 for everyone, especially if you have a good understanding of how to implement a fix or feature. + See the YOLOv5 [Contributing Guide](https://github.com/ultralytics/yolov5/blob/master/CONTRIBUTING.md) to get started. + options: + - label: Yes I'd like to help by submitting a PR! diff --git a/core/vision/yolov5/.github/ISSUE_TEMPLATE/config.yml b/core/vision/yolov5/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 00000000..f388d7ba --- /dev/null +++ b/core/vision/yolov5/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,8 @@ +blank_issues_enabled: true +contact_links: + - name: Slack + url: https://join.slack.com/t/ultralytics/shared_invite/zt-w29ei8bp-jczz7QYUmDtgo6r6KcMIAg + about: Ask on Ultralytics Slack Forum + - name: Stack Overflow + url: https://stackoverflow.com/search?q=YOLOv5 + about: Ask on Stack Overflow with 'YOLOv5' tag diff --git a/core/vision/yolov5/.github/ISSUE_TEMPLATE/feature-request.yml b/core/vision/yolov5/.github/ISSUE_TEMPLATE/feature-request.yml new file mode 100644 index 00000000..68ef9851 --- /dev/null +++ b/core/vision/yolov5/.github/ISSUE_TEMPLATE/feature-request.yml @@ -0,0 +1,50 @@ +name: 🚀 Feature Request +description: Suggest a YOLOv5 idea +# title: " " +labels: [enhancement] +body: + - type: markdown + attributes: + value: | + Thank you for submitting a YOLOv5 🚀 Feature Request! + + - type: checkboxes + attributes: + label: Search before asking + description: > + Please search the [issues](https://github.com/ultralytics/yolov5/issues) to see if a similar feature request already exists. + options: + - label: > + I have searched the YOLOv5 [issues](https://github.com/ultralytics/yolov5/issues) and found no similar feature requests. + required: true + + - type: textarea + attributes: + label: Description + description: A short description of your feature. + placeholder: | + What new feature would you like to see in YOLOv5? + validations: + required: true + + - type: textarea + attributes: + label: Use case + description: | + Describe the use case of your feature request. It will help us understand and prioritize the feature request. + placeholder: | + How would this feature be used, and who would use it? + + - type: textarea + attributes: + label: Additional + description: Anything else you would like to share? + + - type: checkboxes + attributes: + label: Are you willing to submit a PR? + description: > + (Optional) We encourage you to submit a [Pull Request](https://github.com/ultralytics/yolov5/pulls) (PR) to help improve YOLOv5 for everyone, especially if you have a good understanding of how to implement a fix or feature. + See the YOLOv5 [Contributing Guide](https://github.com/ultralytics/yolov5/blob/master/CONTRIBUTING.md) to get started. + options: + - label: Yes I'd like to help by submitting a PR! diff --git a/core/vision/yolov5/.github/ISSUE_TEMPLATE/question.yml b/core/vision/yolov5/.github/ISSUE_TEMPLATE/question.yml new file mode 100644 index 00000000..8e0993c6 --- /dev/null +++ b/core/vision/yolov5/.github/ISSUE_TEMPLATE/question.yml @@ -0,0 +1,33 @@ +name: ❓ Question +description: Ask a YOLOv5 question +# title: " " +labels: [question] +body: + - type: markdown + attributes: + value: | + Thank you for asking a YOLOv5 ❓ Question! + + - type: checkboxes + attributes: + label: Search before asking + description: > + Please search the [issues](https://github.com/ultralytics/yolov5/issues) and [discussions](https://github.com/ultralytics/yolov5/discussions) to see if a similar question already exists. + options: + - label: > + I have searched the YOLOv5 [issues](https://github.com/ultralytics/yolov5/issues) and [discussions](https://github.com/ultralytics/yolov5/discussions) and found no similar questions. + required: true + + - type: textarea + attributes: + label: Question + description: What is your question? + placeholder: | + 💡 ProTip! Include as much information as possible (screenshots, logs, tracebacks etc.) to receive the most helpful response. + validations: + required: true + + - type: textarea + attributes: + label: Additional + description: Anything else you would like to share? diff --git a/core/vision/yolov5/.github/PULL_REQUEST_TEMPLATE.md b/core/vision/yolov5/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..f25b017a --- /dev/null +++ b/core/vision/yolov5/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,9 @@ + diff --git a/core/vision/yolov5/.github/SECURITY.md b/core/vision/yolov5/.github/SECURITY.md new file mode 100644 index 00000000..aa3e8409 --- /dev/null +++ b/core/vision/yolov5/.github/SECURITY.md @@ -0,0 +1,7 @@ +# Security Policy + +We aim to make YOLOv5 🚀 as secure as possible! If you find potential vulnerabilities or have any concerns please let us know so we can investigate and take corrective action if needed. + +### Reporting a Vulnerability + +To report vulnerabilities please email us at hello@ultralytics.com or visit https://ultralytics.com/contact. Thank you! diff --git a/core/vision/yolov5/.github/dependabot.yml b/core/vision/yolov5/.github/dependabot.yml new file mode 100644 index 00000000..c1b3d5d5 --- /dev/null +++ b/core/vision/yolov5/.github/dependabot.yml @@ -0,0 +1,23 @@ +version: 2 +updates: + - package-ecosystem: pip + directory: "/" + schedule: + interval: weekly + time: "04:00" + open-pull-requests-limit: 10 + reviewers: + - glenn-jocher + labels: + - dependencies + + - package-ecosystem: github-actions + directory: "/" + schedule: + interval: weekly + time: "04:00" + open-pull-requests-limit: 5 + reviewers: + - glenn-jocher + labels: + - dependencies diff --git a/core/vision/yolov5/.github/workflows/ci-testing.yml b/core/vision/yolov5/.github/workflows/ci-testing.yml new file mode 100644 index 00000000..f2096ce1 --- /dev/null +++ b/core/vision/yolov5/.github/workflows/ci-testing.yml @@ -0,0 +1,93 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +name: CI CPU testing + +on: # https://help.github.com/en/actions/reference/events-that-trigger-workflows + push: + branches: [ master ] + pull_request: + # The branches below must be a subset of the branches above + branches: [ master ] + schedule: + - cron: '0 0 * * *' # Runs at 00:00 UTC every day + +jobs: + cpu-tests: + + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ ubuntu-latest, macos-latest, windows-latest ] + python-version: [ 3.9 ] + model: [ 'yolov5n' ] # models to test + + # Timeout: https://stackoverflow.com/a/59076067/4521646 + timeout-minutes: 60 + steps: + - uses: actions/checkout@v3 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v3 + with: + python-version: ${{ matrix.python-version }} + + # Note: This uses an internal pip API and may not always work + # https://github.com/actions/cache/blob/master/examples.md#multiple-oss-in-a-workflow + - name: Get pip cache + id: pip-cache + run: | + python -c "from pip._internal.locations import USER_CACHE_DIR; print('::set-output name=dir::' + USER_CACHE_DIR)" + + - name: Cache pip + uses: actions/cache@v2.1.7 + with: + path: ${{ steps.pip-cache.outputs.dir }} + key: ${{ runner.os }}-${{ matrix.python-version }}-pip-${{ hashFiles('requirements.txt') }} + restore-keys: | + ${{ runner.os }}-${{ matrix.python-version }}-pip- + + # Known Keras 2.7.0 issue: https://github.com/ultralytics/yolov5/pull/5486 + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install -qr requirements.txt -f https://download.pytorch.org/whl/cpu/torch_stable.html + pip install -q onnx tensorflow-cpu keras==2.6.0 # wandb # extras + python --version + pip --version + pip list + shell: bash + + # - name: W&B login + # run: wandb login 345011b3fb26dc8337fd9b20e53857c1d403f2aa + + # - name: Download data + # run: | + # curl -L -o tmp.zip https://github.com/ultralytics/yolov5/releases/download/v1.0/coco128.zip + # unzip -q tmp.zip -d ../datasets + + - name: Tests workflow + run: | + # export PYTHONPATH="$PWD" # to run '$ python *.py' files in subdirectories + d=cpu # device + weights=runs/train/exp/weights/best.pt + + # Train + python train.py --img 64 --batch 32 --weights ${{ matrix.model }}.pt --cfg ${{ matrix.model }}.yaml --epochs 1 --device $d + # Val + python val.py --img 64 --batch 32 --weights ${{ matrix.model }}.pt --device $d + python val.py --img 64 --batch 32 --weights $weights --device $d + # Detect + python detect.py --weights ${{ matrix.model }}.pt --device $d + python detect.py --weights $weights --device $d + python hubconf.py # hub + # Export + python models/yolo.py --cfg ${{ matrix.model }}.yaml # build PyTorch model + python models/tf.py --weights ${{ matrix.model }}.pt # build TensorFlow model + python export.py --weights ${{ matrix.model }}.pt --img 64 --include torchscript onnx # export + # Python + python - <=3.7.0**](https://www.python.org/) with all [requirements.txt](https://github.com/ultralytics/yolov5/blob/master/requirements.txt) installed including [**PyTorch>=1.7**](https://pytorch.org/get-started/locally/). To get started: + ```bash + git clone https://github.com/ultralytics/yolov5 # clone + cd yolov5 + pip install -r requirements.txt # install + ``` + + ## Environments + + YOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including [CUDA](https://developer.nvidia.com/cuda)/[CUDNN](https://developer.nvidia.com/cudnn), [Python](https://www.python.org/) and [PyTorch](https://pytorch.org/) preinstalled): + + - **Google Colab and Kaggle** notebooks with free GPU: Open In Colab Open In Kaggle + - **Google Cloud** Deep Learning VM. See [GCP Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/GCP-Quickstart) + - **Amazon** Deep Learning AMI. See [AWS Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/AWS-Quickstart) + - **Docker Image**. See [Docker Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/Docker-Quickstart) Docker Pulls + + + ## Status + + CI CPU testing + + If this badge is green, all [YOLOv5 GitHub Actions](https://github.com/ultralytics/yolov5/actions) Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 training ([train.py](https://github.com/ultralytics/yolov5/blob/master/train.py)), validation ([val.py](https://github.com/ultralytics/yolov5/blob/master/val.py)), inference ([detect.py](https://github.com/ultralytics/yolov5/blob/master/detect.py)) and export ([export.py](https://github.com/ultralytics/yolov5/blob/master/export.py)) on MacOS, Windows, and Ubuntu every 24 hours and on every commit. diff --git a/core/vision/yolov5/.github/workflows/rebase.yml b/core/vision/yolov5/.github/workflows/rebase.yml new file mode 100644 index 00000000..75c57546 --- /dev/null +++ b/core/vision/yolov5/.github/workflows/rebase.yml @@ -0,0 +1,21 @@ +# https://github.com/marketplace/actions/automatic-rebase + +name: Automatic Rebase +on: + issue_comment: + types: [created] +jobs: + rebase: + name: Rebase + if: github.event.issue.pull_request != '' && contains(github.event.comment.body, '/rebase') + runs-on: ubuntu-latest + steps: + - name: Checkout the latest code + uses: actions/checkout@v3 + with: + token: ${{ secrets.ACTIONS_TOKEN }} + fetch-depth: 0 # otherwise, you will fail to push refs to dest repo + - name: Automatic Rebase + uses: cirrus-actions/rebase@1.5 + env: + GITHUB_TOKEN: ${{ secrets.ACTIONS_TOKEN }} diff --git a/core/vision/yolov5/.github/workflows/stale.yml b/core/vision/yolov5/.github/workflows/stale.yml new file mode 100644 index 00000000..7a83950c --- /dev/null +++ b/core/vision/yolov5/.github/workflows/stale.yml @@ -0,0 +1,38 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +name: Close stale issues +on: + schedule: + - cron: '0 0 * * *' # Runs at 00:00 UTC every day + +jobs: + stale: + runs-on: ubuntu-latest + steps: + - uses: actions/stale@v4 + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + stale-issue-message: | + 👋 Hello, this issue has been automatically marked as stale because it has not had recent activity. Please note it will be closed if no further activity occurs. + + Access additional [YOLOv5](https://ultralytics.com/yolov5) 🚀 resources: + - **Wiki** – https://github.com/ultralytics/yolov5/wiki + - **Tutorials** – https://github.com/ultralytics/yolov5#tutorials + - **Docs** – https://docs.ultralytics.com + + Access additional [Ultralytics](https://ultralytics.com) ⚡ resources: + - **Ultralytics HUB** – https://ultralytics.com/hub + - **Vision API** – https://ultralytics.com/yolov5 + - **About Us** – https://ultralytics.com/about + - **Join Our Team** – https://ultralytics.com/work + - **Contact Us** – https://ultralytics.com/contact + + Feel free to inform us of any other **issues** you discover or **feature requests** that come to mind in the future. Pull Requests (PRs) are also always welcomed! + + Thank you for your contributions to YOLOv5 🚀 and Vision AI ⭐! + + stale-pr-message: 'This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions YOLOv5 🚀 and Vision AI ⭐.' + days-before-stale: 30 + days-before-close: 5 + exempt-issue-labels: 'documentation,tutorial,TODO' + operations-per-run: 100 # The maximum number of operations per run, used to control rate limiting. diff --git a/core/vision/yolov5/.gitignore b/core/vision/yolov5/.gitignore new file mode 100644 index 00000000..69a00843 --- /dev/null +++ b/core/vision/yolov5/.gitignore @@ -0,0 +1,256 @@ +# Repo-specific GitIgnore ---------------------------------------------------------------------------------------------- +*.jpg +*.jpeg +*.png +*.bmp +*.tif +*.tiff +*.heic +*.JPG +*.JPEG +*.PNG +*.BMP +*.TIF +*.TIFF +*.HEIC +*.mp4 +*.mov +*.MOV +*.avi +*.data +*.json +*.cfg +!setup.cfg +!cfg/yolov3*.cfg + +storage.googleapis.com +runs/* +data/* +data/images/* +!data/*.yaml +!data/hyps +!data/scripts +!data/images +!data/images/zidane.jpg +!data/images/bus.jpg +!data/*.sh + +results*.csv + +# Datasets ------------------------------------------------------------------------------------------------------------- +coco/ +coco128/ +VOC/ + +# MATLAB GitIgnore ----------------------------------------------------------------------------------------------------- +*.m~ +*.mat +!targets*.mat + +# Neural Network weights ----------------------------------------------------------------------------------------------- +*.weights +*.pt +*.pb +*.onnx +*.engine +*.mlmodel +*.torchscript +*.tflite +*.h5 +*_saved_model/ +*_web_model/ +*_openvino_model/ +darknet53.conv.74 +yolov3-tiny.conv.15 + +# GitHub Python GitIgnore ---------------------------------------------------------------------------------------------- +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +/wandb/ +.installed.cfg +*.egg + + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# dotenv +.env + +# virtualenv +.venv* +venv*/ +ENV*/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + + +# https://github.com/github/gitignore/blob/master/Global/macOS.gitignore ----------------------------------------------- + +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon +Icon? + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + + +# https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff: +.idea/* +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/dictionaries +.html # Bokeh Plots +.pg # TensorFlow Frozen Graphs +.avi # videos + +# Sensitive or high-churn files: +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml + +# Gradle: +.idea/**/gradle.xml +.idea/**/libraries + +# CMake +cmake-build-debug/ +cmake-build-release/ + +# Mongo Explorer plugin: +.idea/**/mongoSettings.xml + +## File-based project format: +*.iws + +## Plugin-specific files: + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties diff --git a/core/vision/yolov5/.pre-commit-config.yaml b/core/vision/yolov5/.pre-commit-config.yaml new file mode 100644 index 00000000..526a5609 --- /dev/null +++ b/core/vision/yolov5/.pre-commit-config.yaml @@ -0,0 +1,66 @@ +# Define hooks for code formations +# Will be applied on any updated commit files if a user has installed and linked commit hook + +default_language_version: + python: python3.8 + +# Define bot property if installed via https://github.com/marketplace/pre-commit-ci +ci: + autofix_prs: true + autoupdate_commit_msg: '[pre-commit.ci] pre-commit suggestions' + autoupdate_schedule: quarterly + # submodules: true + +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.1.0 + hooks: + - id: end-of-file-fixer + - id: trailing-whitespace + - id: check-case-conflict + - id: check-yaml + - id: check-toml + - id: pretty-format-json + - id: check-docstring-first + + - repo: https://github.com/asottile/pyupgrade + rev: v2.31.0 + hooks: + - id: pyupgrade + args: [--py36-plus] + name: Upgrade code + + - repo: https://github.com/PyCQA/isort + rev: 5.10.1 + hooks: + - id: isort + name: Sort imports + + # TODO + #- repo: https://github.com/pre-commit/mirrors-yapf + # rev: v0.31.0 + # hooks: + # - id: yapf + # name: formatting + + # TODO + #- repo: https://github.com/executablebooks/mdformat + # rev: 0.7.7 + # hooks: + # - id: mdformat + # additional_dependencies: + # - mdformat-gfm + # - mdformat-black + # - mdformat_frontmatter + + # TODO + #- repo: https://github.com/asottile/yesqa + # rev: v1.2.3 + # hooks: + # - id: yesqa + + - repo: https://github.com/PyCQA/flake8 + rev: 4.0.1 + hooks: + - id: flake8 + name: PEP8 diff --git a/core/vision/yolov5/CONTRIBUTING.md b/core/vision/yolov5/CONTRIBUTING.md new file mode 100644 index 00000000..ebde03a5 --- /dev/null +++ b/core/vision/yolov5/CONTRIBUTING.md @@ -0,0 +1,94 @@ +## Contributing to YOLOv5 🚀 + +We love your input! We want to make contributing to YOLOv5 as easy and transparent as possible, whether it's: + +- Reporting a bug +- Discussing the current state of the code +- Submitting a fix +- Proposing a new feature +- Becoming a maintainer + +YOLOv5 works so well due to our combined community effort, and for every small improvement you contribute you will be +helping push the frontiers of what's possible in AI 😃! + +## Submitting a Pull Request (PR) 🛠️ + +Submitting a PR is easy! This example shows how to submit a PR for updating `requirements.txt` in 4 steps: + +### 1. Select File to Update + +Select `requirements.txt` to update by clicking on it in GitHub. +

PR_step1

+ +### 2. Click 'Edit this file' + +Button is in top-right corner. +

PR_step2

+ +### 3. Make Changes + +Change `matplotlib` version from `3.2.2` to `3.3`. +

PR_step3

+ +### 4. Preview Changes and Submit PR + +Click on the **Preview changes** tab to verify your updates. At the bottom of the screen select 'Create a **new branch** +for this commit', assign your branch a descriptive name such as `fix/matplotlib_version` and click the green **Propose +changes** button. All done, your PR is now submitted to YOLOv5 for review and approval 😃! +

PR_step4

+ +### PR recommendations + +To allow your work to be integrated as seamlessly as possible, we advise you to: + +- ✅ Verify your PR is **up-to-date with upstream/master.** If your PR is behind upstream/master an + automatic [GitHub Actions](https://github.com/ultralytics/yolov5/blob/master/.github/workflows/rebase.yml) merge may + be attempted by writing /rebase in a new comment, or by running the following code, replacing 'feature' with the name + of your local branch: + +```bash +git remote add upstream https://github.com/ultralytics/yolov5.git +git fetch upstream +# git checkout feature # <--- replace 'feature' with local branch name +git merge upstream/master +git push -u origin -f +``` + +- ✅ Verify all Continuous Integration (CI) **checks are passing**. +- ✅ Reduce changes to the absolute **minimum** required for your bug fix or feature addition. _"It is not daily increase + but daily decrease, hack away the unessential. The closer to the source, the less wastage there is."_ — Bruce Lee + +## Submitting a Bug Report 🐛 + +If you spot a problem with YOLOv5 please submit a Bug Report! + +For us to start investigating a possible problem we need to be able to reproduce it ourselves first. We've created a few +short guidelines below to help users provide what we need in order to get started. + +When asking a question, people will be better able to provide help if you provide **code** that they can easily +understand and use to **reproduce** the problem. This is referred to by community members as creating +a [minimum reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). Your code that reproduces +the problem should be: + +* ✅ **Minimal** – Use as little code as possible that still produces the same problem +* ✅ **Complete** – Provide **all** parts someone else needs to reproduce your problem in the question itself +* ✅ **Reproducible** – Test the code you're about to provide to make sure it reproduces the problem + +In addition to the above requirements, for [Ultralytics](https://ultralytics.com/) to provide assistance your code +should be: + +* ✅ **Current** – Verify that your code is up-to-date with current + GitHub [master](https://github.com/ultralytics/yolov5/tree/master), and if necessary `git pull` or `git clone` a new + copy to ensure your problem has not already been resolved by previous commits. +* ✅ **Unmodified** – Your problem must be reproducible without any modifications to the codebase in this + repository. [Ultralytics](https://ultralytics.com/) does not provide support for custom code ⚠️. + +If you believe your problem meets all of the above criteria, please close this issue and raise a new one using the 🐛 ** +Bug Report** [template](https://github.com/ultralytics/yolov5/issues/new/choose) and providing +a [minimum reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) to help us better +understand and diagnose your problem. + +## License + +By contributing, you agree that your contributions will be licensed under +the [GPL-3.0 license](https://choosealicense.com/licenses/gpl-3.0/) diff --git a/core/vision/yolov5/Dockerfile b/core/vision/yolov5/Dockerfile new file mode 100644 index 00000000..304e8b28 --- /dev/null +++ b/core/vision/yolov5/Dockerfile @@ -0,0 +1,65 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Start FROM Nvidia PyTorch image https://ngc.nvidia.com/catalog/containers/nvidia:pytorch +FROM nvcr.io/nvidia/pytorch:21.10-py3 + +# Install linux packages +RUN apt update && apt install -y zip htop screen libgl1-mesa-glx + +# Install python dependencies +COPY requirements.txt . +RUN python -m pip install --upgrade pip +RUN pip uninstall -y torch torchvision torchtext +RUN pip install --no-cache -r requirements.txt albumentations wandb gsutil notebook \ + torch==1.11.0+cu113 torchvision==0.12.0+cu113 -f https://download.pytorch.org/whl/cu113/torch_stable.html +# RUN pip install --no-cache -U torch torchvision + +# Create working directory +RUN mkdir -p /usr/src/app +WORKDIR /usr/src/app + +# Copy contents +RUN git clone https://github.com/ultralytics/yolov5 /usr/src/app +# COPY . /usr/src/app + +# Downloads to user config dir +ADD https://ultralytics.com/assets/Arial.ttf /root/.config/Ultralytics/ + +# Set environment variables +# ENV HOME=/usr/src/app + + +# Usage Examples ------------------------------------------------------------------------------------------------------- + +# Build and Push +# t=ultralytics/yolov5:latest && sudo docker build -t $t . && sudo docker push $t + +# Pull and Run +# t=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all $t + +# Pull and Run with local directory access +# t=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all -v "$(pwd)"/datasets:/usr/src/datasets $t + +# Kill all +# sudo docker kill $(sudo docker ps -q) + +# Kill all image-based +# sudo docker kill $(sudo docker ps -qa --filter ancestor=ultralytics/yolov5:latest) + +# Bash into running container +# sudo docker exec -it 5a9b5863d93d bash + +# Bash into stopped container +# id=$(sudo docker ps -qa) && sudo docker start $id && sudo docker exec -it $id bash + +# Clean up +# docker system prune -a --volumes + +# Update Ubuntu drivers +# https://www.maketecheasier.com/install-nvidia-drivers-ubuntu/ + +# DDP test +# python -m torch.distributed.run --nproc_per_node 2 --master_port 1 train.py --epochs 3 + +# GCP VM from Image +# docker.io/ultralytics/yolov5:latest diff --git a/core/vision/yolov5/LICENSE b/core/vision/yolov5/LICENSE new file mode 100644 index 00000000..92b370f0 --- /dev/null +++ b/core/vision/yolov5/LICENSE @@ -0,0 +1,674 @@ +GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/core/vision/yolov5/README.md b/core/vision/yolov5/README.md new file mode 100644 index 00000000..3ebc085b --- /dev/null +++ b/core/vision/yolov5/README.md @@ -0,0 +1,304 @@ +
+

+ + +

+
+
+ CI CPU testing + YOLOv5 Citation + Docker Pulls +
+ Open In Colab + Open In Kaggle + Join Forum +
+ +
+

+YOLOv5 🚀 is a family of object detection architectures and models pretrained on the COCO dataset, and represents Ultralytics + open-source research into future vision AI methods, incorporating lessons learned and best practices evolved over thousands of hours of research and development. +

+ + + + + +
+ +##
Documentation
+ +See the [YOLOv5 Docs](https://docs.ultralytics.com) for full documentation on training, testing and deployment. + +##
Quick Start Examples
+ +
+Install + +Clone repo and install [requirements.txt](https://github.com/ultralytics/yolov5/blob/master/requirements.txt) in a +[**Python>=3.7.0**](https://www.python.org/) environment, including +[**PyTorch>=1.7**](https://pytorch.org/get-started/locally/). + +```bash +git clone https://github.com/ultralytics/yolov5 # clone +cd yolov5 +pip install -r requirements.txt # install +``` + +
+ +
+Inference + +Inference with YOLOv5 and [PyTorch Hub](https://github.com/ultralytics/yolov5/issues/36) +. [Models](https://github.com/ultralytics/yolov5/tree/master/models) download automatically from the latest +YOLOv5 [release](https://github.com/ultralytics/yolov5/releases). + +```python +import torch + +# Model +model = torch.hub.load('ultralytics/yolov5', 'yolov5s') # or yolov5m, yolov5l, yolov5x, custom + +# Images +img = 'https://ultralytics.com/images/zidane.jpg' # or file, Path, PIL, OpenCV, numpy, list + +# Inference +results = model(img) + +# Results +results.print() # or .show(), .save(), .crop(), .pandas(), etc. +``` + +
+ + + +
+Inference with detect.py + +`detect.py` runs inference on a variety of sources, downloading [models](https://github.com/ultralytics/yolov5/tree/master/models) automatically from +the latest YOLOv5 [release](https://github.com/ultralytics/yolov5/releases) and saving results to `runs/detect`. + +```bash +python detect.py --source 0 # webcam + img.jpg # image + vid.mp4 # video + path/ # directory + path/*.jpg # glob + 'https://youtu.be/Zgi9g1ksQHc' # YouTube + 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream +``` + +
+ +
+Training + +The commands below reproduce YOLOv5 [COCO](https://github.com/ultralytics/yolov5/blob/master/data/scripts/get_coco.sh) +results. [Models](https://github.com/ultralytics/yolov5/tree/master/models) +and [datasets](https://github.com/ultralytics/yolov5/tree/master/data) download automatically from the latest +YOLOv5 [release](https://github.com/ultralytics/yolov5/releases). Training times for YOLOv5n/s/m/l/x are +1/2/4/6/8 days on a V100 GPU ([Multi-GPU](https://github.com/ultralytics/yolov5/issues/475) times faster). Use the +largest `--batch-size` possible, or pass `--batch-size -1` for +YOLOv5 [AutoBatch](https://github.com/ultralytics/yolov5/pull/5092). Batch sizes shown for V100-16GB. + +```bash +python train.py --data coco.yaml --cfg yolov5n.yaml --weights '' --batch-size 128 + yolov5s 64 + yolov5m 40 + yolov5l 24 + yolov5x 16 +``` + + + +
+ +
+Tutorials + +* [Train Custom Data](https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data)  🚀 RECOMMENDED +* [Tips for Best Training Results](https://github.com/ultralytics/yolov5/wiki/Tips-for-Best-Training-Results)  ☘️ + RECOMMENDED +* [Weights & Biases Logging](https://github.com/ultralytics/yolov5/issues/1289)  🌟 NEW +* [Roboflow for Datasets, Labeling, and Active Learning](https://github.com/ultralytics/yolov5/issues/4975)  🌟 NEW +* [Multi-GPU Training](https://github.com/ultralytics/yolov5/issues/475) +* [PyTorch Hub](https://github.com/ultralytics/yolov5/issues/36)  ⭐ NEW +* [TFLite, ONNX, CoreML, TensorRT Export](https://github.com/ultralytics/yolov5/issues/251) 🚀 +* [Test-Time Augmentation (TTA)](https://github.com/ultralytics/yolov5/issues/303) +* [Model Ensembling](https://github.com/ultralytics/yolov5/issues/318) +* [Model Pruning/Sparsity](https://github.com/ultralytics/yolov5/issues/304) +* [Hyperparameter Evolution](https://github.com/ultralytics/yolov5/issues/607) +* [Transfer Learning with Frozen Layers](https://github.com/ultralytics/yolov5/issues/1314)  ⭐ NEW +* [TensorRT Deployment](https://github.com/wang-xinyu/tensorrtx) + +
+ +##
Environments
+ +Get started in seconds with our verified environments. Click each icon below for details. + + + +##
Integrations
+ + + +|Weights and Biases|Roboflow ⭐ NEW| +|:-:|:-:| +|Automatically track and visualize all your YOLOv5 training runs in the cloud with [Weights & Biases](https://wandb.ai/site?utm_campaign=repo_yolo_readme)|Label and export your custom datasets directly to YOLOv5 for training with [Roboflow](https://roboflow.com/?ref=ultralytics) | + + + + +##
Why YOLOv5
+ +

+
+ YOLOv5-P5 640 Figure (click to expand) + +

+
+
+ Figure Notes (click to expand) + +* **COCO AP val** denotes mAP@0.5:0.95 metric measured on the 5000-image [COCO val2017](http://cocodataset.org) dataset over various inference sizes from 256 to 1536. +* **GPU Speed** measures average inference time per image on [COCO val2017](http://cocodataset.org) dataset using a [AWS p3.2xlarge](https://aws.amazon.com/ec2/instance-types/p3/) V100 instance at batch-size 32. +* **EfficientDet** data from [google/automl](https://github.com/google/automl) at batch size 8. +* **Reproduce** by `python val.py --task study --data coco.yaml --iou 0.7 --weights yolov5n6.pt yolov5s6.pt yolov5m6.pt yolov5l6.pt yolov5x6.pt` +
+ +### Pretrained Checkpoints + +[assets]: https://github.com/ultralytics/yolov5/releases + +[TTA]: https://github.com/ultralytics/yolov5/issues/303 + +|Model |size
(pixels) |mAPval
0.5:0.95 |mAPval
0.5 |Speed
CPU b1
(ms) |Speed
V100 b1
(ms) |Speed
V100 b32
(ms) |params
(M) |FLOPs
@640 (B) +|--- |--- |--- |--- |--- |--- |--- |--- |--- +|[YOLOv5n][assets] |640 |28.0 |45.7 |**45** |**6.3**|**0.6**|**1.9**|**4.5** +|[YOLOv5s][assets] |640 |37.4 |56.8 |98 |6.4 |0.9 |7.2 |16.5 +|[YOLOv5m][assets] |640 |45.4 |64.1 |224 |8.2 |1.7 |21.2 |49.0 +|[YOLOv5l][assets] |640 |49.0 |67.3 |430 |10.1 |2.7 |46.5 |109.1 +|[YOLOv5x][assets] |640 |50.7 |68.9 |766 |12.1 |4.8 |86.7 |205.7 +| | | | | | | | | +|[YOLOv5n6][assets] |1280 |36.0 |54.4 |153 |8.1 |2.1 |3.2 |4.6 +|[YOLOv5s6][assets] |1280 |44.8 |63.7 |385 |8.2 |3.6 |12.6 |16.8 +|[YOLOv5m6][assets] |1280 |51.3 |69.3 |887 |11.1 |6.8 |35.7 |50.0 +|[YOLOv5l6][assets] |1280 |53.7 |71.3 |1784 |15.8 |10.5 |76.8 |111.4 +|[YOLOv5x6][assets]
+ [TTA][TTA]|1280
1536 |55.0
**55.8** |72.7
**72.7** |3136
- |26.2
- |19.4
- |140.7
- |209.8
- + +
+ Table Notes (click to expand) + +* All checkpoints are trained to 300 epochs with default settings. Nano and Small models use [hyp.scratch-low.yaml](https://github.com/ultralytics/yolov5/blob/master/data/hyps/hyp.scratch-low.yaml) hyps, all others use [hyp.scratch-high.yaml](https://github.com/ultralytics/yolov5/blob/master/data/hyps/hyp.scratch-high.yaml). +* **mAPval** values are for single-model single-scale on [COCO val2017](http://cocodataset.org) dataset.
Reproduce by `python val.py --data coco.yaml --img 640 --conf 0.001 --iou 0.65` +* **Speed** averaged over COCO val images using a [AWS p3.2xlarge](https://aws.amazon.com/ec2/instance-types/p3/) instance. NMS times (~1 ms/img) not included.
Reproduce by `python val.py --data coco.yaml --img 640 --task speed --batch 1` +* **TTA** [Test Time Augmentation](https://github.com/ultralytics/yolov5/issues/303) includes reflection and scale augmentations.
Reproduce by `python val.py --data coco.yaml --img 1536 --iou 0.7 --augment` + +
+ +##
Contribute
+ +We love your input! We want to make contributing to YOLOv5 as easy and transparent as possible. Please see our [Contributing Guide](CONTRIBUTING.md) to get started, and fill out the [YOLOv5 Survey](https://ultralytics.com/survey?utm_source=github&utm_medium=social&utm_campaign=Survey) to send us feedback on your experiences. Thank you to all our contributors! + + + +##
Contact
+ +For YOLOv5 bugs and feature requests please visit [GitHub Issues](https://github.com/ultralytics/yolov5/issues). For business inquiries or +professional support requests please visit [https://ultralytics.com/contact](https://ultralytics.com/contact). + +
+ + diff --git a/core/vision/yolov5/__init__.py b/core/vision/yolov5/__init__.py new file mode 100644 index 00000000..ec4dd0ab --- /dev/null +++ b/core/vision/yolov5/__init__.py @@ -0,0 +1,2 @@ +import core.vision.yolov5.utils as utils +import core.vision.yolov5.models as models diff --git a/core/vision/yolov5/data/Argoverse.yaml b/core/vision/yolov5/data/Argoverse.yaml new file mode 100644 index 00000000..312791b3 --- /dev/null +++ b/core/vision/yolov5/data/Argoverse.yaml @@ -0,0 +1,67 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# Argoverse-HD dataset (ring-front-center camera) http://www.cs.cmu.edu/~mengtial/proj/streaming/ by Argo AI +# Example usage: python train.py --data Argoverse.yaml +# parent +# ├── yolov5 +# └── datasets +# └── Argoverse ← downloads here + + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: ../datasets/Argoverse # dataset root dir +train: Argoverse-1.1/images/train/ # train images (relative to 'path') 39384 images +val: Argoverse-1.1/images/val/ # val images (relative to 'path') 15062 images +test: Argoverse-1.1/images/test/ # test images (optional) https://eval.ai/web/challenges/challenge-page/800/overview + +# Classes +nc: 8 # number of classes +names: ['person', 'bicycle', 'car', 'motorcycle', 'bus', 'truck', 'traffic_light', 'stop_sign'] # class names + + +# Download script/URL (optional) --------------------------------------------------------------------------------------- +download: | + import json + + from tqdm import tqdm + from utils.general import download, Path + + + def argoverse2yolo(set): + labels = {} + a = json.load(open(set, "rb")) + for annot in tqdm(a['annotations'], desc=f"Converting {set} to YOLOv5 format..."): + img_id = annot['image_id'] + img_name = a['images'][img_id]['name'] + img_label_name = img_name[:-3] + "txt" + + cls = annot['category_id'] # instance class id + x_center, y_center, width, height = annot['bbox'] + x_center = (x_center + width / 2) / 1920.0 # offset and scale + y_center = (y_center + height / 2) / 1200.0 # offset and scale + width /= 1920.0 # scale + height /= 1200.0 # scale + + img_dir = set.parents[2] / 'Argoverse-1.1' / 'labels' / a['seq_dirs'][a['images'][annot['image_id']]['sid']] + if not img_dir.exists(): + img_dir.mkdir(parents=True, exist_ok=True) + + k = str(img_dir / img_label_name) + if k not in labels: + labels[k] = [] + labels[k].append(f"{cls} {x_center} {y_center} {width} {height}\n") + + for k in labels: + with open(k, "w") as f: + f.writelines(labels[k]) + + + # Download + dir = Path('../datasets/Argoverse') # dataset root dir + urls = ['https://argoverse-hd.s3.us-east-2.amazonaws.com/Argoverse-HD-Full.zip'] + download(urls, dir=dir, delete=False) + + # Convert + annotations_dir = 'Argoverse-HD/annotations/' + (dir / 'Argoverse-1.1' / 'tracking').rename(dir / 'Argoverse-1.1' / 'images') # rename 'tracking' to 'images' + for d in "train.json", "val.json": + argoverse2yolo(dir / annotations_dir / d) # convert VisDrone annotations to YOLO labels diff --git a/core/vision/yolov5/data/GlobalWheat2020.yaml b/core/vision/yolov5/data/GlobalWheat2020.yaml new file mode 100644 index 00000000..869dace0 --- /dev/null +++ b/core/vision/yolov5/data/GlobalWheat2020.yaml @@ -0,0 +1,53 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# Global Wheat 2020 dataset http://www.global-wheat.com/ by University of Saskatchewan +# Example usage: python train.py --data GlobalWheat2020.yaml +# parent +# ├── yolov5 +# └── datasets +# └── GlobalWheat2020 ← downloads here + + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: ../datasets/GlobalWheat2020 # dataset root dir +train: # train images (relative to 'path') 3422 images + - images/arvalis_1 + - images/arvalis_2 + - images/arvalis_3 + - images/ethz_1 + - images/rres_1 + - images/inrae_1 + - images/usask_1 +val: # val images (relative to 'path') 748 images (WARNING: train set contains ethz_1) + - images/ethz_1 +test: # test images (optional) 1276 images + - images/utokyo_1 + - images/utokyo_2 + - images/nau_1 + - images/uq_1 + +# Classes +nc: 1 # number of classes +names: ['wheat_head'] # class names + + +# Download script/URL (optional) --------------------------------------------------------------------------------------- +download: | + from utils.general import download, Path + + # Download + dir = Path(yaml['path']) # dataset root dir + urls = ['https://zenodo.org/record/4298502/files/global-wheat-codalab-official.zip', + 'https://github.com/ultralytics/yolov5/releases/download/v1.0/GlobalWheat2020_labels.zip'] + download(urls, dir=dir) + + # Make Directories + for p in 'annotations', 'images', 'labels': + (dir / p).mkdir(parents=True, exist_ok=True) + + # Move + for p in 'arvalis_1', 'arvalis_2', 'arvalis_3', 'ethz_1', 'rres_1', 'inrae_1', 'usask_1', \ + 'utokyo_1', 'utokyo_2', 'nau_1', 'uq_1': + (dir / p).rename(dir / 'images' / p) # move to /images + f = (dir / p).with_suffix('.json') # json file + if f.exists(): + f.rename((dir / 'annotations' / p).with_suffix('.json')) # move to /annotations diff --git a/core/vision/yolov5/data/Objects365.yaml b/core/vision/yolov5/data/Objects365.yaml new file mode 100644 index 00000000..4c7cf3fd --- /dev/null +++ b/core/vision/yolov5/data/Objects365.yaml @@ -0,0 +1,112 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# Objects365 dataset https://www.objects365.org/ by Megvii +# Example usage: python train.py --data Objects365.yaml +# parent +# ├── yolov5 +# └── datasets +# └── Objects365 ← downloads here + + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: ../datasets/Objects365 # dataset root dir +train: images/train # train images (relative to 'path') 1742289 images +val: images/val # val images (relative to 'path') 80000 images +test: # test images (optional) + +# Classes +nc: 365 # number of classes +names: ['Person', 'Sneakers', 'Chair', 'Other Shoes', 'Hat', 'Car', 'Lamp', 'Glasses', 'Bottle', 'Desk', 'Cup', + 'Street Lights', 'Cabinet/shelf', 'Handbag/Satchel', 'Bracelet', 'Plate', 'Picture/Frame', 'Helmet', 'Book', + 'Gloves', 'Storage box', 'Boat', 'Leather Shoes', 'Flower', 'Bench', 'Potted Plant', 'Bowl/Basin', 'Flag', + 'Pillow', 'Boots', 'Vase', 'Microphone', 'Necklace', 'Ring', 'SUV', 'Wine Glass', 'Belt', 'Monitor/TV', + 'Backpack', 'Umbrella', 'Traffic Light', 'Speaker', 'Watch', 'Tie', 'Trash bin Can', 'Slippers', 'Bicycle', + 'Stool', 'Barrel/bucket', 'Van', 'Couch', 'Sandals', 'Basket', 'Drum', 'Pen/Pencil', 'Bus', 'Wild Bird', + 'High Heels', 'Motorcycle', 'Guitar', 'Carpet', 'Cell Phone', 'Bread', 'Camera', 'Canned', 'Truck', + 'Traffic cone', 'Cymbal', 'Lifesaver', 'Towel', 'Stuffed Toy', 'Candle', 'Sailboat', 'Laptop', 'Awning', + 'Bed', 'Faucet', 'Tent', 'Horse', 'Mirror', 'Power outlet', 'Sink', 'Apple', 'Air Conditioner', 'Knife', + 'Hockey Stick', 'Paddle', 'Pickup Truck', 'Fork', 'Traffic Sign', 'Balloon', 'Tripod', 'Dog', 'Spoon', 'Clock', + 'Pot', 'Cow', 'Cake', 'Dinning Table', 'Sheep', 'Hanger', 'Blackboard/Whiteboard', 'Napkin', 'Other Fish', + 'Orange/Tangerine', 'Toiletry', 'Keyboard', 'Tomato', 'Lantern', 'Machinery Vehicle', 'Fan', + 'Green Vegetables', 'Banana', 'Baseball Glove', 'Airplane', 'Mouse', 'Train', 'Pumpkin', 'Soccer', 'Skiboard', + 'Luggage', 'Nightstand', 'Tea pot', 'Telephone', 'Trolley', 'Head Phone', 'Sports Car', 'Stop Sign', + 'Dessert', 'Scooter', 'Stroller', 'Crane', 'Remote', 'Refrigerator', 'Oven', 'Lemon', 'Duck', 'Baseball Bat', + 'Surveillance Camera', 'Cat', 'Jug', 'Broccoli', 'Piano', 'Pizza', 'Elephant', 'Skateboard', 'Surfboard', + 'Gun', 'Skating and Skiing shoes', 'Gas stove', 'Donut', 'Bow Tie', 'Carrot', 'Toilet', 'Kite', 'Strawberry', + 'Other Balls', 'Shovel', 'Pepper', 'Computer Box', 'Toilet Paper', 'Cleaning Products', 'Chopsticks', + 'Microwave', 'Pigeon', 'Baseball', 'Cutting/chopping Board', 'Coffee Table', 'Side Table', 'Scissors', + 'Marker', 'Pie', 'Ladder', 'Snowboard', 'Cookies', 'Radiator', 'Fire Hydrant', 'Basketball', 'Zebra', 'Grape', + 'Giraffe', 'Potato', 'Sausage', 'Tricycle', 'Violin', 'Egg', 'Fire Extinguisher', 'Candy', 'Fire Truck', + 'Billiards', 'Converter', 'Bathtub', 'Wheelchair', 'Golf Club', 'Briefcase', 'Cucumber', 'Cigar/Cigarette', + 'Paint Brush', 'Pear', 'Heavy Truck', 'Hamburger', 'Extractor', 'Extension Cord', 'Tong', 'Tennis Racket', + 'Folder', 'American Football', 'earphone', 'Mask', 'Kettle', 'Tennis', 'Ship', 'Swing', 'Coffee Machine', + 'Slide', 'Carriage', 'Onion', 'Green beans', 'Projector', 'Frisbee', 'Washing Machine/Drying Machine', + 'Chicken', 'Printer', 'Watermelon', 'Saxophone', 'Tissue', 'Toothbrush', 'Ice cream', 'Hot-air balloon', + 'Cello', 'French Fries', 'Scale', 'Trophy', 'Cabbage', 'Hot dog', 'Blender', 'Peach', 'Rice', 'Wallet/Purse', + 'Volleyball', 'Deer', 'Goose', 'Tape', 'Tablet', 'Cosmetics', 'Trumpet', 'Pineapple', 'Golf Ball', + 'Ambulance', 'Parking meter', 'Mango', 'Key', 'Hurdle', 'Fishing Rod', 'Medal', 'Flute', 'Brush', 'Penguin', + 'Megaphone', 'Corn', 'Lettuce', 'Garlic', 'Swan', 'Helicopter', 'Green Onion', 'Sandwich', 'Nuts', + 'Speed Limit Sign', 'Induction Cooker', 'Broom', 'Trombone', 'Plum', 'Rickshaw', 'Goldfish', 'Kiwi fruit', + 'Router/modem', 'Poker Card', 'Toaster', 'Shrimp', 'Sushi', 'Cheese', 'Notepaper', 'Cherry', 'Pliers', 'CD', + 'Pasta', 'Hammer', 'Cue', 'Avocado', 'Hamimelon', 'Flask', 'Mushroom', 'Screwdriver', 'Soap', 'Recorder', + 'Bear', 'Eggplant', 'Board Eraser', 'Coconut', 'Tape Measure/Ruler', 'Pig', 'Showerhead', 'Globe', 'Chips', + 'Steak', 'Crosswalk Sign', 'Stapler', 'Camel', 'Formula 1', 'Pomegranate', 'Dishwasher', 'Crab', + 'Hoverboard', 'Meat ball', 'Rice Cooker', 'Tuba', 'Calculator', 'Papaya', 'Antelope', 'Parrot', 'Seal', + 'Butterfly', 'Dumbbell', 'Donkey', 'Lion', 'Urinal', 'Dolphin', 'Electric Drill', 'Hair Dryer', 'Egg tart', + 'Jellyfish', 'Treadmill', 'Lighter', 'Grapefruit', 'Game board', 'Mop', 'Radish', 'Baozi', 'Target', 'French', + 'Spring Rolls', 'Monkey', 'Rabbit', 'Pencil Case', 'Yak', 'Red Cabbage', 'Binoculars', 'Asparagus', 'Barbell', + 'Scallop', 'Noddles', 'Comb', 'Dumpling', 'Oyster', 'Table Tennis paddle', 'Cosmetics Brush/Eyeliner Pencil', + 'Chainsaw', 'Eraser', 'Lobster', 'Durian', 'Okra', 'Lipstick', 'Cosmetics Mirror', 'Curling', 'Table Tennis'] + + +# Download script/URL (optional) --------------------------------------------------------------------------------------- +download: | + from pycocotools.coco import COCO + from tqdm import tqdm + + from utils.general import Path, download, np, xyxy2xywhn + + # Make Directories + dir = Path(yaml['path']) # dataset root dir + for p in 'images', 'labels': + (dir / p).mkdir(parents=True, exist_ok=True) + for q in 'train', 'val': + (dir / p / q).mkdir(parents=True, exist_ok=True) + + # Train, Val Splits + for split, patches in [('train', 50 + 1), ('val', 43 + 1)]: + print(f"Processing {split} in {patches} patches ...") + images, labels = dir / 'images' / split, dir / 'labels' / split + + # Download + url = f"https://dorc.ks3-cn-beijing.ksyun.com/data-set/2020Objects365%E6%95%B0%E6%8D%AE%E9%9B%86/{split}/" + if split == 'train': + download([f'{url}zhiyuan_objv2_{split}.tar.gz'], dir=dir, delete=False) # annotations json + download([f'{url}patch{i}.tar.gz' for i in range(patches)], dir=images, curl=True, delete=False, threads=8) + elif split == 'val': + download([f'{url}zhiyuan_objv2_{split}.json'], dir=dir, delete=False) # annotations json + download([f'{url}images/v1/patch{i}.tar.gz' for i in range(15 + 1)], dir=images, curl=True, delete=False, threads=8) + download([f'{url}images/v2/patch{i}.tar.gz' for i in range(16, patches)], dir=images, curl=True, delete=False, threads=8) + + # Move + for f in tqdm(images.rglob('*.jpg'), desc=f'Moving {split} images'): + f.rename(images / f.name) # move to /images/{split} + + # Labels + coco = COCO(dir / f'zhiyuan_objv2_{split}.json') + names = [x["name"] for x in coco.loadCats(coco.getCatIds())] + for cid, cat in enumerate(names): + catIds = coco.getCatIds(catNms=[cat]) + imgIds = coco.getImgIds(catIds=catIds) + for im in tqdm(coco.loadImgs(imgIds), desc=f'Class {cid + 1}/{len(names)} {cat}'): + width, height = im["width"], im["height"] + path = Path(im["file_name"]) # image filename + try: + with open(labels / path.with_suffix('.txt').name, 'a') as file: + annIds = coco.getAnnIds(imgIds=im["id"], catIds=catIds, iscrowd=None) + for a in coco.loadAnns(annIds): + x, y, w, h = a['bbox'] # bounding box in xywh (xy top-left corner) + xyxy = np.array([x, y, x + w, y + h])[None] # pixels(1,4) + x, y, w, h = xyxy2xywhn(xyxy, w=width, h=height, clip=True)[0] # normalized and clipped + file.write(f"{cid} {x:.5f} {y:.5f} {w:.5f} {h:.5f}\n") + except Exception as e: + print(e) diff --git a/core/vision/yolov5/data/SKU-110K.yaml b/core/vision/yolov5/data/SKU-110K.yaml new file mode 100644 index 00000000..9481b7a0 --- /dev/null +++ b/core/vision/yolov5/data/SKU-110K.yaml @@ -0,0 +1,52 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# SKU-110K retail items dataset https://github.com/eg4000/SKU110K_CVPR19 by Trax Retail +# Example usage: python train.py --data SKU-110K.yaml +# parent +# ├── yolov5 +# └── datasets +# └── SKU-110K ← downloads here + + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: ../datasets/SKU-110K # dataset root dir +train: train.txt # train images (relative to 'path') 8219 images +val: val.txt # val images (relative to 'path') 588 images +test: test.txt # test images (optional) 2936 images + +# Classes +nc: 1 # number of classes +names: ['object'] # class names + + +# Download script/URL (optional) --------------------------------------------------------------------------------------- +download: | + import shutil + from tqdm import tqdm + from utils.general import np, pd, Path, download, xyxy2xywh + + # Download + dir = Path(yaml['path']) # dataset root dir + parent = Path(dir.parent) # download dir + urls = ['http://trax-geometry.s3.amazonaws.com/cvpr_challenge/SKU110K_fixed.tar.gz'] + download(urls, dir=parent, delete=False) + + # Rename directories + if dir.exists(): + shutil.rmtree(dir) + (parent / 'SKU110K_fixed').rename(dir) # rename dir + (dir / 'labels').mkdir(parents=True, exist_ok=True) # create labels dir + + # Convert labels + names = 'image', 'x1', 'y1', 'x2', 'y2', 'class', 'image_width', 'image_height' # column names + for d in 'annotations_train.csv', 'annotations_val.csv', 'annotations_test.csv': + x = pd.read_csv(dir / 'annotations' / d, names=names).values # annotations + images, unique_images = x[:, 0], np.unique(x[:, 0]) + with open((dir / d).with_suffix('.txt').__str__().replace('annotations_', ''), 'w') as f: + f.writelines(f'./images/{s}\n' for s in unique_images) + for im in tqdm(unique_images, desc=f'Converting {dir / d}'): + cls = 0 # single-class dataset + with open((dir / 'labels' / im).with_suffix('.txt'), 'a') as f: + for r in x[images == im]: + w, h = r[6], r[7] # image width, height + xywh = xyxy2xywh(np.array([[r[1] / w, r[2] / h, r[3] / w, r[4] / h]]))[0] # instance + f.write(f"{cls} {xywh[0]:.5f} {xywh[1]:.5f} {xywh[2]:.5f} {xywh[3]:.5f}\n") # write label diff --git a/core/vision/yolov5/data/VOC.yaml b/core/vision/yolov5/data/VOC.yaml new file mode 100644 index 00000000..975d5646 --- /dev/null +++ b/core/vision/yolov5/data/VOC.yaml @@ -0,0 +1,80 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# PASCAL VOC dataset http://host.robots.ox.ac.uk/pascal/VOC by University of Oxford +# Example usage: python train.py --data VOC.yaml +# parent +# ├── yolov5 +# └── datasets +# └── VOC ← downloads here + + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: ../datasets/VOC +train: # train images (relative to 'path') 16551 images + - images/train2012 + - images/train2007 + - images/val2012 + - images/val2007 +val: # val images (relative to 'path') 4952 images + - images/test2007 +test: # test images (optional) + - images/test2007 + +# Classes +nc: 20 # number of classes +names: ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', + 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor'] # class names + + +# Download script/URL (optional) --------------------------------------------------------------------------------------- +download: | + import xml.etree.ElementTree as ET + + from tqdm import tqdm + from utils.general import download, Path + + + def convert_label(path, lb_path, year, image_id): + def convert_box(size, box): + dw, dh = 1. / size[0], 1. / size[1] + x, y, w, h = (box[0] + box[1]) / 2.0 - 1, (box[2] + box[3]) / 2.0 - 1, box[1] - box[0], box[3] - box[2] + return x * dw, y * dh, w * dw, h * dh + + in_file = open(path / f'VOC{year}/Annotations/{image_id}.xml') + out_file = open(lb_path, 'w') + tree = ET.parse(in_file) + root = tree.getroot() + size = root.find('size') + w = int(size.find('width').text) + h = int(size.find('height').text) + + for obj in root.iter('object'): + cls = obj.find('name').text + if cls in yaml['names'] and not int(obj.find('difficult').text) == 1: + xmlbox = obj.find('bndbox') + bb = convert_box((w, h), [float(xmlbox.find(x).text) for x in ('xmin', 'xmax', 'ymin', 'ymax')]) + cls_id = yaml['names'].index(cls) # class id + out_file.write(" ".join([str(a) for a in (cls_id, *bb)]) + '\n') + + + # Download + dir = Path(yaml['path']) # dataset root dir + url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/' + urls = [url + 'VOCtrainval_06-Nov-2007.zip', # 446MB, 5012 images + url + 'VOCtest_06-Nov-2007.zip', # 438MB, 4953 images + url + 'VOCtrainval_11-May-2012.zip'] # 1.95GB, 17126 images + download(urls, dir=dir / 'images', delete=False) + + # Convert + path = dir / f'images/VOCdevkit' + for year, image_set in ('2012', 'train'), ('2012', 'val'), ('2007', 'train'), ('2007', 'val'), ('2007', 'test'): + imgs_path = dir / 'images' / f'{image_set}{year}' + lbs_path = dir / 'labels' / f'{image_set}{year}' + imgs_path.mkdir(exist_ok=True, parents=True) + lbs_path.mkdir(exist_ok=True, parents=True) + + image_ids = open(path / f'VOC{year}/ImageSets/Main/{image_set}.txt').read().strip().split() + for id in tqdm(image_ids, desc=f'{image_set}{year}'): + f = path / f'VOC{year}/JPEGImages/{id}.jpg' # old img path + lb_path = (lbs_path / f.name).with_suffix('.txt') # new label path + f.rename(imgs_path / f.name) # move image + convert_label(path, lb_path, year, id) # convert labels to YOLO format diff --git a/core/vision/yolov5/data/VisDrone.yaml b/core/vision/yolov5/data/VisDrone.yaml new file mode 100644 index 00000000..83a5c7d5 --- /dev/null +++ b/core/vision/yolov5/data/VisDrone.yaml @@ -0,0 +1,61 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# VisDrone2019-DET dataset https://github.com/VisDrone/VisDrone-Dataset by Tianjin University +# Example usage: python train.py --data VisDrone.yaml +# parent +# ├── yolov5 +# └── datasets +# └── VisDrone ← downloads here + + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: ../datasets/VisDrone # dataset root dir +train: VisDrone2019-DET-train/images # train images (relative to 'path') 6471 images +val: VisDrone2019-DET-val/images # val images (relative to 'path') 548 images +test: VisDrone2019-DET-test-dev/images # test images (optional) 1610 images + +# Classes +nc: 10 # number of classes +names: ['pedestrian', 'people', 'bicycle', 'car', 'van', 'truck', 'tricycle', 'awning-tricycle', 'bus', 'motor'] + + +# Download script/URL (optional) --------------------------------------------------------------------------------------- +download: | + from utils.general import download, os, Path + + def visdrone2yolo(dir): + from PIL import Image + from tqdm import tqdm + + def convert_box(size, box): + # Convert VisDrone box to YOLO xywh box + dw = 1. / size[0] + dh = 1. / size[1] + return (box[0] + box[2] / 2) * dw, (box[1] + box[3] / 2) * dh, box[2] * dw, box[3] * dh + + (dir / 'labels').mkdir(parents=True, exist_ok=True) # make labels directory + pbar = tqdm((dir / 'annotations').glob('*.txt'), desc=f'Converting {dir}') + for f in pbar: + img_size = Image.open((dir / 'images' / f.name).with_suffix('.jpg')).size + lines = [] + with open(f, 'r') as file: # read annotation.txt + for row in [x.split(',') for x in file.read().strip().splitlines()]: + if row[4] == '0': # VisDrone 'ignored regions' class 0 + continue + cls = int(row[5]) - 1 + box = convert_box(img_size, tuple(map(int, row[:4]))) + lines.append(f"{cls} {' '.join(f'{x:.6f}' for x in box)}\n") + with open(str(f).replace(os.sep + 'annotations' + os.sep, os.sep + 'labels' + os.sep), 'w') as fl: + fl.writelines(lines) # write label.txt + + + # Download + dir = Path(yaml['path']) # dataset root dir + urls = ['https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-train.zip', + 'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-val.zip', + 'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-dev.zip', + 'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-challenge.zip'] + download(urls, dir=dir) + + # Convert + for d in 'VisDrone2019-DET-train', 'VisDrone2019-DET-val', 'VisDrone2019-DET-test-dev': + visdrone2yolo(dir / d) # convert VisDrone annotations to YOLO labels diff --git a/core/vision/yolov5/data/coco.yaml b/core/vision/yolov5/data/coco.yaml new file mode 100644 index 00000000..3ed7e48a --- /dev/null +++ b/core/vision/yolov5/data/coco.yaml @@ -0,0 +1,44 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# COCO 2017 dataset http://cocodataset.org by Microsoft +# Example usage: python train.py --data coco.yaml +# parent +# ├── yolov5 +# └── datasets +# └── coco ← downloads here + + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: ../datasets/coco # dataset root dir +train: train2017.txt # train images (relative to 'path') 118287 images +val: val2017.txt # val images (relative to 'path') 5000 images +test: test-dev2017.txt # 20288 of 40670 images, submit to https://competitions.codalab.org/competitions/20794 + +# Classes +nc: 80 # number of classes +names: ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', + 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', + 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', + 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', + 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', + 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', + 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', + 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', + 'hair drier', 'toothbrush'] # class names + + +# Download script/URL (optional) +download: | + from utils.general import download, Path + + # Download labels + segments = False # segment or box labels + dir = Path(yaml['path']) # dataset root dir + url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/' + urls = [url + ('coco2017labels-segments.zip' if segments else 'coco2017labels.zip')] # labels + download(urls, dir=dir.parent) + + # Download data + urls = ['http://images.cocodataset.org/zips/train2017.zip', # 19G, 118k images + 'http://images.cocodataset.org/zips/val2017.zip', # 1G, 5k images + 'http://images.cocodataset.org/zips/test2017.zip'] # 7G, 41k images (optional) + download(urls, dir=dir / 'images', threads=3) diff --git a/core/vision/yolov5/data/coco128.yaml b/core/vision/yolov5/data/coco128.yaml new file mode 100644 index 00000000..d07c7044 --- /dev/null +++ b/core/vision/yolov5/data/coco128.yaml @@ -0,0 +1,30 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# COCO128 dataset https://www.kaggle.com/ultralytics/coco128 (first 128 images from COCO train2017) by Ultralytics +# Example usage: python train.py --data coco128.yaml +# parent +# ├── yolov5 +# └── datasets +# └── coco128 ← downloads here + + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: ../datasets/coco128 # dataset root dir +train: images/train2017 # train images (relative to 'path') 128 images +val: images/train2017 # val images (relative to 'path') 128 images +test: # test images (optional) + +# Classes +nc: 80 # number of classes +names: ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', + 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', + 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', + 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', + 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', + 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', + 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', + 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', + 'hair drier', 'toothbrush'] # class names + + +# Download script/URL (optional) +download: https://ultralytics.com/assets/coco128.zip diff --git a/core/vision/yolov5/data/hyps/hyp.Objects365.yaml b/core/vision/yolov5/data/hyps/hyp.Objects365.yaml new file mode 100644 index 00000000..74971740 --- /dev/null +++ b/core/vision/yolov5/data/hyps/hyp.Objects365.yaml @@ -0,0 +1,34 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# Hyperparameters for Objects365 training +# python train.py --weights yolov5m.pt --data Objects365.yaml --evolve +# See Hyperparameter Evolution tutorial for details https://github.com/ultralytics/yolov5#tutorials + +lr0: 0.00258 +lrf: 0.17 +momentum: 0.779 +weight_decay: 0.00058 +warmup_epochs: 1.33 +warmup_momentum: 0.86 +warmup_bias_lr: 0.0711 +box: 0.0539 +cls: 0.299 +cls_pw: 0.825 +obj: 0.632 +obj_pw: 1.0 +iou_t: 0.2 +anchor_t: 3.44 +anchors: 3.2 +fl_gamma: 0.0 +hsv_h: 0.0188 +hsv_s: 0.704 +hsv_v: 0.36 +degrees: 0.0 +translate: 0.0902 +scale: 0.491 +shear: 0.0 +perspective: 0.0 +flipud: 0.0 +fliplr: 0.5 +mosaic: 1.0 +mixup: 0.0 +copy_paste: 0.0 diff --git a/core/vision/yolov5/data/hyps/hyp.VOC.yaml b/core/vision/yolov5/data/hyps/hyp.VOC.yaml new file mode 100644 index 00000000..0aa4e7d9 --- /dev/null +++ b/core/vision/yolov5/data/hyps/hyp.VOC.yaml @@ -0,0 +1,40 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# Hyperparameters for VOC training +# python train.py --batch 128 --weights yolov5m6.pt --data VOC.yaml --epochs 50 --img 512 --hyp hyp.scratch-med.yaml --evolve +# See Hyperparameter Evolution tutorial for details https://github.com/ultralytics/yolov5#tutorials + +# YOLOv5 Hyperparameter Evolution Results +# Best generation: 467 +# Last generation: 996 +# metrics/precision, metrics/recall, metrics/mAP_0.5, metrics/mAP_0.5:0.95, val/box_loss, val/obj_loss, val/cls_loss +# 0.87729, 0.85125, 0.91286, 0.72664, 0.0076739, 0.0042529, 0.0013865 + +lr0: 0.00334 +lrf: 0.15135 +momentum: 0.74832 +weight_decay: 0.00025 +warmup_epochs: 3.3835 +warmup_momentum: 0.59462 +warmup_bias_lr: 0.18657 +box: 0.02 +cls: 0.21638 +cls_pw: 0.5 +obj: 0.51728 +obj_pw: 0.67198 +iou_t: 0.2 +anchor_t: 3.3744 +fl_gamma: 0.0 +hsv_h: 0.01041 +hsv_s: 0.54703 +hsv_v: 0.27739 +degrees: 0.0 +translate: 0.04591 +scale: 0.75544 +shear: 0.0 +perspective: 0.0 +flipud: 0.0 +fliplr: 0.5 +mosaic: 0.85834 +mixup: 0.04266 +copy_paste: 0.0 +anchors: 3.412 diff --git a/core/vision/yolov5/data/hyps/hyp.scratch-high.yaml b/core/vision/yolov5/data/hyps/hyp.scratch-high.yaml new file mode 100644 index 00000000..123cc840 --- /dev/null +++ b/core/vision/yolov5/data/hyps/hyp.scratch-high.yaml @@ -0,0 +1,34 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# Hyperparameters for high-augmentation COCO training from scratch +# python train.py --batch 32 --cfg yolov5m6.yaml --weights '' --data coco.yaml --img 1280 --epochs 300 +# See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials + +lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3) +lrf: 0.1 # final OneCycleLR learning rate (lr0 * lrf) +momentum: 0.937 # SGD momentum/Adam beta1 +weight_decay: 0.0005 # optimizer weight decay 5e-4 +warmup_epochs: 3.0 # warmup epochs (fractions ok) +warmup_momentum: 0.8 # warmup initial momentum +warmup_bias_lr: 0.1 # warmup initial bias lr +box: 0.05 # box loss gain +cls: 0.3 # cls loss gain +cls_pw: 1.0 # cls BCELoss positive_weight +obj: 0.7 # obj loss gain (scale with pixels) +obj_pw: 1.0 # obj BCELoss positive_weight +iou_t: 0.20 # IoU training threshold +anchor_t: 4.0 # anchor-multiple threshold +# anchors: 3 # anchors per output layer (0 to ignore) +fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5) +hsv_h: 0.015 # image HSV-Hue augmentation (fraction) +hsv_s: 0.7 # image HSV-Saturation augmentation (fraction) +hsv_v: 0.4 # image HSV-Value augmentation (fraction) +degrees: 0.0 # image rotation (+/- deg) +translate: 0.1 # image translation (+/- fraction) +scale: 0.9 # image scale (+/- gain) +shear: 0.0 # image shear (+/- deg) +perspective: 0.0 # image perspective (+/- fraction), range 0-0.001 +flipud: 0.0 # image flip up-down (probability) +fliplr: 0.5 # image flip left-right (probability) +mosaic: 1.0 # image mosaic (probability) +mixup: 0.1 # image mixup (probability) +copy_paste: 0.1 # segment copy-paste (probability) diff --git a/core/vision/yolov5/data/hyps/hyp.scratch-low.yaml b/core/vision/yolov5/data/hyps/hyp.scratch-low.yaml new file mode 100644 index 00000000..b9ef1d55 --- /dev/null +++ b/core/vision/yolov5/data/hyps/hyp.scratch-low.yaml @@ -0,0 +1,34 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# Hyperparameters for low-augmentation COCO training from scratch +# python train.py --batch 64 --cfg yolov5n6.yaml --weights '' --data coco.yaml --img 640 --epochs 300 --linear +# See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials + +lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3) +lrf: 0.01 # final OneCycleLR learning rate (lr0 * lrf) +momentum: 0.937 # SGD momentum/Adam beta1 +weight_decay: 0.0005 # optimizer weight decay 5e-4 +warmup_epochs: 3.0 # warmup epochs (fractions ok) +warmup_momentum: 0.8 # warmup initial momentum +warmup_bias_lr: 0.1 # warmup initial bias lr +box: 0.05 # box loss gain +cls: 0.5 # cls loss gain +cls_pw: 1.0 # cls BCELoss positive_weight +obj: 1.0 # obj loss gain (scale with pixels) +obj_pw: 1.0 # obj BCELoss positive_weight +iou_t: 0.20 # IoU training threshold +anchor_t: 4.0 # anchor-multiple threshold +# anchors: 3 # anchors per output layer (0 to ignore) +fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5) +hsv_h: 0.015 # image HSV-Hue augmentation (fraction) +hsv_s: 0.7 # image HSV-Saturation augmentation (fraction) +hsv_v: 0.4 # image HSV-Value augmentation (fraction) +degrees: 0.0 # image rotation (+/- deg) +translate: 0.1 # image translation (+/- fraction) +scale: 0.5 # image scale (+/- gain) +shear: 0.0 # image shear (+/- deg) +perspective: 0.0 # image perspective (+/- fraction), range 0-0.001 +flipud: 0.0 # image flip up-down (probability) +fliplr: 0.5 # image flip left-right (probability) +mosaic: 1.0 # image mosaic (probability) +mixup: 0.0 # image mixup (probability) +copy_paste: 0.0 # segment copy-paste (probability) diff --git a/core/vision/yolov5/data/hyps/hyp.scratch-med.yaml b/core/vision/yolov5/data/hyps/hyp.scratch-med.yaml new file mode 100644 index 00000000..d6867d75 --- /dev/null +++ b/core/vision/yolov5/data/hyps/hyp.scratch-med.yaml @@ -0,0 +1,34 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# Hyperparameters for medium-augmentation COCO training from scratch +# python train.py --batch 32 --cfg yolov5m6.yaml --weights '' --data coco.yaml --img 1280 --epochs 300 +# See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials + +lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3) +lrf: 0.1 # final OneCycleLR learning rate (lr0 * lrf) +momentum: 0.937 # SGD momentum/Adam beta1 +weight_decay: 0.0005 # optimizer weight decay 5e-4 +warmup_epochs: 3.0 # warmup epochs (fractions ok) +warmup_momentum: 0.8 # warmup initial momentum +warmup_bias_lr: 0.1 # warmup initial bias lr +box: 0.05 # box loss gain +cls: 0.3 # cls loss gain +cls_pw: 1.0 # cls BCELoss positive_weight +obj: 0.7 # obj loss gain (scale with pixels) +obj_pw: 1.0 # obj BCELoss positive_weight +iou_t: 0.20 # IoU training threshold +anchor_t: 4.0 # anchor-multiple threshold +# anchors: 3 # anchors per output layer (0 to ignore) +fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5) +hsv_h: 0.015 # image HSV-Hue augmentation (fraction) +hsv_s: 0.7 # image HSV-Saturation augmentation (fraction) +hsv_v: 0.4 # image HSV-Value augmentation (fraction) +degrees: 0.0 # image rotation (+/- deg) +translate: 0.1 # image translation (+/- fraction) +scale: 0.9 # image scale (+/- gain) +shear: 0.0 # image shear (+/- deg) +perspective: 0.0 # image perspective (+/- fraction), range 0-0.001 +flipud: 0.0 # image flip up-down (probability) +fliplr: 0.5 # image flip left-right (probability) +mosaic: 1.0 # image mosaic (probability) +mixup: 0.1 # image mixup (probability) +copy_paste: 0.0 # segment copy-paste (probability) diff --git a/core/vision/yolov5/data/images/bus.jpg b/core/vision/yolov5/data/images/bus.jpg new file mode 100644 index 00000000..b43e3111 Binary files /dev/null and b/core/vision/yolov5/data/images/bus.jpg differ diff --git a/core/vision/yolov5/data/images/zidane.jpg b/core/vision/yolov5/data/images/zidane.jpg new file mode 100644 index 00000000..92d72ea1 Binary files /dev/null and b/core/vision/yolov5/data/images/zidane.jpg differ diff --git a/core/vision/yolov5/data/scripts/download_weights.sh b/core/vision/yolov5/data/scripts/download_weights.sh new file mode 100644 index 00000000..e9fa6539 --- /dev/null +++ b/core/vision/yolov5/data/scripts/download_weights.sh @@ -0,0 +1,20 @@ +#!/bin/bash +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# Download latest models from https://github.com/ultralytics/yolov5/releases +# Example usage: bash path/to/download_weights.sh +# parent +# └── yolov5 +# ├── yolov5s.pt ← downloads here +# ├── yolov5m.pt +# └── ... + +python - <= cls >= 0, f'incorrect class index {cls}' + + # Write YOLO label + if id not in shapes: + shapes[id] = Image.open(file).size + box = xyxy2xywhn(box[None].astype(np.float), w=shapes[id][0], h=shapes[id][1], clip=True) + with open((labels / id).with_suffix('.txt'), 'a') as f: + f.write(f"{cls} {' '.join(f'{x:.6f}' for x in box[0])}\n") # write label.txt + except Exception as e: + print(f'WARNING: skipping one label for {file}: {e}') + + + # Download manually from https://challenge.xviewdataset.org + dir = Path(yaml['path']) # dataset root dir + # urls = ['https://d307kc0mrhucc3.cloudfront.net/train_labels.zip', # train labels + # 'https://d307kc0mrhucc3.cloudfront.net/train_images.zip', # 15G, 847 train images + # 'https://d307kc0mrhucc3.cloudfront.net/val_images.zip'] # 5G, 282 val images (no labels) + # download(urls, dir=dir, delete=False) + + # Convert labels + convert_labels(dir / 'xView_train.geojson') + + # Move images + images = Path(dir / 'images') + images.mkdir(parents=True, exist_ok=True) + Path(dir / 'train_images').rename(dir / 'images' / 'train') + Path(dir / 'val_images').rename(dir / 'images' / 'val') + + # Split + autosplit(dir / 'images' / 'train') diff --git a/core/vision/yolov5/detect.py b/core/vision/yolov5/detect.py new file mode 100644 index 00000000..ccb9fbf5 --- /dev/null +++ b/core/vision/yolov5/detect.py @@ -0,0 +1,252 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Run inference on images, videos, directories, streams, etc. + +Usage - sources: + $ python path/to/detect.py --weights yolov5s.pt --source 0 # webcam + img.jpg # image + vid.mp4 # video + path/ # directory + path/*.jpg # glob + 'https://youtu.be/Zgi9g1ksQHc' # YouTube + 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream + +Usage - formats: + $ python path/to/detect.py --weights yolov5s.pt # PyTorch + yolov5s.torchscript # TorchScript + yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn + yolov5s.xml # OpenVINO + yolov5s.engine # TensorRT + yolov5s.mlmodel # CoreML (MacOS-only) + yolov5s_saved_model # TensorFlow SavedModel + yolov5s.pb # TensorFlow GraphDef + yolov5s.tflite # TensorFlow Lite + yolov5s_edgetpu.tflite # TensorFlow Edge TPU +""" + +import argparse +import os +import sys +from pathlib import Path + +import cv2 +import torch +import torch.backends.cudnn as cudnn + +FILE = Path(__file__).resolve() +ROOT = FILE.parents[0] # YOLOv5 root directory +if str(ROOT) not in sys.path: + sys.path.append(str(ROOT)) # add ROOT to PATH +ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative + +from models.common import DetectMultiBackend +from utils.datasets import IMG_FORMATS, VID_FORMATS, LoadImages, LoadStreams +from utils.general import (LOGGER, check_file, check_img_size, check_imshow, check_requirements, colorstr, + increment_path, non_max_suppression, print_args, scale_coords, strip_optimizer, xyxy2xywh) +from utils.plots import Annotator, colors, save_one_box +from utils.torch_utils import select_device, time_sync + + +@torch.no_grad() +def run(weights=ROOT / 'yolov5s.pt', # model.pt path(s) + source=ROOT / 'data/images', # file/dir/URL/glob, 0 for webcam + data=ROOT / 'data/coco128.yaml', # dataset.yaml path + imgsz=(640, 640), # inference size (height, width) + conf_thres=0.25, # confidence threshold + iou_thres=0.45, # NMS IOU threshold + max_det=1000, # maximum detections per image + device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu + view_img=False, # show results + save_txt=False, # save results to *.txt + save_conf=False, # save confidences in --save-txt labels + save_crop=False, # save cropped prediction boxes + nosave=False, # do not save images/videos + classes=None, # filter by class: --class 0, or --class 0 2 3 + agnostic_nms=False, # class-agnostic NMS + augment=False, # augmented inference + visualize=False, # visualize features + update=False, # update all models + project=ROOT / 'runs/detect', # save results to project/name + name='exp', # save results to project/name + exist_ok=False, # existing project/name ok, do not increment + line_thickness=3, # bounding box thickness (pixels) + hide_labels=False, # hide labels + hide_conf=False, # hide confidences + half=False, # use FP16 half-precision inference + dnn=False, # use OpenCV DNN for ONNX inference + ): + source = str(source) + save_img = not nosave and not source.endswith('.txt') # save inference images + is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS) + is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://')) + webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file) + if is_url and is_file: + source = check_file(source) # download + + # Directories + save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run + (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir + + # Load model + device = select_device(device) + model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half) + stride, names, pt = model.stride, model.names, model.pt + imgsz = check_img_size(imgsz, s=stride) # check image size + + # Dataloader + if webcam: + view_img = check_imshow() + cudnn.benchmark = True # set True to speed up constant image size inference + dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt) + bs = len(dataset) # batch_size + else: + dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt) + bs = 1 # batch_size + vid_path, vid_writer = [None] * bs, [None] * bs + + # Run inference + model.warmup(imgsz=(1 if pt else bs, 3, *imgsz)) # warmup + dt, seen = [0.0, 0.0, 0.0], 0 + for path, im, im0s, vid_cap, s in dataset: + t1 = time_sync() + im = torch.from_numpy(im).to(device) + im = im.half() if model.fp16 else im.float() # uint8 to fp16/32 + im /= 255 # 0 - 255 to 0.0 - 1.0 + if len(im.shape) == 3: + im = im[None] # expand for batch dim + t2 = time_sync() + dt[0] += t2 - t1 + + # Inference + visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False + pred = model(im, augment=augment, visualize=visualize) + t3 = time_sync() + dt[1] += t3 - t2 + + # NMS + pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det) + dt[2] += time_sync() - t3 + + # Second-stage classifier (optional) + # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s) + + # Process predictions + for i, det in enumerate(pred): # per image + seen += 1 + if webcam: # batch_size >= 1 + p, im0, frame = path[i], im0s[i].copy(), dataset.count + s += f'{i}: ' + else: + p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0) + + p = Path(p) # to Path + save_path = str(save_dir / p.name) # im.jpg + txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # im.txt + s += '%gx%g ' % im.shape[2:] # print string + gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh + imc = im0.copy() if save_crop else im0 # for save_crop + annotator = Annotator(im0, line_width=line_thickness, example=str(names)) + if len(det): + # Rescale boxes from img_size to im0 size + det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round() + + # Print results + for c in det[:, -1].unique(): + n = (det[:, -1] == c).sum() # detections per class + s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string + + # Write results + for *xyxy, conf, cls in reversed(det): + if save_txt: # Write to file + xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh + line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format + with open(txt_path + '.txt', 'a') as f: + f.write(('%g ' * len(line)).rstrip() % line + '\n') + + if save_img or save_crop or view_img: # Add bbox to image + c = int(cls) # integer class + label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}') + annotator.box_label(xyxy, label, color=colors(c, True)) + if save_crop: + save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True) + + # Stream results + im0 = annotator.result() + if view_img: + cv2.imshow(str(p), im0) + cv2.waitKey(1) # 1 millisecond + + # Save results (image with detections) + if save_img: + if dataset.mode == 'image': + cv2.imwrite(save_path, im0) + else: # 'video' or 'stream' + if vid_path[i] != save_path: # new video + vid_path[i] = save_path + if isinstance(vid_writer[i], cv2.VideoWriter): + vid_writer[i].release() # release previous video writer + if vid_cap: # video + fps = vid_cap.get(cv2.CAP_PROP_FPS) + w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + else: # stream + fps, w, h = 30, im0.shape[1], im0.shape[0] + save_path = str(Path(save_path).with_suffix('.mp4')) # force *.mp4 suffix on results videos + vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h)) + vid_writer[i].write(im0) + + # Print time (inference-only) + LOGGER.info(f'{s}Done. ({t3 - t2:.3f}s)') + + # Print results + t = tuple(x / seen * 1E3 for x in dt) # speeds per image + LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t) + if save_txt or save_img: + s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else '' + LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}") + if update: + strip_optimizer(weights) # update model (to fix SourceChangeWarning) + + +def parse_opt(): + parser = argparse.ArgumentParser() + parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model path(s)') + parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob, 0 for webcam') + parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path') + parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w') + parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold') + parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold') + parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image') + parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') + parser.add_argument('--view-img', action='store_true', help='show results') + parser.add_argument('--save-txt', action='store_true', help='save results to *.txt') + parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels') + parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes') + parser.add_argument('--nosave', action='store_true', help='do not save images/videos') + parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3') + parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS') + parser.add_argument('--augment', action='store_true', help='augmented inference') + parser.add_argument('--visualize', action='store_true', help='visualize features') + parser.add_argument('--update', action='store_true', help='update all models') + parser.add_argument('--project', default=ROOT / 'runs/detect', help='save results to project/name') + parser.add_argument('--name', default='exp', help='save results to project/name') + parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment') + parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)') + parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels') + parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences') + parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference') + parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference') + opt = parser.parse_args() + opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand + print_args(FILE.stem, opt) + return opt + + +def main(opt): + check_requirements(exclude=('tensorboard', 'thop')) + run(**vars(opt)) + + +if __name__ == "__main__": + opt = parse_opt() + main(opt) diff --git a/core/vision/yolov5/export.py b/core/vision/yolov5/export.py new file mode 100644 index 00000000..2d4a68e6 --- /dev/null +++ b/core/vision/yolov5/export.py @@ -0,0 +1,559 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Export a YOLOv5 PyTorch model to other formats. TensorFlow exports authored by https://github.com/zldrobit + +Format | `export.py --include` | Model +--- | --- | --- +PyTorch | - | yolov5s.pt +TorchScript | `torchscript` | yolov5s.torchscript +ONNX | `onnx` | yolov5s.onnx +OpenVINO | `openvino` | yolov5s_openvino_model/ +TensorRT | `engine` | yolov5s.engine +CoreML | `coreml` | yolov5s.mlmodel +TensorFlow SavedModel | `saved_model` | yolov5s_saved_model/ +TensorFlow GraphDef | `pb` | yolov5s.pb +TensorFlow Lite | `tflite` | yolov5s.tflite +TensorFlow Edge TPU | `edgetpu` | yolov5s_edgetpu.tflite +TensorFlow.js | `tfjs` | yolov5s_web_model/ + +Requirements: + $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu # CPU + $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow # GPU + +Usage: + $ python path/to/export.py --weights yolov5s.pt --include torchscript onnx openvino engine coreml tflite ... + +Inference: + $ python path/to/detect.py --weights yolov5s.pt # PyTorch + yolov5s.torchscript # TorchScript + yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn + yolov5s.xml # OpenVINO + yolov5s.engine # TensorRT + yolov5s.mlmodel # CoreML (MacOS-only) + yolov5s_saved_model # TensorFlow SavedModel + yolov5s.pb # TensorFlow GraphDef + yolov5s.tflite # TensorFlow Lite + yolov5s_edgetpu.tflite # TensorFlow Edge TPU + +TensorFlow.js: + $ cd .. && git clone https://github.com/zldrobit/tfjs-yolov5-example.git && cd tfjs-yolov5-example + $ npm install + $ ln -s ../../yolov5/yolov5s_web_model public/yolov5s_web_model + $ npm start +""" + +import argparse +import json +import os +import platform +import subprocess +import sys +import time +import warnings +from pathlib import Path + +import pandas as pd +import torch +import torch.nn as nn +from torch.utils.mobile_optimizer import optimize_for_mobile + +FILE = Path(__file__).resolve() +ROOT = FILE.parents[0] # YOLOv5 root directory +if str(ROOT) not in sys.path: + sys.path.append(str(ROOT)) # add ROOT to PATH +ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative + +from models.common import Conv +from models.experimental import attempt_load +from models.yolo import Detect +from utils.activations import SiLU +from utils.datasets import LoadImages +from utils.general import (LOGGER, check_dataset, check_img_size, check_requirements, check_version, colorstr, + file_size, print_args, url2file) +from utils.torch_utils import select_device + + +def export_formats(): + # YOLOv5 export formats + x = [['PyTorch', '-', '.pt', True], + ['TorchScript', 'torchscript', '.torchscript', True], + ['ONNX', 'onnx', '.onnx', True], + ['OpenVINO', 'openvino', '_openvino_model', False], + ['TensorRT', 'engine', '.engine', True], + ['CoreML', 'coreml', '.mlmodel', False], + ['TensorFlow SavedModel', 'saved_model', '_saved_model', True], + ['TensorFlow GraphDef', 'pb', '.pb', True], + ['TensorFlow Lite', 'tflite', '.tflite', False], + ['TensorFlow Edge TPU', 'edgetpu', '_edgetpu.tflite', False], + ['TensorFlow.js', 'tfjs', '_web_model', False]] + return pd.DataFrame(x, columns=['Format', 'Argument', 'Suffix', 'GPU']) + + +def export_torchscript(model, im, file, optimize, prefix=colorstr('TorchScript:')): + # YOLOv5 TorchScript model export + try: + LOGGER.info(f'\n{prefix} starting export with torch {torch.__version__}...') + f = file.with_suffix('.torchscript') + + ts = torch.jit.trace(model, im, strict=False) + d = {"shape": im.shape, "stride": int(max(model.stride)), "names": model.names} + extra_files = {'config.txt': json.dumps(d)} # torch._C.ExtraFilesMap() + if optimize: # https://pytorch.org/tutorials/recipes/mobile_interpreter.html + optimize_for_mobile(ts)._save_for_lite_interpreter(str(f), _extra_files=extra_files) + else: + ts.save(str(f), _extra_files=extra_files) + + LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') + return f + except Exception as e: + LOGGER.info(f'{prefix} export failure: {e}') + + +def export_onnx(model, im, file, opset, train, dynamic, simplify, prefix=colorstr('ONNX:')): + # YOLOv5 ONNX export + try: + check_requirements(('onnx',)) + import onnx + + LOGGER.info(f'\n{prefix} starting export with onnx {onnx.__version__}...') + f = file.with_suffix('.onnx') + + torch.onnx.export(model, im, f, verbose=False, opset_version=opset, + training=torch.onnx.TrainingMode.TRAINING if train else torch.onnx.TrainingMode.EVAL, + do_constant_folding=not train, + input_names=['images'], + output_names=['output'], + dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # shape(1,3,640,640) + 'output': {0: 'batch', 1: 'anchors'} # shape(1,25200,85) + } if dynamic else None) + + # Checks + model_onnx = onnx.load(f) # load onnx model + onnx.checker.check_model(model_onnx) # check onnx model + # LOGGER.info(onnx.helper.printable_graph(model_onnx.graph)) # print + + # Simplify + if simplify: + try: + check_requirements(('onnx-simplifier',)) + import onnxsim + + LOGGER.info(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...') + model_onnx, check = onnxsim.simplify( + model_onnx, + dynamic_input_shape=dynamic, + input_shapes={'images': list(im.shape)} if dynamic else None) + assert check, 'assert check failed' + onnx.save(model_onnx, f) + except Exception as e: + LOGGER.info(f'{prefix} simplifier failure: {e}') + LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') + return f + except Exception as e: + LOGGER.info(f'{prefix} export failure: {e}') + + +def export_openvino(model, im, file, prefix=colorstr('OpenVINO:')): + # YOLOv5 OpenVINO export + try: + check_requirements(('openvino-dev',)) # requires openvino-dev: https://pypi.org/project/openvino-dev/ + import openvino.inference_engine as ie + + LOGGER.info(f'\n{prefix} starting export with openvino {ie.__version__}...') + f = str(file).replace('.pt', '_openvino_model' + os.sep) + + cmd = f"mo --input_model {file.with_suffix('.onnx')} --output_dir {f}" + subprocess.check_output(cmd, shell=True) + + LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') + return f + except Exception as e: + LOGGER.info(f'\n{prefix} export failure: {e}') + + +def export_coreml(model, im, file, prefix=colorstr('CoreML:')): + # YOLOv5 CoreML export + try: + check_requirements(('coremltools',)) + import coremltools as ct + + LOGGER.info(f'\n{prefix} starting export with coremltools {ct.__version__}...') + f = file.with_suffix('.mlmodel') + + ts = torch.jit.trace(model, im, strict=False) # TorchScript model + ct_model = ct.convert(ts, inputs=[ct.ImageType('image', shape=im.shape, scale=1 / 255, bias=[0, 0, 0])]) + ct_model.save(f) + + LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') + return ct_model, f + except Exception as e: + LOGGER.info(f'\n{prefix} export failure: {e}') + return None, None + + +def export_engine(model, im, file, train, half, simplify, workspace=4, verbose=False, prefix=colorstr('TensorRT:')): + # YOLOv5 TensorRT export https://developer.nvidia.com/tensorrt + try: + check_requirements(('tensorrt',)) + import tensorrt as trt + + if trt.__version__[0] == '7': # TensorRT 7 handling https://github.com/ultralytics/yolov5/issues/6012 + grid = model.model[-1].anchor_grid + model.model[-1].anchor_grid = [a[..., :1, :1, :] for a in grid] + export_onnx(model, im, file, 12, train, False, simplify) # opset 12 + model.model[-1].anchor_grid = grid + else: # TensorRT >= 8 + check_version(trt.__version__, '8.0.0', hard=True) # require tensorrt>=8.0.0 + export_onnx(model, im, file, 13, train, False, simplify) # opset 13 + onnx = file.with_suffix('.onnx') + + LOGGER.info(f'\n{prefix} starting export with TensorRT {trt.__version__}...') + assert im.device.type != 'cpu', 'export running on CPU but must be on GPU, i.e. `python export.py --device 0`' + assert onnx.exists(), f'failed to export ONNX file: {onnx}' + f = file.with_suffix('.engine') # TensorRT engine file + logger = trt.Logger(trt.Logger.INFO) + if verbose: + logger.min_severity = trt.Logger.Severity.VERBOSE + + builder = trt.Builder(logger) + config = builder.create_builder_config() + config.max_workspace_size = workspace * 1 << 30 + # config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, workspace << 30) # fix TRT 8.4 deprecation notice + + flag = (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) + network = builder.create_network(flag) + parser = trt.OnnxParser(network, logger) + if not parser.parse_from_file(str(onnx)): + raise RuntimeError(f'failed to load ONNX file: {onnx}') + + inputs = [network.get_input(i) for i in range(network.num_inputs)] + outputs = [network.get_output(i) for i in range(network.num_outputs)] + LOGGER.info(f'{prefix} Network Description:') + for inp in inputs: + LOGGER.info(f'{prefix}\tinput "{inp.name}" with shape {inp.shape} and dtype {inp.dtype}') + for out in outputs: + LOGGER.info(f'{prefix}\toutput "{out.name}" with shape {out.shape} and dtype {out.dtype}') + + LOGGER.info(f'{prefix} building FP{16 if builder.platform_has_fast_fp16 else 32} engine in {f}') + if builder.platform_has_fast_fp16: + config.set_flag(trt.BuilderFlag.FP16) + with builder.build_engine(network, config) as engine, open(f, 'wb') as t: + t.write(engine.serialize()) + LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') + return f + except Exception as e: + LOGGER.info(f'\n{prefix} export failure: {e}') + + +def export_saved_model(model, im, file, dynamic, + tf_nms=False, agnostic_nms=False, topk_per_class=100, topk_all=100, iou_thres=0.45, + conf_thres=0.25, keras=False, prefix=colorstr('TensorFlow SavedModel:')): + # YOLOv5 TensorFlow SavedModel export + try: + import tensorflow as tf + from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2 + + from models.tf import TFDetect, TFModel + + LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...') + f = str(file).replace('.pt', '_saved_model') + batch_size, ch, *imgsz = list(im.shape) # BCHW + + tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz) + im = tf.zeros((batch_size, *imgsz, ch)) # BHWC order for TensorFlow + _ = tf_model.predict(im, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres) + inputs = tf.keras.Input(shape=(*imgsz, ch), batch_size=None if dynamic else batch_size) + outputs = tf_model.predict(inputs, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres) + keras_model = tf.keras.Model(inputs=inputs, outputs=outputs) + keras_model.trainable = False + keras_model.summary() + if keras: + keras_model.save(f, save_format='tf') + else: + m = tf.function(lambda x: keras_model(x)) # full model + spec = tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype) + m = m.get_concrete_function(spec) + frozen_func = convert_variables_to_constants_v2(m) + tfm = tf.Module() + tfm.__call__ = tf.function(lambda x: frozen_func(x)[0], [spec]) + tfm.__call__(im) + tf.saved_model.save( + tfm, + f, + options=tf.saved_model.SaveOptions(experimental_custom_gradients=False) if + check_version(tf.__version__, '2.6') else tf.saved_model.SaveOptions()) + LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') + return keras_model, f + except Exception as e: + LOGGER.info(f'\n{prefix} export failure: {e}') + return None, None + + +def export_pb(keras_model, im, file, prefix=colorstr('TensorFlow GraphDef:')): + # YOLOv5 TensorFlow GraphDef *.pb export https://github.com/leimao/Frozen_Graph_TensorFlow + try: + import tensorflow as tf + from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2 + + LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...') + f = file.with_suffix('.pb') + + m = tf.function(lambda x: keras_model(x)) # full model + m = m.get_concrete_function(tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype)) + frozen_func = convert_variables_to_constants_v2(m) + frozen_func.graph.as_graph_def() + tf.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir=str(f.parent), name=f.name, as_text=False) + + LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') + return f + except Exception as e: + LOGGER.info(f'\n{prefix} export failure: {e}') + + +def export_tflite(keras_model, im, file, int8, data, ncalib, prefix=colorstr('TensorFlow Lite:')): + # YOLOv5 TensorFlow Lite export + try: + import tensorflow as tf + + LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...') + batch_size, ch, *imgsz = list(im.shape) # BCHW + f = str(file).replace('.pt', '-fp16.tflite') + + converter = tf.lite.TFLiteConverter.from_keras_model(keras_model) + converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS] + converter.target_spec.supported_types = [tf.float16] + converter.optimizations = [tf.lite.Optimize.DEFAULT] + if int8: + from models.tf import representative_dataset_gen + dataset = LoadImages(check_dataset(data)['train'], img_size=imgsz, auto=False) # representative data + converter.representative_dataset = lambda: representative_dataset_gen(dataset, ncalib) + converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8] + converter.target_spec.supported_types = [] + converter.inference_input_type = tf.uint8 # or tf.int8 + converter.inference_output_type = tf.uint8 # or tf.int8 + converter.experimental_new_quantizer = True + f = str(file).replace('.pt', '-int8.tflite') + + tflite_model = converter.convert() + open(f, "wb").write(tflite_model) + LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') + return f + except Exception as e: + LOGGER.info(f'\n{prefix} export failure: {e}') + + +def export_edgetpu(keras_model, im, file, prefix=colorstr('Edge TPU:')): + # YOLOv5 Edge TPU export https://coral.ai/docs/edgetpu/models-intro/ + try: + cmd = 'edgetpu_compiler --version' + help_url = 'https://coral.ai/docs/edgetpu/compiler/' + assert platform.system() == 'Linux', f'export only supported on Linux. See {help_url}' + if subprocess.run(cmd + ' >/dev/null', shell=True).returncode != 0: + LOGGER.info(f'\n{prefix} export requires Edge TPU compiler. Attempting install from {help_url}') + sudo = subprocess.run('sudo --version >/dev/null', shell=True).returncode == 0 # sudo installed on system + for c in ['curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -', + 'echo "deb https://packages.cloud.google.com/apt coral-edgetpu-stable main" | sudo tee /etc/apt/sources.list.d/coral-edgetpu.list', + 'sudo apt-get update', + 'sudo apt-get install edgetpu-compiler']: + subprocess.run(c if sudo else c.replace('sudo ', ''), shell=True, check=True) + ver = subprocess.run(cmd, shell=True, capture_output=True, check=True).stdout.decode().split()[-1] + + LOGGER.info(f'\n{prefix} starting export with Edge TPU compiler {ver}...') + f = str(file).replace('.pt', '-int8_edgetpu.tflite') # Edge TPU model + f_tfl = str(file).replace('.pt', '-int8.tflite') # TFLite model + + cmd = f"edgetpu_compiler -s {f_tfl}" + subprocess.run(cmd, shell=True, check=True) + + LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') + return f + except Exception as e: + LOGGER.info(f'\n{prefix} export failure: {e}') + + +def export_tfjs(keras_model, im, file, prefix=colorstr('TensorFlow.js:')): + # YOLOv5 TensorFlow.js export + try: + check_requirements(('tensorflowjs',)) + import re + + import tensorflowjs as tfjs + + LOGGER.info(f'\n{prefix} starting export with tensorflowjs {tfjs.__version__}...') + f = str(file).replace('.pt', '_web_model') # js dir + f_pb = file.with_suffix('.pb') # *.pb path + f_json = f + '/model.json' # *.json path + + cmd = f'tensorflowjs_converter --input_format=tf_frozen_model ' \ + f'--output_node_names="Identity,Identity_1,Identity_2,Identity_3" {f_pb} {f}' + subprocess.run(cmd, shell=True) + + json = open(f_json).read() + with open(f_json, 'w') as j: # sort JSON Identity_* in ascending order + subst = re.sub( + r'{"outputs": {"Identity.?.?": {"name": "Identity.?.?"}, ' + r'"Identity.?.?": {"name": "Identity.?.?"}, ' + r'"Identity.?.?": {"name": "Identity.?.?"}, ' + r'"Identity.?.?": {"name": "Identity.?.?"}}}', + r'{"outputs": {"Identity": {"name": "Identity"}, ' + r'"Identity_1": {"name": "Identity_1"}, ' + r'"Identity_2": {"name": "Identity_2"}, ' + r'"Identity_3": {"name": "Identity_3"}}}', + json) + j.write(subst) + + LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') + return f + except Exception as e: + LOGGER.info(f'\n{prefix} export failure: {e}') + + +@torch.no_grad() +def run(data=ROOT / 'data/coco128.yaml', # 'dataset.yaml path' + weights=ROOT / 'yolov5s.pt', # weights path + imgsz=(640, 640), # image (height, width) + batch_size=1, # batch size + device='cpu', # cuda device, i.e. 0 or 0,1,2,3 or cpu + include=('torchscript', 'onnx'), # include formats + half=False, # FP16 half-precision export + inplace=False, # set YOLOv5 Detect() inplace=True + train=False, # model.train() mode + optimize=False, # TorchScript: optimize for mobile + int8=False, # CoreML/TF INT8 quantization + dynamic=False, # ONNX/TF: dynamic axes + simplify=False, # ONNX: simplify model + opset=12, # ONNX: opset version + verbose=False, # TensorRT: verbose log + workspace=4, # TensorRT: workspace size (GB) + nms=False, # TF: add NMS to model + agnostic_nms=False, # TF: add agnostic NMS to model + topk_per_class=100, # TF.js NMS: topk per class to keep + topk_all=100, # TF.js NMS: topk for all classes to keep + iou_thres=0.45, # TF.js NMS: IoU threshold + conf_thres=0.25 # TF.js NMS: confidence threshold + ): + t = time.time() + include = [x.lower() for x in include] # to lowercase + formats = tuple(export_formats()['Argument'][1:]) # --include arguments + flags = [x in include for x in formats] + assert sum(flags) == len(include), f'ERROR: Invalid --include {include}, valid --include arguments are {formats}' + jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs = flags # export booleans + file = Path(url2file(weights) if str(weights).startswith(('http:/', 'https:/')) else weights) # PyTorch weights + + # Load PyTorch model + device = select_device(device) + assert not (device.type == 'cpu' and half), '--half only compatible with GPU export, i.e. use --device 0' + model = attempt_load(weights, map_location=device, inplace=True, fuse=True) # load FP32 model + nc, names = model.nc, model.names # number of classes, class names + + # Checks + imgsz *= 2 if len(imgsz) == 1 else 1 # expand + opset = 12 if ('openvino' in include) else opset # OpenVINO requires opset <= 12 + assert nc == len(names), f'Model class count {nc} != len(names) {len(names)}' + + # Input + gs = int(max(model.stride)) # grid size (max stride) + imgsz = [check_img_size(x, gs) for x in imgsz] # verify img_size are gs-multiples + im = torch.zeros(batch_size, 3, *imgsz).to(device) # image size(1,3,320,192) BCHW iDetection + + # Update model + if half: + im, model = im.half(), model.half() # to FP16 + model.train() if train else model.eval() # training mode = no Detect() layer grid construction + for k, m in model.named_modules(): + if isinstance(m, Conv): # assign export-friendly activations + if isinstance(m.act, nn.SiLU): + m.act = SiLU() + elif isinstance(m, Detect): + m.inplace = inplace + m.onnx_dynamic = dynamic + if hasattr(m, 'forward_export'): + m.forward = m.forward_export # assign custom forward (optional) + + for _ in range(2): + y = model(im) # dry runs + shape = tuple(y[0].shape) # model output shape + LOGGER.info(f"\n{colorstr('PyTorch:')} starting from {file} with output shape {shape} ({file_size(file):.1f} MB)") + + # Exports + f = [''] * 10 # exported filenames + warnings.filterwarnings(action='ignore', category=torch.jit.TracerWarning) # suppress TracerWarning + if jit: + f[0] = export_torchscript(model, im, file, optimize) + if engine: # TensorRT required before ONNX + f[1] = export_engine(model, im, file, train, half, simplify, workspace, verbose) + if onnx or xml: # OpenVINO requires ONNX + f[2] = export_onnx(model, im, file, opset, train, dynamic, simplify) + if xml: # OpenVINO + f[3] = export_openvino(model, im, file) + if coreml: + _, f[4] = export_coreml(model, im, file) + + # TensorFlow Exports + if any((saved_model, pb, tflite, edgetpu, tfjs)): + if int8 or edgetpu: # TFLite --int8 bug https://github.com/ultralytics/yolov5/issues/5707 + check_requirements(('flatbuffers==1.12',)) # required before `import tensorflow` + assert not (tflite and tfjs), 'TFLite and TF.js models must be exported separately, please pass only one type.' + model, f[5] = export_saved_model(model.cpu(), im, file, dynamic, tf_nms=nms or agnostic_nms or tfjs, + agnostic_nms=agnostic_nms or tfjs, topk_per_class=topk_per_class, + topk_all=topk_all, conf_thres=conf_thres, iou_thres=iou_thres) # keras model + if pb or tfjs: # pb prerequisite to tfjs + f[6] = export_pb(model, im, file) + if tflite or edgetpu: + f[7] = export_tflite(model, im, file, int8=int8 or edgetpu, data=data, ncalib=100) + if edgetpu: + f[8] = export_edgetpu(model, im, file) + if tfjs: + f[9] = export_tfjs(model, im, file) + + # Finish + f = [str(x) for x in f if x] # filter out '' and None + if any(f): + LOGGER.info(f'\nExport complete ({time.time() - t:.2f}s)' + f"\nResults saved to {colorstr('bold', file.parent.resolve())}" + f"\nDetect: python detect.py --weights {f[-1]}" + f"\nPyTorch Hub: model = torch.hub.load('ultralytics/yolov5', 'custom', '{f[-1]}')" + f"\nValidate: python val.py --weights {f[-1]}" + f"\nVisualize: https://netron.app") + return f # return list of exported files/dirs + + +def parse_opt(): + parser = argparse.ArgumentParser() + parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path') + parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model.pt path(s)') + parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640, 640], help='image (h, w)') + parser.add_argument('--batch-size', type=int, default=1, help='batch size') + parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') + parser.add_argument('--half', action='store_true', help='FP16 half-precision export') + parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True') + parser.add_argument('--train', action='store_true', help='model.train() mode') + parser.add_argument('--optimize', action='store_true', help='TorchScript: optimize for mobile') + parser.add_argument('--int8', action='store_true', help='CoreML/TF INT8 quantization') + parser.add_argument('--dynamic', action='store_true', help='ONNX/TF: dynamic axes') + parser.add_argument('--simplify', action='store_true', help='ONNX: simplify model') + parser.add_argument('--opset', type=int, default=12, help='ONNX: opset version') + parser.add_argument('--verbose', action='store_true', help='TensorRT: verbose log') + parser.add_argument('--workspace', type=int, default=4, help='TensorRT: workspace size (GB)') + parser.add_argument('--nms', action='store_true', help='TF: add NMS to model') + parser.add_argument('--agnostic-nms', action='store_true', help='TF: add agnostic NMS to model') + parser.add_argument('--topk-per-class', type=int, default=100, help='TF.js NMS: topk per class to keep') + parser.add_argument('--topk-all', type=int, default=100, help='TF.js NMS: topk for all classes to keep') + parser.add_argument('--iou-thres', type=float, default=0.45, help='TF.js NMS: IoU threshold') + parser.add_argument('--conf-thres', type=float, default=0.25, help='TF.js NMS: confidence threshold') + parser.add_argument('--include', nargs='+', + default=['torchscript', 'onnx'], + help='torchscript, onnx, openvino, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs') + opt = parser.parse_args() + print_args(FILE.stem, opt) + return opt + + +def main(opt): + for opt.weights in (opt.weights if isinstance(opt.weights, list) else [opt.weights]): + run(**vars(opt)) + + +if __name__ == "__main__": + opt = parse_opt() + main(opt) diff --git a/core/vision/yolov5/hubconf.py b/core/vision/yolov5/hubconf.py new file mode 100644 index 00000000..39fa614b --- /dev/null +++ b/core/vision/yolov5/hubconf.py @@ -0,0 +1,143 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +PyTorch Hub models https://pytorch.org/hub/ultralytics_yolov5/ + +Usage: + import torch + model = torch.hub.load('ultralytics/yolov5', 'yolov5s') + model = torch.hub.load('ultralytics/yolov5:master', 'custom', 'path/to/yolov5s.onnx') # file from branch +""" + +import torch + + +def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): + """Creates or loads a YOLOv5 model + + Arguments: + name (str): model name 'yolov5s' or path 'path/to/best.pt' + pretrained (bool): load pretrained weights into the model + channels (int): number of input channels + classes (int): number of model classes + autoshape (bool): apply YOLOv5 .autoshape() wrapper to model + verbose (bool): print all information to screen + device (str, torch.device, None): device to use for model parameters + + Returns: + YOLOv5 model + """ + from pathlib import Path + + from models.common import AutoShape, DetectMultiBackend + from models.yolo import Model + from utils.downloads import attempt_download + from utils.general import LOGGER, check_requirements, intersect_dicts, logging + from utils.torch_utils import select_device + + if not verbose: + LOGGER.setLevel(logging.WARNING) + check_requirements(exclude=('tensorboard', 'thop', 'opencv-python')) + name = Path(name) + path = name.with_suffix('.pt') if name.suffix == '' else name # checkpoint path + try: + device = select_device(('0' if torch.cuda.is_available() else 'cpu') if device is None else device) + + if pretrained and channels == 3 and classes == 80: + model = DetectMultiBackend(path, device=device) # download/load FP32 model + # model = models.experimental.attempt_load(path, map_location=device) # download/load FP32 model + else: + cfg = list((Path(__file__).parent / 'models').rglob(f'{path.stem}.yaml'))[0] # model.yaml path + model = Model(cfg, channels, classes) # create model + if pretrained: + ckpt = torch.load(attempt_download(path), map_location=device) # load + csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32 + csd = intersect_dicts(csd, model.state_dict(), exclude=['anchors']) # intersect + model.load_state_dict(csd, strict=False) # load + if len(ckpt['model'].names) == classes: + model.names = ckpt['model'].names # set class names attribute + if autoshape: + model = AutoShape(model) # for file/URI/PIL/cv2/np inputs and NMS + return model.to(device) + + except Exception as e: + help_url = 'https://github.com/ultralytics/yolov5/issues/36' + s = f'{e}. Cache may be out of date, try `force_reload=True` or see {help_url} for help.' + raise Exception(s) from e + + +def custom(path='path/to/model.pt', autoshape=True, verbose=True, device=None): + # YOLOv5 custom or local model + return _create(path, autoshape=autoshape, verbose=verbose, device=device) + + +def yolov5n(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): + # YOLOv5-nano model https://github.com/ultralytics/yolov5 + return _create('yolov5n', pretrained, channels, classes, autoshape, verbose, device) + + +def yolov5s(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): + # YOLOv5-small model https://github.com/ultralytics/yolov5 + return _create('yolov5s', pretrained, channels, classes, autoshape, verbose, device) + + +def yolov5m(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): + # YOLOv5-medium model https://github.com/ultralytics/yolov5 + return _create('yolov5m', pretrained, channels, classes, autoshape, verbose, device) + + +def yolov5l(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): + # YOLOv5-large model https://github.com/ultralytics/yolov5 + return _create('yolov5l', pretrained, channels, classes, autoshape, verbose, device) + + +def yolov5x(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): + # YOLOv5-xlarge model https://github.com/ultralytics/yolov5 + return _create('yolov5x', pretrained, channels, classes, autoshape, verbose, device) + + +def yolov5n6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): + # YOLOv5-nano-P6 model https://github.com/ultralytics/yolov5 + return _create('yolov5n6', pretrained, channels, classes, autoshape, verbose, device) + + +def yolov5s6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): + # YOLOv5-small-P6 model https://github.com/ultralytics/yolov5 + return _create('yolov5s6', pretrained, channels, classes, autoshape, verbose, device) + + +def yolov5m6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): + # YOLOv5-medium-P6 model https://github.com/ultralytics/yolov5 + return _create('yolov5m6', pretrained, channels, classes, autoshape, verbose, device) + + +def yolov5l6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): + # YOLOv5-large-P6 model https://github.com/ultralytics/yolov5 + return _create('yolov5l6', pretrained, channels, classes, autoshape, verbose, device) + + +def yolov5x6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): + # YOLOv5-xlarge-P6 model https://github.com/ultralytics/yolov5 + return _create('yolov5x6', pretrained, channels, classes, autoshape, verbose, device) + + +if __name__ == '__main__': + model = _create(name='yolov5s', pretrained=True, channels=3, classes=80, autoshape=True, verbose=True) # pretrained + # model = custom(path='path/to/model.pt') # custom + + # Verify inference + from pathlib import Path + + import cv2 + import numpy as np + from PIL import Image + + imgs = ['data/images/zidane.jpg', # filename + Path('data/images/zidane.jpg'), # Path + 'https://ultralytics.com/images/zidane.jpg', # URI + cv2.imread('data/images/bus.jpg')[:, :, ::-1], # OpenCV + Image.open('data/images/bus.jpg'), # PIL + np.zeros((320, 640, 3))] # numpy + + results = model(imgs, size=320) # batched inference + results.print() + results.save() diff --git a/core/vision/yolov5/models/__init__.py b/core/vision/yolov5/models/__init__.py new file mode 100644 index 00000000..8e1f5352 --- /dev/null +++ b/core/vision/yolov5/models/__init__.py @@ -0,0 +1,8 @@ +import sys +from pathlib import Path + +FILE = Path(__file__).resolve() +ROOT = FILE.parents[1] # YOLOv5 root directory +if str(ROOT) not in sys.path: + sys.path.append(str(ROOT)) # add ROOT to PATH +ROOT = ROOT.relative_to(Path.cwd()) # relative diff --git a/core/vision/yolov5/models/common.py b/core/vision/yolov5/models/common.py new file mode 100644 index 00000000..53b7c496 --- /dev/null +++ b/core/vision/yolov5/models/common.py @@ -0,0 +1,723 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Common modules +""" + +import json +import math +import platform +import warnings +from collections import OrderedDict, namedtuple +from copy import copy +from pathlib import Path + +import cv2 +import numpy as np +import pandas as pd +import requests +import torch +import torch.nn as nn +import yaml +from PIL import Image +from torch.cuda import amp + +from utils.datasets import exif_transpose, letterbox +from utils.general import ( + LOGGER, + check_requirements, + check_suffix, + check_version, + colorstr, + increment_path, + make_divisible, + non_max_suppression, + scale_coords, + xywh2xyxy, + xyxy2xywh, +) +from utils.plots import Annotator, colors, save_one_box +from utils.torch_utils import copy_attr, time_sync + + +def autopad(k, p=None): # kernel, padding + # Pad to 'same' + if p is None: + p = k // 2 if isinstance(k, int) else (x // 2 for x in k) # auto-pad + return p + + +class Conv(nn.Module): + # Standard convolution + def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups + super().__init__() + self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False) + self.bn = nn.BatchNorm2d(c2) + self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity()) + + def forward(self, x): + return self.act(self.bn(self.conv(x))) + + def forward_fuse(self, x): + return self.act(self.conv(x)) + + +class DWConv(Conv): + # Depth-wise convolution class + def __init__(self, c1, c2, k=1, s=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups + super().__init__(c1, c2, k, s, g=math.gcd(c1, c2), act=act) + + +class TransformerLayer(nn.Module): + # Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance) + def __init__(self, c, num_heads): + super().__init__() + self.q = nn.Linear(c, c, bias=False) + self.k = nn.Linear(c, c, bias=False) + self.v = nn.Linear(c, c, bias=False) + self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads) + self.fc1 = nn.Linear(c, c, bias=False) + self.fc2 = nn.Linear(c, c, bias=False) + + def forward(self, x): + x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x + x = self.fc2(self.fc1(x)) + x + return x + + +class TransformerBlock(nn.Module): + # Vision Transformer https://arxiv.org/abs/2010.11929 + def __init__(self, c1, c2, num_heads, num_layers): + super().__init__() + self.conv = None + if c1 != c2: + self.conv = Conv(c1, c2) + self.linear = nn.Linear(c2, c2) # learnable position embedding + self.tr = nn.Sequential(*(TransformerLayer(c2, num_heads) for _ in range(num_layers))) + self.c2 = c2 + + def forward(self, x): + if self.conv is not None: + x = self.conv(x) + b, _, w, h = x.shape + p = x.flatten(2).permute(2, 0, 1) + return self.tr(p + self.linear(p)).permute(1, 2, 0).reshape(b, self.c2, w, h) + + +class Bottleneck(nn.Module): + # Standard bottleneck + def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = Conv(c_, c2, 3, 1, g=g) + self.add = shortcut and c1 == c2 + + def forward(self, x): + return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x)) + + +class BottleneckCSP(nn.Module): + # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False) + self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False) + self.cv4 = Conv(2 * c_, c2, 1, 1) + self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3) + self.act = nn.SiLU() + self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n))) + + def forward(self, x): + y1 = self.cv3(self.m(self.cv1(x))) + y2 = self.cv2(x) + return self.cv4(self.act(self.bn(torch.cat((y1, y2), dim=1)))) + + +class C3(nn.Module): + # CSP Bottleneck with 3 convolutions + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = Conv(c1, c_, 1, 1) + self.cv3 = Conv(2 * c_, c2, 1) # act=FReLU(c2) + self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n))) + # self.m = nn.Sequential(*(CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n))) + + def forward(self, x): + return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), dim=1)) + + +class C3TR(C3): + # C3 module with TransformerBlock() + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): + super().__init__(c1, c2, n, shortcut, g, e) + c_ = int(c2 * e) + self.m = TransformerBlock(c_, c_, 4, n) + + +class C3SPP(C3): + # C3 module with SPP() + def __init__(self, c1, c2, k=(5, 9, 13), n=1, shortcut=True, g=1, e=0.5): + super().__init__(c1, c2, n, shortcut, g, e) + c_ = int(c2 * e) + self.m = SPP(c_, c_, k) + + +class C3Ghost(C3): + # C3 module with GhostBottleneck() + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): + super().__init__(c1, c2, n, shortcut, g, e) + c_ = int(c2 * e) # hidden channels + self.m = nn.Sequential(*(GhostBottleneck(c_, c_) for _ in range(n))) + + +class SPP(nn.Module): + # Spatial Pyramid Pooling (SPP) layer https://arxiv.org/abs/1406.4729 + def __init__(self, c1, c2, k=(5, 9, 13)): + super().__init__() + c_ = c1 // 2 # hidden channels + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1) + self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k]) + + def forward(self, x): + x = self.cv1(x) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") # suppress torch 1.9.0 max_pool2d() warning + return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1)) + + +class SPPF(nn.Module): + # Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher + def __init__(self, c1, c2, k=5): # equivalent to SPP(k=(5, 9, 13)) + super().__init__() + c_ = c1 // 2 # hidden channels + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = Conv(c_ * 4, c2, 1, 1) + self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2) + + def forward(self, x): + x = self.cv1(x) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") # suppress torch 1.9.0 max_pool2d() warning + y1 = self.m(x) + y2 = self.m(y1) + return self.cv2(torch.cat((x, y1, y2, self.m(y2)), 1)) + + +class Focus(nn.Module): + # Focus wh information into c-space + def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups + super().__init__() + self.conv = Conv(c1 * 4, c2, k, s, p, g, act) + # self.contract = Contract(gain=2) + + def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2) + return self.conv(torch.cat((x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]), 1)) + # return self.conv(self.contract(x)) + + +class GhostConv(nn.Module): + # Ghost Convolution https://github.com/huawei-noah/ghostnet + def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups + super().__init__() + c_ = c2 // 2 # hidden channels + self.cv1 = Conv(c1, c_, k, s, None, g, act) + self.cv2 = Conv(c_, c_, 5, 1, None, c_, act) + + def forward(self, x): + y = self.cv1(x) + return torch.cat((y, self.cv2(y)), 1) + + +class GhostBottleneck(nn.Module): + # Ghost Bottleneck https://github.com/huawei-noah/ghostnet + def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride + super().__init__() + c_ = c2 // 2 + self.conv = nn.Sequential( + GhostConv(c1, c_, 1, 1), # pw + DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw + GhostConv(c_, c2, 1, 1, act=False), + ) # pw-linear + self.shortcut = ( + nn.Sequential(DWConv(c1, c1, k, s, act=False), Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity() + ) + + def forward(self, x): + return self.conv(x) + self.shortcut(x) + + +class Contract(nn.Module): + # Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40) + def __init__(self, gain=2): + super().__init__() + self.gain = gain + + def forward(self, x): + b, c, h, w = x.size() # assert (h / s == 0) and (W / s == 0), 'Indivisible gain' + s = self.gain + x = x.view(b, c, h // s, s, w // s, s) # x(1,64,40,2,40,2) + x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40) + return x.view(b, c * s * s, h // s, w // s) # x(1,256,40,40) + + +class Expand(nn.Module): + # Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160) + def __init__(self, gain=2): + super().__init__() + self.gain = gain + + def forward(self, x): + b, c, h, w = x.size() # assert C / s ** 2 == 0, 'Indivisible gain' + s = self.gain + x = x.view(b, s, s, c // s ** 2, h, w) # x(1,2,2,16,80,80) + x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2) + return x.view(b, c // s ** 2, h * s, w * s) # x(1,16,160,160) + + +class Concat(nn.Module): + # Concatenate a list of tensors along dimension + def __init__(self, dimension=1): + super().__init__() + self.d = dimension + + def forward(self, x): + return torch.cat(x, self.d) + + +class DetectMultiBackend(nn.Module): + # YOLOv5 MultiBackend class for python inference on various backends + def __init__(self, weights="yolov5s.pt", device=torch.device("cpu"), dnn=False, data=None, fp16=False): + # Usage: + # PyTorch: weights = *.pt + # TorchScript: *.torchscript + # ONNX Runtime: *.onnx + # ONNX OpenCV DNN: *.onnx with --dnn + # OpenVINO: *.xml + # CoreML: *.mlmodel + # TensorRT: *.engine + # TensorFlow SavedModel: *_saved_model + # TensorFlow GraphDef: *.pb + # TensorFlow Lite: *.tflite + # TensorFlow Edge TPU: *_edgetpu.tflite + from models.experimental import attempt_download, attempt_load # scoped to avoid circular import + + super().__init__() + w = str(weights[0] if isinstance(weights, list) else weights) + pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs = self.model_type(w) # get backend + stride, names = 64, [f"class{i}" for i in range(1000)] # assign defaults + w = attempt_download(w) # download if not local + fp16 &= (pt or jit or onnx or engine) and device.type != "cpu" # FP16 + if data: # data.yaml path (optional) + with open(data, errors="ignore") as f: + names = yaml.safe_load(f)["names"] # class names + + if pt: # PyTorch + model = attempt_load(weights if isinstance(weights, list) else w, map_location=device) + stride = max(int(model.stride.max()), 32) # model stride + names = model.module.names if hasattr(model, "module") else model.names # get class names + model.half() if fp16 else model.float() + self.model = model # explicitly assign for to(), cpu(), cuda(), half() + elif jit: # TorchScript + LOGGER.info(f"Loading {w} for TorchScript inference...") + extra_files = {"config.txt": ""} # model metadata + model = torch.jit.load(w, _extra_files=extra_files) + model.half() if fp16 else model.float() + if extra_files["config.txt"]: + d = json.loads(extra_files["config.txt"]) # extra_files dict + stride, names = int(d["stride"]), d["names"] + elif dnn: # ONNX OpenCV DNN + LOGGER.info(f"Loading {w} for ONNX OpenCV DNN inference...") + check_requirements(("opencv-python>=4.5.4",)) + net = cv2.dnn.readNetFromONNX(w) + elif onnx: # ONNX Runtime + LOGGER.info(f"Loading {w} for ONNX Runtime inference...") + cuda = torch.cuda.is_available() + check_requirements(("onnx", "onnxruntime-gpu" if cuda else "onnxruntime")) + import onnxruntime + + providers = ["CUDAExecutionProvider", "CPUExecutionProvider"] if cuda else ["CPUExecutionProvider"] + session = onnxruntime.InferenceSession(w, providers=providers) + elif xml: # OpenVINO + LOGGER.info(f"Loading {w} for OpenVINO inference...") + check_requirements(("openvino-dev",)) # requires openvino-dev: https://pypi.org/project/openvino-dev/ + import openvino.inference_engine as ie + + core = ie.IECore() + if not Path(w).is_file(): # if not *.xml + w = next(Path(w).glob("*.xml")) # get *.xml file from *_openvino_model dir + network = core.read_network(model=w, weights=Path(w).with_suffix(".bin")) # *.xml, *.bin paths + executable_network = core.load_network(network, device_name="CPU", num_requests=1) + elif engine: # TensorRT + LOGGER.info(f"Loading {w} for TensorRT inference...") + import tensorrt as trt # https://developer.nvidia.com/nvidia-tensorrt-download + + check_version(trt.__version__, "7.0.0", hard=True) # require tensorrt>=7.0.0 + Binding = namedtuple("Binding", ("name", "dtype", "shape", "data", "ptr")) + logger = trt.Logger(trt.Logger.INFO) + with open(w, "rb") as f, trt.Runtime(logger) as runtime: + model = runtime.deserialize_cuda_engine(f.read()) + bindings = OrderedDict() + fp16 = False # default updated below + for index in range(model.num_bindings): + name = model.get_binding_name(index) + dtype = trt.nptype(model.get_binding_dtype(index)) + shape = tuple(model.get_binding_shape(index)) + data = torch.from_numpy(np.empty(shape, dtype=np.dtype(dtype))).to(device) + bindings[name] = Binding(name, dtype, shape, data, int(data.data_ptr())) + if model.binding_is_input(index) and dtype == np.float16: + fp16 = True + binding_addrs = OrderedDict((n, d.ptr) for n, d in bindings.items()) + context = model.create_execution_context() + batch_size = bindings["images"].shape[0] + elif coreml: # CoreML + LOGGER.info(f"Loading {w} for CoreML inference...") + import coremltools as ct + + model = ct.models.MLModel(w) + else: # TensorFlow (SavedModel, GraphDef, Lite, Edge TPU) + if saved_model: # SavedModel + LOGGER.info(f"Loading {w} for TensorFlow SavedModel inference...") + import tensorflow as tf + + keras = False # assume TF1 saved_model + model = tf.keras.models.load_model(w) if keras else tf.saved_model.load(w) + elif pb: # GraphDef https://www.tensorflow.org/guide/migrate#a_graphpb_or_graphpbtxt + LOGGER.info(f"Loading {w} for TensorFlow GraphDef inference...") + import tensorflow as tf + + def wrap_frozen_graph(gd, inputs, outputs): + x = tf.compat.v1.wrap_function(lambda: tf.compat.v1.import_graph_def(gd, name=""), []) # wrapped + ge = x.graph.as_graph_element + return x.prune(tf.nest.map_structure(ge, inputs), tf.nest.map_structure(ge, outputs)) + + gd = tf.Graph().as_graph_def() # graph_def + gd.ParseFromString(open(w, "rb").read()) + frozen_func = wrap_frozen_graph(gd, inputs="x:0", outputs="Identity:0") + elif tflite or edgetpu: # https://www.tensorflow.org/lite/guide/python#install_tensorflow_lite_for_python + try: # https://coral.ai/docs/edgetpu/tflite-python/#update-existing-tf-lite-code-for-the-edge-tpu + from tflite_runtime.interpreter import Interpreter, load_delegate + except ImportError: + import tensorflow as tf + + Interpreter, load_delegate = ( + tf.lite.Interpreter, + tf.lite.experimental.load_delegate, + ) + if edgetpu: # Edge TPU https://coral.ai/software/#edgetpu-runtime + LOGGER.info(f"Loading {w} for TensorFlow Lite Edge TPU inference...") + delegate = {"Linux": "libedgetpu.so.1", "Darwin": "libedgetpu.1.dylib", "Windows": "edgetpu.dll"}[ + platform.system() + ] + interpreter = Interpreter(model_path=w, experimental_delegates=[load_delegate(delegate)]) + else: # Lite + LOGGER.info(f"Loading {w} for TensorFlow Lite inference...") + interpreter = Interpreter(model_path=w) # load TFLite model + interpreter.allocate_tensors() # allocate + input_details = interpreter.get_input_details() # inputs + output_details = interpreter.get_output_details() # outputs + elif tfjs: + raise Exception("ERROR: YOLOv5 TF.js inference is not supported") + self.__dict__.update(locals()) # assign all variables to self + + def forward(self, im, augment=False, visualize=False, val=False): + # YOLOv5 MultiBackend inference + b, ch, h, w = im.shape # batch, channel, height, width + if self.pt or self.jit: # PyTorch + y = self.model(im) if self.jit else self.model(im, augment=augment, visualize=visualize) + return y if val else y[0] + elif self.dnn: # ONNX OpenCV DNN + im = im.cpu().numpy() # torch to numpy + self.net.setInput(im) + y = self.net.forward() + elif self.onnx: # ONNX Runtime + im = im.cpu().numpy() # torch to numpy + y = self.session.run([self.session.get_outputs()[0].name], {self.session.get_inputs()[0].name: im})[0] + elif self.xml: # OpenVINO + im = im.cpu().numpy() # FP32 + desc = self.ie.TensorDesc(precision="FP32", dims=im.shape, layout="NCHW") # Tensor Description + request = self.executable_network.requests[0] # inference request + request.set_blob(blob_name="images", blob=self.ie.Blob(desc, im)) # name=next(iter(request.input_blobs)) + request.infer() + y = request.output_blobs["output"].buffer # name=next(iter(request.output_blobs)) + elif self.engine: # TensorRT + assert im.shape == self.bindings["images"].shape, (im.shape, self.bindings["images"].shape) + self.binding_addrs["images"] = int(im.data_ptr()) + self.context.execute_v2(list(self.binding_addrs.values())) + y = self.bindings["output"].data + elif self.coreml: # CoreML + im = im.permute(0, 2, 3, 1).cpu().numpy() # torch BCHW to numpy BHWC shape(1,320,192,3) + im = Image.fromarray((im[0] * 255).astype("uint8")) + # im = im.resize((192, 320), Image.ANTIALIAS) + y = self.model.predict({"image": im}) # coordinates are xywh normalized + if "confidence" in y: + box = xywh2xyxy(y["coordinates"] * [[w, h, w, h]]) # xyxy pixels + conf, cls = y["confidence"].max(1), y["confidence"].argmax(1).astype(np.float) + y = np.concatenate((box, conf.reshape(-1, 1), cls.reshape(-1, 1)), 1) + else: + k = "var_" + str(sorted(int(k.replace("var_", "")) for k in y)[-1]) # output key + y = y[k] # output + else: # TensorFlow (SavedModel, GraphDef, Lite, Edge TPU) + im = im.permute(0, 2, 3, 1).cpu().numpy() # torch BCHW to numpy BHWC shape(1,320,192,3) + if self.saved_model: # SavedModel + y = (self.model(im, training=False) if self.keras else self.model(im)).numpy() + elif self.pb: # GraphDef + y = self.frozen_func(x=self.tf.constant(im)).numpy() + else: # Lite or Edge TPU + input, output = self.input_details[0], self.output_details[0] + int8 = input["dtype"] == np.uint8 # is TFLite quantized uint8 model + if int8: + scale, zero_point = input["quantization"] + im = (im / scale + zero_point).astype(np.uint8) # de-scale + self.interpreter.set_tensor(input["index"], im) + self.interpreter.invoke() + y = self.interpreter.get_tensor(output["index"]) + if int8: + scale, zero_point = output["quantization"] + y = (y.astype(np.float32) - zero_point) * scale # re-scale + y[..., :4] *= [w, h, w, h] # xywh normalized to pixels + + if isinstance(y, np.ndarray): + y = torch.tensor(y, device=self.device) + return (y, []) if val else y + + def warmup(self, imgsz=(1, 3, 640, 640)): + # Warmup model by running inference once + if any((self.pt, self.jit, self.onnx, self.engine, self.saved_model, self.pb)): # warmup types + if self.device.type != "cpu": # only warmup GPU models + im = torch.zeros(*imgsz, dtype=torch.half if self.fp16 else torch.float, device=self.device) # input + for _ in range(2 if self.jit else 1): # + self.forward(im) # warmup + + @staticmethod + def model_type(p="path/to/model.pt"): + # Return model type from model path, i.e. path='path/to/model.onnx' -> type=onnx + from export import export_formats + + suffixes = list(export_formats().Suffix) + [".xml"] # export suffixes + check_suffix(p, suffixes) # checks + p = Path(p).name # eliminate trailing separators + pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, xml2 = (s in p for s in suffixes) + xml |= xml2 # *_openvino_model or *.xml + tflite &= not edgetpu # *.tflite + return pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs + + +class AutoShape(nn.Module): + # YOLOv5 input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS + conf = 0.25 # NMS confidence threshold + iou = 0.45 # NMS IoU threshold + agnostic = False # NMS class-agnostic + multi_label = False # NMS multiple labels per box + classes = None # (optional list) filter by class, i.e. = [0, 15, 16] for COCO persons, cats and dogs + max_det = 1000 # maximum number of detections per image + amp = False # Automatic Mixed Precision (AMP) inference + + def __init__(self, model): + super().__init__() + LOGGER.info("Adding AutoShape... ") + copy_attr(self, model, include=("yaml", "nc", "hyp", "names", "stride", "abc"), exclude=()) # copy attributes + self.dmb = isinstance(model, DetectMultiBackend) # DetectMultiBackend() instance + self.pt = not self.dmb or model.pt # PyTorch model + self.model = model.eval() + + def _apply(self, fn): + # Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers + self = super()._apply(fn) + if self.pt: + m = self.model.model.model[-1] if self.dmb else self.model.model[-1] # Detect() + m.stride = fn(m.stride) + m.grid = list(map(fn, m.grid)) + if isinstance(m.anchor_grid, list): + m.anchor_grid = list(map(fn, m.anchor_grid)) + return self + + @torch.no_grad() + def forward(self, imgs, size=640, augment=False, profile=False): + # Inference from various sources. For height=640, width=1280, RGB images example inputs are: + # file: imgs = 'data/images/zidane.jpg' # str or PosixPath + # URI: = 'https://ultralytics.com/images/zidane.jpg' + # OpenCV: = cv2.imread('image.jpg')[:,:,::-1] # HWC BGR to RGB x(640,1280,3) + # PIL: = Image.open('image.jpg') or ImageGrab.grab() # HWC x(640,1280,3) + # numpy: = np.zeros((640,1280,3)) # HWC + # torch: = torch.zeros(16,3,320,640) # BCHW (scaled to size=640, 0-1 values) + # multiple: = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...] # list of images + + t = [time_sync()] + p = next(self.model.parameters()) if self.pt else torch.zeros(1) # for device and type + autocast = self.amp and (p.device.type != "cpu") # Automatic Mixed Precision (AMP) inference + if isinstance(imgs, torch.Tensor): # torch + with amp.autocast(enabled=autocast): + return self.model(imgs.to(p.device).type_as(p), augment, profile) # inference + + # Pre-process + n, imgs = (len(imgs), imgs) if isinstance(imgs, list) else (1, [imgs]) # number of images, list of images + shape0, shape1, files = [], [], [] # image and inference shapes, filenames + for i, im in enumerate(imgs): + f = f"image{i}" # filename + if isinstance(im, (str, Path)): # filename or uri + im, f = Image.open(requests.get(im, stream=True).raw if str(im).startswith("http") else im), im + im = np.asarray(exif_transpose(im)) + elif isinstance(im, Image.Image): # PIL Image + im, f = np.asarray(exif_transpose(im)), getattr(im, "filename", f) or f + files.append(Path(f).with_suffix(".jpg").name) + if im.shape[0] < 5: # image in CHW + im = im.transpose((1, 2, 0)) # reverse dataloader .transpose(2, 0, 1) + im = im[..., :3] if im.ndim == 3 else np.tile(im[..., None], 3) # enforce 3ch input + s = im.shape[:2] # HWC + shape0.append(s) # image shape + g = size / max(s) # gain + shape1.append([y * g for y in s]) + imgs[i] = im if im.data.contiguous else np.ascontiguousarray(im) # update + shape1 = [make_divisible(x, self.stride) if self.pt else size for x in np.array(shape1).max(0)] # inf shape + x = [letterbox(im, new_shape=shape1, auto=False)[0] for im in imgs] # pad + x = np.ascontiguousarray(np.array(x).transpose((0, 3, 1, 2))) # stack and BHWC to BCHW + x = torch.from_numpy(x).to(p.device).type_as(p) / 255 # uint8 to fp16/32 + t.append(time_sync()) + + with amp.autocast(enabled=autocast): + # Inference + y = self.model(x, augment, profile) # forward + t.append(time_sync()) + + # Post-process + y = non_max_suppression( + y if self.dmb else y[0], + self.conf, + iou_thres=self.iou, + classes=self.classes, + agnostic=self.agnostic, + multi_label=self.multi_label, + max_det=self.max_det, + ) # NMS + for i in range(n): + scale_coords(shape1, y[i][:, :4], shape0[i]) + + t.append(time_sync()) + return Detections(imgs, y, files, t, self.names, x.shape) + + +class Detections: + # YOLOv5 detections class for inference results + def __init__(self, imgs, pred, files, times=(0, 0, 0, 0), names=None, shape=None): + super().__init__() + d = pred[0].device # device + gn = [torch.tensor([*(im.shape[i] for i in [1, 0, 1, 0]), 1, 1], device=d) for im in imgs] # normalizations + self.imgs = imgs # list of images as numpy arrays + self.pred = pred # list of tensors pred[0] = (xyxy, conf, cls) + self.names = names # class names + self.files = files # image filenames + self.times = times # profiling times + self.xyxy = pred # xyxy pixels + self.xywh = [xyxy2xywh(x) for x in pred] # xywh pixels + self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)] # xyxy normalized + self.xywhn = [x / g for x, g in zip(self.xywh, gn)] # xywh normalized + self.n = len(self.pred) # number of images (batch size) + self.t = tuple((times[i + 1] - times[i]) * 1000 / self.n for i in range(3)) # timestamps (ms) + self.s = shape # inference BCHW shape + + def display(self, pprint=False, show=False, save=False, crop=False, render=False, save_dir=Path("")): + crops = [] + for i, (im, pred) in enumerate(zip(self.imgs, self.pred)): + s = f"image {i + 1}/{len(self.pred)}: {im.shape[0]}x{im.shape[1]} " # string + if pred.shape[0]: + for c in pred[:, -1].unique(): + n = (pred[:, -1] == c).sum() # detections per class + s += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " # add to string + if show or save or render or crop: + annotator = Annotator(im, example=str(self.names)) + for *box, conf, cls in reversed(pred): # xyxy, confidence, class + label = f"{self.names[int(cls)]} {conf:.2f}" + if crop: + file = save_dir / "crops" / self.names[int(cls)] / self.files[i] if save else None + crops.append( + { + "box": box, + "conf": conf, + "cls": cls, + "label": label, + "im": save_one_box(box, im, file=file, save=save), + } + ) + else: # all others + annotator.box_label(box, label, color=colors(cls)) + im = annotator.im + else: + s += "(no detections)" + + im = Image.fromarray(im.astype(np.uint8)) if isinstance(im, np.ndarray) else im # from np + if pprint: + LOGGER.info(s.rstrip(", ")) + if show: + im.show(self.files[i]) # show + if save: + f = self.files[i] + im.save(save_dir / f) # save + if i == self.n - 1: + LOGGER.info(f"Saved {self.n} image{'s' * (self.n > 1)} to {colorstr('bold', save_dir)}") + if render: + self.imgs[i] = np.asarray(im) + if crop: + if save: + LOGGER.info(f"Saved results to {save_dir}\n") + return crops + + def print(self): + self.display(pprint=True) # print results + LOGGER.info( + f"Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {tuple(self.s)}" % self.t + ) + + def show(self): + self.display(show=True) # show results + + def save(self, save_dir="runs/detect/exp"): + save_dir = increment_path(save_dir, exist_ok=save_dir != "runs/detect/exp", mkdir=True) # increment save_dir + self.display(save=True, save_dir=save_dir) # save results + + def crop(self, save=True, save_dir="runs/detect/exp"): + save_dir = increment_path(save_dir, exist_ok=save_dir != "runs/detect/exp", mkdir=True) if save else None + return self.display(crop=True, save=save, save_dir=save_dir) # crop results + + def render(self): + self.display(render=True) # render results + return self.imgs + + def pandas(self): + # return detections as pandas DataFrames, i.e. print(results.pandas().xyxy[0]) + new = copy(self) # return copy + ca = "xmin", "ymin", "xmax", "ymax", "confidence", "class", "name" # xyxy columns + cb = "xcenter", "ycenter", "width", "height", "confidence", "class", "name" # xywh columns + for k, c in zip(["xyxy", "xyxyn", "xywh", "xywhn"], [ca, ca, cb, cb]): + a = [[x[:5] + [int(x[5]), self.names[int(x[5])]] for x in x.tolist()] for x in getattr(self, k)] # update + setattr(new, k, [pd.DataFrame(x, columns=c) for x in a]) + return new + + def tolist(self): + # return a list of Detections objects, i.e. 'for result in results.tolist():' + r = range(self.n) # iterable + x = [Detections([self.imgs[i]], [self.pred[i]], [self.files[i]], self.times, self.names, self.s) for i in r] + # for d in x: + # for k in ['imgs', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']: + # setattr(d, k, getattr(d, k)[0]) # pop out of list + return x + + def __len__(self): + return self.n + + +class Classify(nn.Module): + # Classification head, i.e. x(b,c1,20,20) to x(b,c2) + def __init__(self, c1, c2, k=1, s=1, p=None, g=1): # ch_in, ch_out, kernel, stride, padding, groups + super().__init__() + self.aap = nn.AdaptiveAvgPool2d(1) # to x(b,c1,1,1) + self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g) # to x(b,c2,1,1) + self.flat = nn.Flatten() + + def forward(self, x): + z = torch.cat([self.aap(y) for y in (x if isinstance(x, list) else [x])], 1) # cat if list + return self.flat(self.conv(z)) # flatten to x(b,c2) diff --git a/core/vision/yolov5/models/experimental.py b/core/vision/yolov5/models/experimental.py new file mode 100644 index 00000000..1230f465 --- /dev/null +++ b/core/vision/yolov5/models/experimental.py @@ -0,0 +1,121 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Experimental modules +""" +import math + +import numpy as np +import torch +import torch.nn as nn + +from models.common import Conv +from utils.downloads import attempt_download + + +class CrossConv(nn.Module): + # Cross Convolution Downsample + def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False): + # ch_in, ch_out, kernel, stride, groups, expansion, shortcut + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = Conv(c1, c_, (1, k), (1, s)) + self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g) + self.add = shortcut and c1 == c2 + + def forward(self, x): + return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x)) + + +class Sum(nn.Module): + # Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070 + def __init__(self, n, weight=False): # n: number of inputs + super().__init__() + self.weight = weight # apply weights boolean + self.iter = range(n - 1) # iter object + if weight: + self.w = nn.Parameter(-torch.arange(1.0, n) / 2, requires_grad=True) # layer weights + + def forward(self, x): + y = x[0] # no weight + if self.weight: + w = torch.sigmoid(self.w) * 2 + for i in self.iter: + y = y + x[i + 1] * w[i] + else: + for i in self.iter: + y = y + x[i + 1] + return y + + +class MixConv2d(nn.Module): + # Mixed Depth-wise Conv https://arxiv.org/abs/1907.09595 + def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): # ch_in, ch_out, kernel, stride, ch_strategy + super().__init__() + n = len(k) # number of convolutions + if equal_ch: # equal c_ per group + i = torch.linspace(0, n - 1E-6, c2).floor() # c2 indices + c_ = [(i == g).sum() for g in range(n)] # intermediate channels + else: # equal weight.numel() per group + b = [c2] + [0] * n + a = np.eye(n + 1, n, k=-1) + a -= np.roll(a, 1, axis=1) + a *= np.array(k) ** 2 + a[0] = 1 + c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b + + self.m = nn.ModuleList( + [nn.Conv2d(c1, int(c_), k, s, k // 2, groups=math.gcd(c1, int(c_)), bias=False) for k, c_ in zip(k, c_)]) + self.bn = nn.BatchNorm2d(c2) + self.act = nn.SiLU() + + def forward(self, x): + return self.act(self.bn(torch.cat([m(x) for m in self.m], 1))) + + +class Ensemble(nn.ModuleList): + # Ensemble of models + def __init__(self): + super().__init__() + + def forward(self, x, augment=False, profile=False, visualize=False): + y = [] + for module in self: + y.append(module(x, augment, profile, visualize)[0]) + # y = torch.stack(y).max(0)[0] # max ensemble + # y = torch.stack(y).mean(0) # mean ensemble + y = torch.cat(y, 1) # nms ensemble + return y, None # inference, train output + + +def attempt_load(weights, map_location=None, inplace=True, fuse=True): + from models.yolo import Detect, Model + + # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a + model = Ensemble() + for w in weights if isinstance(weights, list) else [weights]: + ckpt = torch.load(attempt_download(w), map_location=map_location) # load + ckpt = (ckpt.get('ema') or ckpt['model']).float() # FP32 model + model.append(ckpt.fuse().eval() if fuse else ckpt.eval()) # fused or un-fused model in eval mode + + # Compatibility updates + for m in model.modules(): + t = type(m) + if t in (nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model): + m.inplace = inplace # torch 1.7.0 compatibility + if t is Detect: + if not isinstance(m.anchor_grid, list): # new Detect Layer compatibility + delattr(m, 'anchor_grid') + setattr(m, 'anchor_grid', [torch.zeros(1)] * m.nl) + elif t is Conv: + m._non_persistent_buffers_set = set() # torch 1.6.0 compatibility + elif t is nn.Upsample and not hasattr(m, 'recompute_scale_factor'): + m.recompute_scale_factor = None # torch 1.11.0 compatibility + + if len(model) == 1: + return model[-1] # return model + else: + print(f'Ensemble created with {weights}\n') + for k in ['names']: + setattr(model, k, getattr(model[-1], k)) + model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride + return model # return ensemble diff --git a/core/vision/yolov5/models/hub/anchors.yaml b/core/vision/yolov5/models/hub/anchors.yaml new file mode 100644 index 00000000..e4d7beb0 --- /dev/null +++ b/core/vision/yolov5/models/hub/anchors.yaml @@ -0,0 +1,59 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# Default anchors for COCO data + + +# P5 ------------------------------------------------------------------------------------------------------------------- +# P5-640: +anchors_p5_640: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + + +# P6 ------------------------------------------------------------------------------------------------------------------- +# P6-640: thr=0.25: 0.9964 BPR, 5.54 anchors past thr, n=12, img_size=640, metric_all=0.281/0.716-mean/best, past_thr=0.469-mean: 9,11, 21,19, 17,41, 43,32, 39,70, 86,64, 65,131, 134,130, 120,265, 282,180, 247,354, 512,387 +anchors_p6_640: + - [9,11, 21,19, 17,41] # P3/8 + - [43,32, 39,70, 86,64] # P4/16 + - [65,131, 134,130, 120,265] # P5/32 + - [282,180, 247,354, 512,387] # P6/64 + +# P6-1280: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1280, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 19,27, 44,40, 38,94, 96,68, 86,152, 180,137, 140,301, 303,264, 238,542, 436,615, 739,380, 925,792 +anchors_p6_1280: + - [19,27, 44,40, 38,94] # P3/8 + - [96,68, 86,152, 180,137] # P4/16 + - [140,301, 303,264, 238,542] # P5/32 + - [436,615, 739,380, 925,792] # P6/64 + +# P6-1920: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1920, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 28,41, 67,59, 57,141, 144,103, 129,227, 270,205, 209,452, 455,396, 358,812, 653,922, 1109,570, 1387,1187 +anchors_p6_1920: + - [28,41, 67,59, 57,141] # P3/8 + - [144,103, 129,227, 270,205] # P4/16 + - [209,452, 455,396, 358,812] # P5/32 + - [653,922, 1109,570, 1387,1187] # P6/64 + + +# P7 ------------------------------------------------------------------------------------------------------------------- +# P7-640: thr=0.25: 0.9962 BPR, 6.76 anchors past thr, n=15, img_size=640, metric_all=0.275/0.733-mean/best, past_thr=0.466-mean: 11,11, 13,30, 29,20, 30,46, 61,38, 39,92, 78,80, 146,66, 79,163, 149,150, 321,143, 157,303, 257,402, 359,290, 524,372 +anchors_p7_640: + - [11,11, 13,30, 29,20] # P3/8 + - [30,46, 61,38, 39,92] # P4/16 + - [78,80, 146,66, 79,163] # P5/32 + - [149,150, 321,143, 157,303] # P6/64 + - [257,402, 359,290, 524,372] # P7/128 + +# P7-1280: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1280, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 19,22, 54,36, 32,77, 70,83, 138,71, 75,173, 165,159, 148,334, 375,151, 334,317, 251,626, 499,474, 750,326, 534,814, 1079,818 +anchors_p7_1280: + - [19,22, 54,36, 32,77] # P3/8 + - [70,83, 138,71, 75,173] # P4/16 + - [165,159, 148,334, 375,151] # P5/32 + - [334,317, 251,626, 499,474] # P6/64 + - [750,326, 534,814, 1079,818] # P7/128 + +# P7-1920: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1920, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 29,34, 81,55, 47,115, 105,124, 207,107, 113,259, 247,238, 222,500, 563,227, 501,476, 376,939, 749,711, 1126,489, 801,1222, 1618,1227 +anchors_p7_1920: + - [29,34, 81,55, 47,115] # P3/8 + - [105,124, 207,107, 113,259] # P4/16 + - [247,238, 222,500, 563,227] # P5/32 + - [501,476, 376,939, 749,711] # P6/64 + - [1126,489, 801,1222, 1618,1227] # P7/128 diff --git a/core/vision/yolov5/models/hub/yolov3-spp.yaml b/core/vision/yolov5/models/hub/yolov3-spp.yaml new file mode 100644 index 00000000..c6698215 --- /dev/null +++ b/core/vision/yolov5/models/hub/yolov3-spp.yaml @@ -0,0 +1,51 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# darknet53 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [32, 3, 1]], # 0 + [-1, 1, Conv, [64, 3, 2]], # 1-P1/2 + [-1, 1, Bottleneck, [64]], + [-1, 1, Conv, [128, 3, 2]], # 3-P2/4 + [-1, 2, Bottleneck, [128]], + [-1, 1, Conv, [256, 3, 2]], # 5-P3/8 + [-1, 8, Bottleneck, [256]], + [-1, 1, Conv, [512, 3, 2]], # 7-P4/16 + [-1, 8, Bottleneck, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 9-P5/32 + [-1, 4, Bottleneck, [1024]], # 10 + ] + +# YOLOv3-SPP head +head: + [[-1, 1, Bottleneck, [1024, False]], + [-1, 1, SPP, [512, [5, 9, 13]]], + [-1, 1, Conv, [1024, 3, 1]], + [-1, 1, Conv, [512, 1, 1]], + [-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large) + + [-2, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 8], 1, Concat, [1]], # cat backbone P4 + [-1, 1, Bottleneck, [512, False]], + [-1, 1, Bottleneck, [512, False]], + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium) + + [-2, 1, Conv, [128, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P3 + [-1, 1, Bottleneck, [256, False]], + [-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small) + + [[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/core/vision/yolov5/models/hub/yolov3-tiny.yaml b/core/vision/yolov5/models/hub/yolov3-tiny.yaml new file mode 100644 index 00000000..b28b4431 --- /dev/null +++ b/core/vision/yolov5/models/hub/yolov3-tiny.yaml @@ -0,0 +1,41 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple +anchors: + - [10,14, 23,27, 37,58] # P4/16 + - [81,82, 135,169, 344,319] # P5/32 + +# YOLOv3-tiny backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [16, 3, 1]], # 0 + [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 1-P1/2 + [-1, 1, Conv, [32, 3, 1]], + [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 3-P2/4 + [-1, 1, Conv, [64, 3, 1]], + [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 5-P3/8 + [-1, 1, Conv, [128, 3, 1]], + [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 7-P4/16 + [-1, 1, Conv, [256, 3, 1]], + [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 9-P5/32 + [-1, 1, Conv, [512, 3, 1]], + [-1, 1, nn.ZeroPad2d, [[0, 1, 0, 1]]], # 11 + [-1, 1, nn.MaxPool2d, [2, 1, 0]], # 12 + ] + +# YOLOv3-tiny head +head: + [[-1, 1, Conv, [1024, 3, 1]], + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, Conv, [512, 3, 1]], # 15 (P5/32-large) + + [-2, 1, Conv, [128, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 8], 1, Concat, [1]], # cat backbone P4 + [-1, 1, Conv, [256, 3, 1]], # 19 (P4/16-medium) + + [[19, 15], 1, Detect, [nc, anchors]], # Detect(P4, P5) + ] diff --git a/core/vision/yolov5/models/hub/yolov3.yaml b/core/vision/yolov5/models/hub/yolov3.yaml new file mode 100644 index 00000000..d1ef9129 --- /dev/null +++ b/core/vision/yolov5/models/hub/yolov3.yaml @@ -0,0 +1,51 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# darknet53 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [32, 3, 1]], # 0 + [-1, 1, Conv, [64, 3, 2]], # 1-P1/2 + [-1, 1, Bottleneck, [64]], + [-1, 1, Conv, [128, 3, 2]], # 3-P2/4 + [-1, 2, Bottleneck, [128]], + [-1, 1, Conv, [256, 3, 2]], # 5-P3/8 + [-1, 8, Bottleneck, [256]], + [-1, 1, Conv, [512, 3, 2]], # 7-P4/16 + [-1, 8, Bottleneck, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 9-P5/32 + [-1, 4, Bottleneck, [1024]], # 10 + ] + +# YOLOv3 head +head: + [[-1, 1, Bottleneck, [1024, False]], + [-1, 1, Conv, [512, 1, 1]], + [-1, 1, Conv, [1024, 3, 1]], + [-1, 1, Conv, [512, 1, 1]], + [-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large) + + [-2, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 8], 1, Concat, [1]], # cat backbone P4 + [-1, 1, Bottleneck, [512, False]], + [-1, 1, Bottleneck, [512, False]], + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium) + + [-2, 1, Conv, [128, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P3 + [-1, 1, Bottleneck, [256, False]], + [-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small) + + [[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/core/vision/yolov5/models/hub/yolov5-bifpn.yaml b/core/vision/yolov5/models/hub/yolov5-bifpn.yaml new file mode 100644 index 00000000..504815f5 --- /dev/null +++ b/core/vision/yolov5/models/hub/yolov5-bifpn.yaml @@ -0,0 +1,48 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 9 + ] + +# YOLOv5 v6.0 BiFPN head +head: + [[-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 13 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 17 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 14, 6], 1, Concat, [1]], # cat P4 <--- BiFPN change + [-1, 3, C3, [512, False]], # 20 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [1024, False]], # 23 (P5/32-large) + + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/core/vision/yolov5/models/hub/yolov5-fpn.yaml b/core/vision/yolov5/models/hub/yolov5-fpn.yaml new file mode 100644 index 00000000..a23e9c6f --- /dev/null +++ b/core/vision/yolov5/models/hub/yolov5-fpn.yaml @@ -0,0 +1,42 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 9 + ] + +# YOLOv5 v6.0 FPN head +head: + [[-1, 3, C3, [1024, False]], # 10 (P5/32-large) + + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 1, Conv, [512, 1, 1]], + [-1, 3, C3, [512, False]], # 14 (P4/16-medium) + + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 1, Conv, [256, 1, 1]], + [-1, 3, C3, [256, False]], # 18 (P3/8-small) + + [[18, 14, 10], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/core/vision/yolov5/models/hub/yolov5-p2.yaml b/core/vision/yolov5/models/hub/yolov5-p2.yaml new file mode 100644 index 00000000..554117dd --- /dev/null +++ b/core/vision/yolov5/models/hub/yolov5-p2.yaml @@ -0,0 +1,54 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple +anchors: 3 # AutoAnchor evolves 3 anchors per P output layer + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 9 + ] + +# YOLOv5 v6.0 head with (P2, P3, P4, P5) outputs +head: + [[-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 13 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 17 (P3/8-small) + + [-1, 1, Conv, [128, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 2], 1, Concat, [1]], # cat backbone P2 + [-1, 1, C3, [128, False]], # 21 (P2/4-xsmall) + + [-1, 1, Conv, [128, 3, 2]], + [[-1, 18], 1, Concat, [1]], # cat head P3 + [-1, 3, C3, [256, False]], # 24 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 14], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 27 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [1024, False]], # 30 (P5/32-large) + + [[21, 24, 27, 30], 1, Detect, [nc, anchors]], # Detect(P2, P3, P4, P5) + ] diff --git a/core/vision/yolov5/models/hub/yolov5-p34.yaml b/core/vision/yolov5/models/hub/yolov5-p34.yaml new file mode 100644 index 00000000..dbf0f850 --- /dev/null +++ b/core/vision/yolov5/models/hub/yolov5-p34.yaml @@ -0,0 +1,41 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 0.33 # model depth multiple +width_multiple: 0.50 # layer channel multiple +anchors: 3 # AutoAnchor evolves 3 anchors per P output layer + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [ [ -1, 1, Conv, [ 64, 6, 2, 2 ] ], # 0-P1/2 + [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 + [ -1, 3, C3, [ 128 ] ], + [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 + [ -1, 6, C3, [ 256 ] ], + [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 + [ -1, 9, C3, [ 512 ] ], + [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 7-P5/32 + [ -1, 3, C3, [ 1024 ] ], + [ -1, 1, SPPF, [ 1024, 5 ] ], # 9 + ] + +# YOLOv5 v6.0 head with (P3, P4) outputs +head: + [ [ -1, 1, Conv, [ 512, 1, 1 ] ], + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], + [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 + [ -1, 3, C3, [ 512, False ] ], # 13 + + [ -1, 1, Conv, [ 256, 1, 1 ] ], + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], + [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 + [ -1, 3, C3, [ 256, False ] ], # 17 (P3/8-small) + + [ -1, 1, Conv, [ 256, 3, 2 ] ], + [ [ -1, 14 ], 1, Concat, [ 1 ] ], # cat head P4 + [ -1, 3, C3, [ 512, False ] ], # 20 (P4/16-medium) + + [ [ 17, 20 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4) + ] diff --git a/core/vision/yolov5/models/hub/yolov5-p6.yaml b/core/vision/yolov5/models/hub/yolov5-p6.yaml new file mode 100644 index 00000000..a17202f2 --- /dev/null +++ b/core/vision/yolov5/models/hub/yolov5-p6.yaml @@ -0,0 +1,56 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple +anchors: 3 # AutoAnchor evolves 3 anchors per P output layer + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [768, 3, 2]], # 7-P5/32 + [-1, 3, C3, [768]], + [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 11 + ] + +# YOLOv5 v6.0 head with (P3, P4, P5, P6) outputs +head: + [[-1, 1, Conv, [768, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 8], 1, Concat, [1]], # cat backbone P5 + [-1, 3, C3, [768, False]], # 15 + + [-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 19 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 23 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 20], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 26 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 16], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [768, False]], # 29 (P5/32-large) + + [-1, 1, Conv, [768, 3, 2]], + [[-1, 12], 1, Concat, [1]], # cat head P6 + [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge) + + [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6) + ] diff --git a/core/vision/yolov5/models/hub/yolov5-p7.yaml b/core/vision/yolov5/models/hub/yolov5-p7.yaml new file mode 100644 index 00000000..edd7d13a --- /dev/null +++ b/core/vision/yolov5/models/hub/yolov5-p7.yaml @@ -0,0 +1,67 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple +anchors: 3 # AutoAnchor evolves 3 anchors per P output layer + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [768, 3, 2]], # 7-P5/32 + [-1, 3, C3, [768]], + [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64 + [-1, 3, C3, [1024]], + [-1, 1, Conv, [1280, 3, 2]], # 11-P7/128 + [-1, 3, C3, [1280]], + [-1, 1, SPPF, [1280, 5]], # 13 + ] + +# YOLOv5 v6.0 head with (P3, P4, P5, P6, P7) outputs +head: + [[-1, 1, Conv, [1024, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 10], 1, Concat, [1]], # cat backbone P6 + [-1, 3, C3, [1024, False]], # 17 + + [-1, 1, Conv, [768, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 8], 1, Concat, [1]], # cat backbone P5 + [-1, 3, C3, [768, False]], # 21 + + [-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 25 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 29 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 26], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 32 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 22], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [768, False]], # 35 (P5/32-large) + + [-1, 1, Conv, [768, 3, 2]], + [[-1, 18], 1, Concat, [1]], # cat head P6 + [-1, 3, C3, [1024, False]], # 38 (P6/64-xlarge) + + [-1, 1, Conv, [1024, 3, 2]], + [[-1, 14], 1, Concat, [1]], # cat head P7 + [-1, 3, C3, [1280, False]], # 41 (P7/128-xxlarge) + + [[29, 32, 35, 38, 41], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6, P7) + ] diff --git a/core/vision/yolov5/models/hub/yolov5-panet.yaml b/core/vision/yolov5/models/hub/yolov5-panet.yaml new file mode 100644 index 00000000..ccfbf900 --- /dev/null +++ b/core/vision/yolov5/models/hub/yolov5-panet.yaml @@ -0,0 +1,48 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 9 + ] + +# YOLOv5 v6.0 PANet head +head: + [[-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 13 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 17 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 14], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 20 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [1024, False]], # 23 (P5/32-large) + + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/core/vision/yolov5/models/hub/yolov5l6.yaml b/core/vision/yolov5/models/hub/yolov5l6.yaml new file mode 100644 index 00000000..632c2cb6 --- /dev/null +++ b/core/vision/yolov5/models/hub/yolov5l6.yaml @@ -0,0 +1,60 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple +anchors: + - [19,27, 44,40, 38,94] # P3/8 + - [96,68, 86,152, 180,137] # P4/16 + - [140,301, 303,264, 238,542] # P5/32 + - [436,615, 739,380, 925,792] # P6/64 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [768, 3, 2]], # 7-P5/32 + [-1, 3, C3, [768]], + [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 11 + ] + +# YOLOv5 v6.0 head +head: + [[-1, 1, Conv, [768, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 8], 1, Concat, [1]], # cat backbone P5 + [-1, 3, C3, [768, False]], # 15 + + [-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 19 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 23 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 20], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 26 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 16], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [768, False]], # 29 (P5/32-large) + + [-1, 1, Conv, [768, 3, 2]], + [[-1, 12], 1, Concat, [1]], # cat head P6 + [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge) + + [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6) + ] diff --git a/core/vision/yolov5/models/hub/yolov5m6.yaml b/core/vision/yolov5/models/hub/yolov5m6.yaml new file mode 100644 index 00000000..ecc53fd6 --- /dev/null +++ b/core/vision/yolov5/models/hub/yolov5m6.yaml @@ -0,0 +1,60 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 0.67 # model depth multiple +width_multiple: 0.75 # layer channel multiple +anchors: + - [19,27, 44,40, 38,94] # P3/8 + - [96,68, 86,152, 180,137] # P4/16 + - [140,301, 303,264, 238,542] # P5/32 + - [436,615, 739,380, 925,792] # P6/64 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [768, 3, 2]], # 7-P5/32 + [-1, 3, C3, [768]], + [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 11 + ] + +# YOLOv5 v6.0 head +head: + [[-1, 1, Conv, [768, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 8], 1, Concat, [1]], # cat backbone P5 + [-1, 3, C3, [768, False]], # 15 + + [-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 19 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 23 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 20], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 26 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 16], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [768, False]], # 29 (P5/32-large) + + [-1, 1, Conv, [768, 3, 2]], + [[-1, 12], 1, Concat, [1]], # cat head P6 + [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge) + + [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6) + ] diff --git a/core/vision/yolov5/models/hub/yolov5n6.yaml b/core/vision/yolov5/models/hub/yolov5n6.yaml new file mode 100644 index 00000000..0c0c71d3 --- /dev/null +++ b/core/vision/yolov5/models/hub/yolov5n6.yaml @@ -0,0 +1,60 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 0.33 # model depth multiple +width_multiple: 0.25 # layer channel multiple +anchors: + - [19,27, 44,40, 38,94] # P3/8 + - [96,68, 86,152, 180,137] # P4/16 + - [140,301, 303,264, 238,542] # P5/32 + - [436,615, 739,380, 925,792] # P6/64 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [768, 3, 2]], # 7-P5/32 + [-1, 3, C3, [768]], + [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 11 + ] + +# YOLOv5 v6.0 head +head: + [[-1, 1, Conv, [768, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 8], 1, Concat, [1]], # cat backbone P5 + [-1, 3, C3, [768, False]], # 15 + + [-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 19 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 23 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 20], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 26 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 16], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [768, False]], # 29 (P5/32-large) + + [-1, 1, Conv, [768, 3, 2]], + [[-1, 12], 1, Concat, [1]], # cat head P6 + [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge) + + [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6) + ] diff --git a/core/vision/yolov5/models/hub/yolov5s-ghost.yaml b/core/vision/yolov5/models/hub/yolov5s-ghost.yaml new file mode 100644 index 00000000..ff9519c3 --- /dev/null +++ b/core/vision/yolov5/models/hub/yolov5s-ghost.yaml @@ -0,0 +1,48 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 0.33 # model depth multiple +width_multiple: 0.50 # layer channel multiple +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, GhostConv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3Ghost, [128]], + [-1, 1, GhostConv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3Ghost, [256]], + [-1, 1, GhostConv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3Ghost, [512]], + [-1, 1, GhostConv, [1024, 3, 2]], # 7-P5/32 + [-1, 3, C3Ghost, [1024]], + [-1, 1, SPPF, [1024, 5]], # 9 + ] + +# YOLOv5 v6.0 head +head: + [[-1, 1, GhostConv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3Ghost, [512, False]], # 13 + + [-1, 1, GhostConv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3Ghost, [256, False]], # 17 (P3/8-small) + + [-1, 1, GhostConv, [256, 3, 2]], + [[-1, 14], 1, Concat, [1]], # cat head P4 + [-1, 3, C3Ghost, [512, False]], # 20 (P4/16-medium) + + [-1, 1, GhostConv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, C3Ghost, [1024, False]], # 23 (P5/32-large) + + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/core/vision/yolov5/models/hub/yolov5s-transformer.yaml b/core/vision/yolov5/models/hub/yolov5s-transformer.yaml new file mode 100644 index 00000000..100d7c44 --- /dev/null +++ b/core/vision/yolov5/models/hub/yolov5s-transformer.yaml @@ -0,0 +1,48 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 0.33 # model depth multiple +width_multiple: 0.50 # layer channel multiple +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 3, C3TR, [1024]], # 9 <--- C3TR() Transformer module + [-1, 1, SPPF, [1024, 5]], # 9 + ] + +# YOLOv5 v6.0 head +head: + [[-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 13 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 17 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 14], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 20 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [1024, False]], # 23 (P5/32-large) + + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/core/vision/yolov5/models/hub/yolov5s6.yaml b/core/vision/yolov5/models/hub/yolov5s6.yaml new file mode 100644 index 00000000..a28fb559 --- /dev/null +++ b/core/vision/yolov5/models/hub/yolov5s6.yaml @@ -0,0 +1,60 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 0.33 # model depth multiple +width_multiple: 0.50 # layer channel multiple +anchors: + - [19,27, 44,40, 38,94] # P3/8 + - [96,68, 86,152, 180,137] # P4/16 + - [140,301, 303,264, 238,542] # P5/32 + - [436,615, 739,380, 925,792] # P6/64 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [768, 3, 2]], # 7-P5/32 + [-1, 3, C3, [768]], + [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 11 + ] + +# YOLOv5 v6.0 head +head: + [[-1, 1, Conv, [768, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 8], 1, Concat, [1]], # cat backbone P5 + [-1, 3, C3, [768, False]], # 15 + + [-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 19 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 23 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 20], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 26 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 16], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [768, False]], # 29 (P5/32-large) + + [-1, 1, Conv, [768, 3, 2]], + [[-1, 12], 1, Concat, [1]], # cat head P6 + [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge) + + [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6) + ] diff --git a/core/vision/yolov5/models/hub/yolov5x6.yaml b/core/vision/yolov5/models/hub/yolov5x6.yaml new file mode 100644 index 00000000..ba795c4a --- /dev/null +++ b/core/vision/yolov5/models/hub/yolov5x6.yaml @@ -0,0 +1,60 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 1.33 # model depth multiple +width_multiple: 1.25 # layer channel multiple +anchors: + - [19,27, 44,40, 38,94] # P3/8 + - [96,68, 86,152, 180,137] # P4/16 + - [140,301, 303,264, 238,542] # P5/32 + - [436,615, 739,380, 925,792] # P6/64 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [768, 3, 2]], # 7-P5/32 + [-1, 3, C3, [768]], + [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 11 + ] + +# YOLOv5 v6.0 head +head: + [[-1, 1, Conv, [768, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 8], 1, Concat, [1]], # cat backbone P5 + [-1, 3, C3, [768, False]], # 15 + + [-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 19 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 23 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 20], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 26 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 16], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [768, False]], # 29 (P5/32-large) + + [-1, 1, Conv, [768, 3, 2]], + [[-1, 12], 1, Concat, [1]], # cat head P6 + [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge) + + [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6) + ] diff --git a/core/vision/yolov5/models/tf.py b/core/vision/yolov5/models/tf.py new file mode 100644 index 00000000..728907f8 --- /dev/null +++ b/core/vision/yolov5/models/tf.py @@ -0,0 +1,466 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +TensorFlow, Keras and TFLite versions of YOLOv5 +Authored by https://github.com/zldrobit in PR https://github.com/ultralytics/yolov5/pull/1127 + +Usage: + $ python models/tf.py --weights yolov5s.pt + +Export: + $ python path/to/export.py --weights yolov5s.pt --include saved_model pb tflite tfjs +""" + +import argparse +import sys +from copy import deepcopy +from pathlib import Path + +FILE = Path(__file__).resolve() +ROOT = FILE.parents[1] # YOLOv5 root directory +if str(ROOT) not in sys.path: + sys.path.append(str(ROOT)) # add ROOT to PATH +# ROOT = ROOT.relative_to(Path.cwd()) # relative + +import numpy as np +import tensorflow as tf +import torch +import torch.nn as nn +from tensorflow import keras + +from models.common import C3, SPP, SPPF, Bottleneck, BottleneckCSP, Concat, Conv, DWConv, Focus, autopad +from models.experimental import CrossConv, MixConv2d, attempt_load +from models.yolo import Detect +from utils.activations import SiLU +from utils.general import LOGGER, make_divisible, print_args + + +class TFBN(keras.layers.Layer): + # TensorFlow BatchNormalization wrapper + def __init__(self, w=None): + super().__init__() + self.bn = keras.layers.BatchNormalization( + beta_initializer=keras.initializers.Constant(w.bias.numpy()), + gamma_initializer=keras.initializers.Constant(w.weight.numpy()), + moving_mean_initializer=keras.initializers.Constant(w.running_mean.numpy()), + moving_variance_initializer=keras.initializers.Constant(w.running_var.numpy()), + epsilon=w.eps) + + def call(self, inputs): + return self.bn(inputs) + + +class TFPad(keras.layers.Layer): + def __init__(self, pad): + super().__init__() + self.pad = tf.constant([[0, 0], [pad, pad], [pad, pad], [0, 0]]) + + def call(self, inputs): + return tf.pad(inputs, self.pad, mode='constant', constant_values=0) + + +class TFConv(keras.layers.Layer): + # Standard convolution + def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None): + # ch_in, ch_out, weights, kernel, stride, padding, groups + super().__init__() + assert g == 1, "TF v2.2 Conv2D does not support 'groups' argument" + assert isinstance(k, int), "Convolution with multiple kernels are not allowed." + # TensorFlow convolution padding is inconsistent with PyTorch (e.g. k=3 s=2 'SAME' padding) + # see https://stackoverflow.com/questions/52975843/comparing-conv2d-with-padding-between-tensorflow-and-pytorch + + conv = keras.layers.Conv2D( + c2, k, s, 'SAME' if s == 1 else 'VALID', use_bias=False if hasattr(w, 'bn') else True, + kernel_initializer=keras.initializers.Constant(w.conv.weight.permute(2, 3, 1, 0).numpy()), + bias_initializer='zeros' if hasattr(w, 'bn') else keras.initializers.Constant(w.conv.bias.numpy())) + self.conv = conv if s == 1 else keras.Sequential([TFPad(autopad(k, p)), conv]) + self.bn = TFBN(w.bn) if hasattr(w, 'bn') else tf.identity + + # YOLOv5 activations + if isinstance(w.act, nn.LeakyReLU): + self.act = (lambda x: keras.activations.relu(x, alpha=0.1)) if act else tf.identity + elif isinstance(w.act, nn.Hardswish): + self.act = (lambda x: x * tf.nn.relu6(x + 3) * 0.166666667) if act else tf.identity + elif isinstance(w.act, (nn.SiLU, SiLU)): + self.act = (lambda x: keras.activations.swish(x)) if act else tf.identity + else: + raise Exception(f'no matching TensorFlow activation found for {w.act}') + + def call(self, inputs): + return self.act(self.bn(self.conv(inputs))) + + +class TFFocus(keras.layers.Layer): + # Focus wh information into c-space + def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None): + # ch_in, ch_out, kernel, stride, padding, groups + super().__init__() + self.conv = TFConv(c1 * 4, c2, k, s, p, g, act, w.conv) + + def call(self, inputs): # x(b,w,h,c) -> y(b,w/2,h/2,4c) + # inputs = inputs / 255 # normalize 0-255 to 0-1 + return self.conv(tf.concat([inputs[:, ::2, ::2, :], + inputs[:, 1::2, ::2, :], + inputs[:, ::2, 1::2, :], + inputs[:, 1::2, 1::2, :]], 3)) + + +class TFBottleneck(keras.layers.Layer): + # Standard bottleneck + def __init__(self, c1, c2, shortcut=True, g=1, e=0.5, w=None): # ch_in, ch_out, shortcut, groups, expansion + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1) + self.cv2 = TFConv(c_, c2, 3, 1, g=g, w=w.cv2) + self.add = shortcut and c1 == c2 + + def call(self, inputs): + return inputs + self.cv2(self.cv1(inputs)) if self.add else self.cv2(self.cv1(inputs)) + + +class TFConv2d(keras.layers.Layer): + # Substitution for PyTorch nn.Conv2D + def __init__(self, c1, c2, k, s=1, g=1, bias=True, w=None): + super().__init__() + assert g == 1, "TF v2.2 Conv2D does not support 'groups' argument" + self.conv = keras.layers.Conv2D( + c2, k, s, 'VALID', use_bias=bias, + kernel_initializer=keras.initializers.Constant(w.weight.permute(2, 3, 1, 0).numpy()), + bias_initializer=keras.initializers.Constant(w.bias.numpy()) if bias else None, ) + + def call(self, inputs): + return self.conv(inputs) + + +class TFBottleneckCSP(keras.layers.Layer): + # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None): + # ch_in, ch_out, number, shortcut, groups, expansion + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1) + self.cv2 = TFConv2d(c1, c_, 1, 1, bias=False, w=w.cv2) + self.cv3 = TFConv2d(c_, c_, 1, 1, bias=False, w=w.cv3) + self.cv4 = TFConv(2 * c_, c2, 1, 1, w=w.cv4) + self.bn = TFBN(w.bn) + self.act = lambda x: keras.activations.relu(x, alpha=0.1) + self.m = keras.Sequential([TFBottleneck(c_, c_, shortcut, g, e=1.0, w=w.m[j]) for j in range(n)]) + + def call(self, inputs): + y1 = self.cv3(self.m(self.cv1(inputs))) + y2 = self.cv2(inputs) + return self.cv4(self.act(self.bn(tf.concat((y1, y2), axis=3)))) + + +class TFC3(keras.layers.Layer): + # CSP Bottleneck with 3 convolutions + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None): + # ch_in, ch_out, number, shortcut, groups, expansion + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1) + self.cv2 = TFConv(c1, c_, 1, 1, w=w.cv2) + self.cv3 = TFConv(2 * c_, c2, 1, 1, w=w.cv3) + self.m = keras.Sequential([TFBottleneck(c_, c_, shortcut, g, e=1.0, w=w.m[j]) for j in range(n)]) + + def call(self, inputs): + return self.cv3(tf.concat((self.m(self.cv1(inputs)), self.cv2(inputs)), axis=3)) + + +class TFSPP(keras.layers.Layer): + # Spatial pyramid pooling layer used in YOLOv3-SPP + def __init__(self, c1, c2, k=(5, 9, 13), w=None): + super().__init__() + c_ = c1 // 2 # hidden channels + self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1) + self.cv2 = TFConv(c_ * (len(k) + 1), c2, 1, 1, w=w.cv2) + self.m = [keras.layers.MaxPool2D(pool_size=x, strides=1, padding='SAME') for x in k] + + def call(self, inputs): + x = self.cv1(inputs) + return self.cv2(tf.concat([x] + [m(x) for m in self.m], 3)) + + +class TFSPPF(keras.layers.Layer): + # Spatial pyramid pooling-Fast layer + def __init__(self, c1, c2, k=5, w=None): + super().__init__() + c_ = c1 // 2 # hidden channels + self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1) + self.cv2 = TFConv(c_ * 4, c2, 1, 1, w=w.cv2) + self.m = keras.layers.MaxPool2D(pool_size=k, strides=1, padding='SAME') + + def call(self, inputs): + x = self.cv1(inputs) + y1 = self.m(x) + y2 = self.m(y1) + return self.cv2(tf.concat([x, y1, y2, self.m(y2)], 3)) + + +class TFDetect(keras.layers.Layer): + def __init__(self, nc=80, anchors=(), ch=(), imgsz=(640, 640), w=None): # detection layer + super().__init__() + self.stride = tf.convert_to_tensor(w.stride.numpy(), dtype=tf.float32) + self.nc = nc # number of classes + self.no = nc + 5 # number of outputs per anchor + self.nl = len(anchors) # number of detection layers + self.na = len(anchors[0]) // 2 # number of anchors + self.grid = [tf.zeros(1)] * self.nl # init grid + self.anchors = tf.convert_to_tensor(w.anchors.numpy(), dtype=tf.float32) + self.anchor_grid = tf.reshape(self.anchors * tf.reshape(self.stride, [self.nl, 1, 1]), + [self.nl, 1, -1, 1, 2]) + self.m = [TFConv2d(x, self.no * self.na, 1, w=w.m[i]) for i, x in enumerate(ch)] + self.training = False # set to False after building model + self.imgsz = imgsz + for i in range(self.nl): + ny, nx = self.imgsz[0] // self.stride[i], self.imgsz[1] // self.stride[i] + self.grid[i] = self._make_grid(nx, ny) + + def call(self, inputs): + z = [] # inference output + x = [] + for i in range(self.nl): + x.append(self.m[i](inputs[i])) + # x(bs,20,20,255) to x(bs,3,20,20,85) + ny, nx = self.imgsz[0] // self.stride[i], self.imgsz[1] // self.stride[i] + x[i] = tf.reshape(x[i], [-1, ny * nx, self.na, self.no]) + + if not self.training: # inference + y = tf.sigmoid(x[i]) + grid = tf.transpose(self.grid[i], [0, 2, 1, 3]) - 0.5 + anchor_grid = tf.transpose(self.anchor_grid[i], [0, 2, 1, 3]) * 4 + xy = (y[..., 0:2] * 2 + grid) * self.stride[i] # xy + wh = y[..., 2:4] ** 2 * anchor_grid + # Normalize xywh to 0-1 to reduce calibration error + xy /= tf.constant([[self.imgsz[1], self.imgsz[0]]], dtype=tf.float32) + wh /= tf.constant([[self.imgsz[1], self.imgsz[0]]], dtype=tf.float32) + y = tf.concat([xy, wh, y[..., 4:]], -1) + z.append(tf.reshape(y, [-1, self.na * ny * nx, self.no])) + + return tf.transpose(x, [0, 2, 1, 3]) if self.training else (tf.concat(z, 1), x) + + @staticmethod + def _make_grid(nx=20, ny=20): + # yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)]) + # return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float() + xv, yv = tf.meshgrid(tf.range(nx), tf.range(ny)) + return tf.cast(tf.reshape(tf.stack([xv, yv], 2), [1, 1, ny * nx, 2]), dtype=tf.float32) + + +class TFUpsample(keras.layers.Layer): + def __init__(self, size, scale_factor, mode, w=None): # warning: all arguments needed including 'w' + super().__init__() + assert scale_factor == 2, "scale_factor must be 2" + self.upsample = lambda x: tf.image.resize(x, (x.shape[1] * 2, x.shape[2] * 2), method=mode) + # self.upsample = keras.layers.UpSampling2D(size=scale_factor, interpolation=mode) + # with default arguments: align_corners=False, half_pixel_centers=False + # self.upsample = lambda x: tf.raw_ops.ResizeNearestNeighbor(images=x, + # size=(x.shape[1] * 2, x.shape[2] * 2)) + + def call(self, inputs): + return self.upsample(inputs) + + +class TFConcat(keras.layers.Layer): + def __init__(self, dimension=1, w=None): + super().__init__() + assert dimension == 1, "convert only NCHW to NHWC concat" + self.d = 3 + + def call(self, inputs): + return tf.concat(inputs, self.d) + + +def parse_model(d, ch, model, imgsz): # model_dict, input_channels(3) + LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}") + anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple'] + na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors + no = na * (nc + 5) # number of outputs = anchors * (classes + 5) + + layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out + for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args + m_str = m + m = eval(m) if isinstance(m, str) else m # eval strings + for j, a in enumerate(args): + try: + args[j] = eval(a) if isinstance(a, str) else a # eval strings + except NameError: + pass + + n = max(round(n * gd), 1) if n > 1 else n # depth gain + if m in [nn.Conv2d, Conv, Bottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv, BottleneckCSP, C3]: + c1, c2 = ch[f], args[0] + c2 = make_divisible(c2 * gw, 8) if c2 != no else c2 + + args = [c1, c2, *args[1:]] + if m in [BottleneckCSP, C3]: + args.insert(2, n) + n = 1 + elif m is nn.BatchNorm2d: + args = [ch[f]] + elif m is Concat: + c2 = sum(ch[-1 if x == -1 else x + 1] for x in f) + elif m is Detect: + args.append([ch[x + 1] for x in f]) + if isinstance(args[1], int): # number of anchors + args[1] = [list(range(args[1] * 2))] * len(f) + args.append(imgsz) + else: + c2 = ch[f] + + tf_m = eval('TF' + m_str.replace('nn.', '')) + m_ = keras.Sequential([tf_m(*args, w=model.model[i][j]) for j in range(n)]) if n > 1 \ + else tf_m(*args, w=model.model[i]) # module + + torch_m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module + t = str(m)[8:-2].replace('__main__.', '') # module type + np = sum(x.numel() for x in torch_m_.parameters()) # number params + m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params + LOGGER.info(f'{i:>3}{str(f):>18}{str(n):>3}{np:>10} {t:<40}{str(args):<30}') # print + save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist + layers.append(m_) + ch.append(c2) + return keras.Sequential(layers), sorted(save) + + +class TFModel: + def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, model=None, imgsz=(640, 640)): # model, channels, classes + super().__init__() + if isinstance(cfg, dict): + self.yaml = cfg # model dict + else: # is *.yaml + import yaml # for torch hub + self.yaml_file = Path(cfg).name + with open(cfg) as f: + self.yaml = yaml.load(f, Loader=yaml.FullLoader) # model dict + + # Define model + if nc and nc != self.yaml['nc']: + LOGGER.info(f"Overriding {cfg} nc={self.yaml['nc']} with nc={nc}") + self.yaml['nc'] = nc # override yaml value + self.model, self.savelist = parse_model(deepcopy(self.yaml), ch=[ch], model=model, imgsz=imgsz) + + def predict(self, inputs, tf_nms=False, agnostic_nms=False, topk_per_class=100, topk_all=100, iou_thres=0.45, + conf_thres=0.25): + y = [] # outputs + x = inputs + for i, m in enumerate(self.model.layers): + if m.f != -1: # if not from previous layer + x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers + + x = m(x) # run + y.append(x if m.i in self.savelist else None) # save output + + # Add TensorFlow NMS + if tf_nms: + boxes = self._xywh2xyxy(x[0][..., :4]) + probs = x[0][:, :, 4:5] + classes = x[0][:, :, 5:] + scores = probs * classes + if agnostic_nms: + nms = AgnosticNMS()((boxes, classes, scores), topk_all, iou_thres, conf_thres) + return nms, x[1] + else: + boxes = tf.expand_dims(boxes, 2) + nms = tf.image.combined_non_max_suppression( + boxes, scores, topk_per_class, topk_all, iou_thres, conf_thres, clip_boxes=False) + return nms, x[1] + + return x[0] # output only first tensor [1,6300,85] = [xywh, conf, class0, class1, ...] + # x = x[0][0] # [x(1,6300,85), ...] to x(6300,85) + # xywh = x[..., :4] # x(6300,4) boxes + # conf = x[..., 4:5] # x(6300,1) confidences + # cls = tf.reshape(tf.cast(tf.argmax(x[..., 5:], axis=1), tf.float32), (-1, 1)) # x(6300,1) classes + # return tf.concat([conf, cls, xywh], 1) + + @staticmethod + def _xywh2xyxy(xywh): + # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right + x, y, w, h = tf.split(xywh, num_or_size_splits=4, axis=-1) + return tf.concat([x - w / 2, y - h / 2, x + w / 2, y + h / 2], axis=-1) + + +class AgnosticNMS(keras.layers.Layer): + # TF Agnostic NMS + def call(self, input, topk_all, iou_thres, conf_thres): + # wrap map_fn to avoid TypeSpec related error https://stackoverflow.com/a/65809989/3036450 + return tf.map_fn(lambda x: self._nms(x, topk_all, iou_thres, conf_thres), input, + fn_output_signature=(tf.float32, tf.float32, tf.float32, tf.int32), + name='agnostic_nms') + + @staticmethod + def _nms(x, topk_all=100, iou_thres=0.45, conf_thres=0.25): # agnostic NMS + boxes, classes, scores = x + class_inds = tf.cast(tf.argmax(classes, axis=-1), tf.float32) + scores_inp = tf.reduce_max(scores, -1) + selected_inds = tf.image.non_max_suppression( + boxes, scores_inp, max_output_size=topk_all, iou_threshold=iou_thres, score_threshold=conf_thres) + selected_boxes = tf.gather(boxes, selected_inds) + padded_boxes = tf.pad(selected_boxes, + paddings=[[0, topk_all - tf.shape(selected_boxes)[0]], [0, 0]], + mode="CONSTANT", constant_values=0.0) + selected_scores = tf.gather(scores_inp, selected_inds) + padded_scores = tf.pad(selected_scores, + paddings=[[0, topk_all - tf.shape(selected_boxes)[0]]], + mode="CONSTANT", constant_values=-1.0) + selected_classes = tf.gather(class_inds, selected_inds) + padded_classes = tf.pad(selected_classes, + paddings=[[0, topk_all - tf.shape(selected_boxes)[0]]], + mode="CONSTANT", constant_values=-1.0) + valid_detections = tf.shape(selected_inds)[0] + return padded_boxes, padded_scores, padded_classes, valid_detections + + +def representative_dataset_gen(dataset, ncalib=100): + # Representative dataset generator for use with converter.representative_dataset, returns a generator of np arrays + for n, (path, img, im0s, vid_cap, string) in enumerate(dataset): + input = np.transpose(img, [1, 2, 0]) + input = np.expand_dims(input, axis=0).astype(np.float32) + input /= 255 + yield [input] + if n >= ncalib: + break + + +def run(weights=ROOT / 'yolov5s.pt', # weights path + imgsz=(640, 640), # inference size h,w + batch_size=1, # batch size + dynamic=False, # dynamic batch size + ): + # PyTorch model + im = torch.zeros((batch_size, 3, *imgsz)) # BCHW image + model = attempt_load(weights, map_location=torch.device('cpu'), inplace=True, fuse=False) + _ = model(im) # inference + model.info() + + # TensorFlow model + im = tf.zeros((batch_size, *imgsz, 3)) # BHWC image + tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz) + _ = tf_model.predict(im) # inference + + # Keras model + im = keras.Input(shape=(*imgsz, 3), batch_size=None if dynamic else batch_size) + keras_model = keras.Model(inputs=im, outputs=tf_model.predict(im)) + keras_model.summary() + + LOGGER.info('PyTorch, TensorFlow and Keras models successfully verified.\nUse export.py for TF model export.') + + +def parse_opt(): + parser = argparse.ArgumentParser() + parser.add_argument('--weights', type=str, default=ROOT / 'yolov5s.pt', help='weights path') + parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w') + parser.add_argument('--batch-size', type=int, default=1, help='batch size') + parser.add_argument('--dynamic', action='store_true', help='dynamic batch size') + opt = parser.parse_args() + opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand + print_args(FILE.stem, opt) + return opt + + +def main(opt): + run(**vars(opt)) + + +if __name__ == "__main__": + opt = parse_opt() + main(opt) diff --git a/core/vision/yolov5/models/yolo.py b/core/vision/yolov5/models/yolo.py new file mode 100644 index 00000000..09215101 --- /dev/null +++ b/core/vision/yolov5/models/yolo.py @@ -0,0 +1,330 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +YOLO-specific modules + +Usage: + $ python path/to/models/yolo.py --cfg yolov5s.yaml +""" + +import argparse +import sys +from copy import deepcopy +from pathlib import Path + +FILE = Path(__file__).resolve() +ROOT = FILE.parents[1] # YOLOv5 root directory +if str(ROOT) not in sys.path: + sys.path.append(str(ROOT)) # add ROOT to PATH +# ROOT = ROOT.relative_to(Path.cwd()) # relative + +from models.common import * +from models.experimental import * +from utils.autoanchor import check_anchor_order +from utils.general import LOGGER, check_version, check_yaml, make_divisible, print_args +from utils.plots import feature_visualization +from utils.torch_utils import fuse_conv_and_bn, initialize_weights, model_info, scale_img, select_device, time_sync + +try: + import thop # for FLOPs computation +except ImportError: + thop = None + + +class Detect(nn.Module): + stride = None # strides computed during build + onnx_dynamic = False # ONNX export parameter + + def __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detection layer + super().__init__() + self.nc = nc # number of classes + self.no = nc + 5 # number of outputs per anchor + self.nl = len(anchors) # number of detection layers + self.na = len(anchors[0]) // 2 # number of anchors + self.grid = [torch.zeros(1)] * self.nl # init grid + self.anchor_grid = [torch.zeros(1)] * self.nl # init anchor grid + self.register_buffer('anchors', torch.tensor(anchors).float().view(self.nl, -1, 2)) # shape(nl,na,2) + self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv + self.inplace = inplace # use in-place ops (e.g. slice assignment) + + def forward(self, x): + z = [] # inference output + for i in range(self.nl): + x[i] = self.m[i](x[i]) # conv + bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85) + x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous() + + if not self.training: # inference + if self.onnx_dynamic or self.grid[i].shape[2:4] != x[i].shape[2:4]: + self.grid[i], self.anchor_grid[i] = self._make_grid(nx, ny, i) + + y = x[i].sigmoid() + if self.inplace: + y[..., 0:2] = (y[..., 0:2] * 2 - 0.5 + self.grid[i]) * self.stride[i] # xy + y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh + else: # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953 + xy, wh, conf = y.tensor_split((2, 4), 4) + xy = (xy * 2 - 0.5 + self.grid[i]) * self.stride[i] # xy + wh = (wh * 2) ** 2 * self.anchor_grid[i] # wh + y = torch.cat((xy, wh, conf), 4) + z.append(y.view(bs, -1, self.no)) + + return x if self.training else (torch.cat(z, 1), x) + + def _make_grid(self, nx=20, ny=20, i=0): + d = self.anchors[i].device + if check_version(torch.__version__, '1.10.0'): # torch>=1.10.0 meshgrid workaround for torch>=0.7 compatibility + yv, xv = torch.meshgrid([torch.arange(ny, device=d), torch.arange(nx, device=d)], indexing='ij') + else: + yv, xv = torch.meshgrid([torch.arange(ny, device=d), torch.arange(nx, device=d)]) + grid = torch.stack((xv, yv), 2).expand((1, self.na, ny, nx, 2)).float() + anchor_grid = (self.anchors[i].clone() * self.stride[i]) \ + .view((1, self.na, 1, 1, 2)).expand((1, self.na, ny, nx, 2)).float() + return grid, anchor_grid + + +class Model(nn.Module): + def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes + super().__init__() + if isinstance(cfg, dict): + self.yaml = cfg # model dict + else: # is *.yaml + import yaml # for torch hub + self.yaml_file = Path(cfg).name + with open(cfg, encoding='ascii', errors='ignore') as f: + self.yaml = yaml.safe_load(f) # model dict + + # Define model + ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels + if nc and nc != self.yaml['nc']: + LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}") + self.yaml['nc'] = nc # override yaml value + if anchors: + LOGGER.info(f'Overriding model.yaml anchors with anchors={anchors}') + self.yaml['anchors'] = round(anchors) # override yaml value + self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist + self.names = [str(i) for i in range(self.yaml['nc'])] # default names + self.inplace = self.yaml.get('inplace', True) + + # Build strides, anchors + m = self.model[-1] # Detect() + if isinstance(m, Detect): + s = 256 # 2x min stride + m.inplace = self.inplace + m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward + check_anchor_order(m) # must be in pixel-space (not grid-space) + m.anchors /= m.stride.view(-1, 1, 1) + self.stride = m.stride + self._initialize_biases() # only run once + + # Init weights, biases + initialize_weights(self) + self.info() + LOGGER.info('') + + def forward(self, x, augment=False, profile=False, visualize=False): + if augment: + return self._forward_augment(x) # augmented inference, None + return self._forward_once(x, profile, visualize) # single-scale inference, train + + def _forward_augment(self, x): + img_size = x.shape[-2:] # height, width + s = [1, 0.83, 0.67] # scales + f = [None, 3, None] # flips (2-ud, 3-lr) + y = [] # outputs + for si, fi in zip(s, f): + xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max())) + yi = self._forward_once(xi)[0] # forward + # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save + yi = self._descale_pred(yi, fi, si, img_size) + y.append(yi) + y = self._clip_augmented(y) # clip augmented tails + return torch.cat(y, 1), None # augmented inference, train + + def _forward_once(self, x, profile=False, visualize=False): + y, dt = [], [] # outputs + for m in self.model: + if m.f != -1: # if not from previous layer + x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers + if profile: + self._profile_one_layer(m, x, dt) + x = m(x) # run + y.append(x if m.i in self.save else None) # save output + if visualize: + feature_visualization(x, m.type, m.i, save_dir=visualize) + return x + + def _descale_pred(self, p, flips, scale, img_size): + # de-scale predictions following augmented inference (inverse operation) + if self.inplace: + p[..., :4] /= scale # de-scale + if flips == 2: + p[..., 1] = img_size[0] - p[..., 1] # de-flip ud + elif flips == 3: + p[..., 0] = img_size[1] - p[..., 0] # de-flip lr + else: + x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale + if flips == 2: + y = img_size[0] - y # de-flip ud + elif flips == 3: + x = img_size[1] - x # de-flip lr + p = torch.cat((x, y, wh, p[..., 4:]), -1) + return p + + def _clip_augmented(self, y): + # Clip YOLOv5 augmented inference tails + nl = self.model[-1].nl # number of detection layers (P3-P5) + g = sum(4 ** x for x in range(nl)) # grid points + e = 1 # exclude layer count + i = (y[0].shape[1] // g) * sum(4 ** x for x in range(e)) # indices + y[0] = y[0][:, :-i] # large + i = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e)) # indices + y[-1] = y[-1][:, i:] # small + return y + + def _profile_one_layer(self, m, x, dt): + c = isinstance(m, Detect) # is final layer, copy input as inplace fix + o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPs + t = time_sync() + for _ in range(10): + m(x.copy() if c else x) + dt.append((time_sync() - t) * 100) + if m == self.model[0]: + LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} {'module'}") + LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}') + if c: + LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total") + + def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency + # https://arxiv.org/abs/1708.02002 section 3.3 + # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1. + m = self.model[-1] # Detect() module + for mi, s in zip(m.m, m.stride): # from + b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85) + b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image) + b.data[:, 5:] += math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # cls + mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True) + + def _print_biases(self): + m = self.model[-1] # Detect() module + for mi in m.m: # from + b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85) + LOGGER.info( + ('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean())) + + # def _print_weights(self): + # for m in self.model.modules(): + # if type(m) is Bottleneck: + # LOGGER.info('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights + + def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers + LOGGER.info('Fusing layers... ') + for m in self.model.modules(): + if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'): + m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv + delattr(m, 'bn') # remove batchnorm + m.forward = m.forward_fuse # update forward + self.info() + return self + + def info(self, verbose=False, img_size=640): # print model information + model_info(self, verbose, img_size) + + def _apply(self, fn): + # Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers + self = super()._apply(fn) + m = self.model[-1] # Detect() + if isinstance(m, Detect): + m.stride = fn(m.stride) + m.grid = list(map(fn, m.grid)) + if isinstance(m.anchor_grid, list): + m.anchor_grid = list(map(fn, m.anchor_grid)) + return self + + +def parse_model(d, ch): # model_dict, input_channels(3) + LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}") + anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple'] + na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors + no = na * (nc + 5) # number of outputs = anchors * (classes + 5) + + layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out + for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args + m = eval(m) if isinstance(m, str) else m # eval strings + for j, a in enumerate(args): + try: + args[j] = eval(a) if isinstance(a, str) else a # eval strings + except NameError: + pass + + n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain + if m in [Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv, + BottleneckCSP, C3, C3TR, C3SPP, C3Ghost]: + c1, c2 = ch[f], args[0] + if c2 != no: # if not output + c2 = make_divisible(c2 * gw, 8) + + args = [c1, c2, *args[1:]] + if m in [BottleneckCSP, C3, C3TR, C3Ghost]: + args.insert(2, n) # number of repeats + n = 1 + elif m is nn.BatchNorm2d: + args = [ch[f]] + elif m is Concat: + c2 = sum(ch[x] for x in f) + elif m is Detect: + args.append([ch[x] for x in f]) + if isinstance(args[1], int): # number of anchors + args[1] = [list(range(args[1] * 2))] * len(f) + elif m is Contract: + c2 = ch[f] * args[0] ** 2 + elif m is Expand: + c2 = ch[f] // args[0] ** 2 + else: + c2 = ch[f] + + m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module + t = str(m)[8:-2].replace('__main__.', '') # module type + np = sum(x.numel() for x in m_.parameters()) # number params + m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params + LOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f} {t:<40}{str(args):<30}') # print + save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist + layers.append(m_) + if i == 0: + ch = [] + ch.append(c2) + return nn.Sequential(*layers), sorted(save) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml') + parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') + parser.add_argument('--profile', action='store_true', help='profile model speed') + parser.add_argument('--test', action='store_true', help='test all yolo*.yaml') + opt = parser.parse_args() + opt.cfg = check_yaml(opt.cfg) # check YAML + print_args(FILE.stem, opt) + device = select_device(opt.device) + + # Create model + model = Model(opt.cfg).to(device) + model.train() + + # Profile + if opt.profile: + img = torch.rand(8 if torch.cuda.is_available() else 1, 3, 640, 640).to(device) + y = model(img, profile=True) + + # Test all models + if opt.test: + for cfg in Path(ROOT / 'models').rglob('yolo*.yaml'): + try: + _ = Model(cfg) + except Exception as e: + print(f'Error in {cfg}: {e}') + + # Tensorboard (not working https://github.com/ultralytics/yolov5/issues/2898) + # from torch.utils.tensorboard import SummaryWriter + # tb_writer = SummaryWriter('.') + # LOGGER.info("Run 'tensorboard --logdir=models' to view tensorboard at http://localhost:6006/") + # tb_writer.add_graph(torch.jit.trace(model, img, strict=False), []) # add model graph diff --git a/core/vision/yolov5/models/yolov5l.yaml b/core/vision/yolov5/models/yolov5l.yaml new file mode 100644 index 00000000..ce8a5de4 --- /dev/null +++ b/core/vision/yolov5/models/yolov5l.yaml @@ -0,0 +1,48 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 9 + ] + +# YOLOv5 v6.0 head +head: + [[-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 13 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 17 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 14], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 20 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [1024, False]], # 23 (P5/32-large) + + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/core/vision/yolov5/models/yolov5m.yaml b/core/vision/yolov5/models/yolov5m.yaml new file mode 100644 index 00000000..ad13ab37 --- /dev/null +++ b/core/vision/yolov5/models/yolov5m.yaml @@ -0,0 +1,48 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 0.67 # model depth multiple +width_multiple: 0.75 # layer channel multiple +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 9 + ] + +# YOLOv5 v6.0 head +head: + [[-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 13 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 17 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 14], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 20 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [1024, False]], # 23 (P5/32-large) + + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/core/vision/yolov5/models/yolov5n.yaml b/core/vision/yolov5/models/yolov5n.yaml new file mode 100644 index 00000000..8a28a40d --- /dev/null +++ b/core/vision/yolov5/models/yolov5n.yaml @@ -0,0 +1,48 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 0.33 # model depth multiple +width_multiple: 0.25 # layer channel multiple +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 9 + ] + +# YOLOv5 v6.0 head +head: + [[-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 13 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 17 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 14], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 20 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [1024, False]], # 23 (P5/32-large) + + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/core/vision/yolov5/models/yolov5s.yaml b/core/vision/yolov5/models/yolov5s.yaml new file mode 100644 index 00000000..f35beabb --- /dev/null +++ b/core/vision/yolov5/models/yolov5s.yaml @@ -0,0 +1,48 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 0.33 # model depth multiple +width_multiple: 0.50 # layer channel multiple +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 9 + ] + +# YOLOv5 v6.0 head +head: + [[-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 13 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 17 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 14], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 20 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [1024, False]], # 23 (P5/32-large) + + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/core/vision/yolov5/models/yolov5x.yaml b/core/vision/yolov5/models/yolov5x.yaml new file mode 100644 index 00000000..f617a027 --- /dev/null +++ b/core/vision/yolov5/models/yolov5x.yaml @@ -0,0 +1,48 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 1.33 # model depth multiple +width_multiple: 1.25 # layer channel multiple +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 9 + ] + +# YOLOv5 v6.0 head +head: + [[-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 13 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 17 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 14], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 20 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [1024, False]], # 23 (P5/32-large) + + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/core/vision/yolov5/requirements.txt b/core/vision/yolov5/requirements.txt new file mode 100644 index 00000000..478ec43e --- /dev/null +++ b/core/vision/yolov5/requirements.txt @@ -0,0 +1,35 @@ +# pip install -r requirements.txt + +# Base ---------------------------------------- +matplotlib>=3.2.2 +numpy>=1.18.5 +opencv-python>=4.1.2 +Pillow>=7.1.2 +PyYAML>=5.3.1 +requests>=2.23.0 +scipy>=1.4.1 +tqdm>=4.41.0 + +# Logging ------------------------------------- +tensorboard>=2.4.1 +# wandb + +# Plotting ------------------------------------ +pandas>=1.1.4 +seaborn>=0.11.0 + +# Export -------------------------------------- +# coremltools>=4.1 # CoreML export +# onnx>=1.9.0 # ONNX export +# onnx-simplifier>=0.3.6 # ONNX simplifier +# scikit-learn==0.19.2 # CoreML quantization +# tensorflow>=2.4.1 # TFLite export +# tensorflowjs>=3.9.0 # TF.js export +# openvino-dev # OpenVINO export + +# Extras -------------------------------------- +# albumentations>=1.0.3 +# Cython # for pycocotools https://github.com/cocodataset/cocoapi/issues/172 +# pycocotools>=2.0 # COCO mAP +# roboflow +thop # FLOPs computation diff --git a/core/vision/yolov5/setup.cfg b/core/vision/yolov5/setup.cfg new file mode 100644 index 00000000..20ea49a8 --- /dev/null +++ b/core/vision/yolov5/setup.cfg @@ -0,0 +1,45 @@ +# Project-wide configuration file, can be used for package metadata and other toll configurations +# Example usage: global configuration for PEP8 (via flake8) setting or default pytest arguments + +[metadata] +license_file = LICENSE +description-file = README.md + + +[tool:pytest] +norecursedirs = + .git + dist + build +addopts = + --doctest-modules + --durations=25 + --color=yes + + +[flake8] +max-line-length = 120 +exclude = .tox,*.egg,build,temp +select = E,W,F +doctests = True +verbose = 2 +# https://pep8.readthedocs.io/en/latest/intro.html#error-codes +format = pylint +# see: https://www.flake8rules.com/ +ignore = + E731 # Do not assign a lambda expression, use a def + F405 # name may be undefined, or defined from star imports: module + E402 # module level import not at top of file + F401 # module imported but unused + W504 # line break after binary operator + E127 # continuation line over-indented for visual indent + W504 # line break after binary operator + E231 # missing whitespace after ‘,’, ‘;’, or ‘:’ + E501 # line too long + F403 # ‘from module import *’ used; unable to detect undefined names + + +[isort] +# https://pycqa.github.io/isort/docs/configuration/options.html +line_length = 120 +multi_line_output = 0 diff --git a/core/vision/yolov5/train.py b/core/vision/yolov5/train.py new file mode 100644 index 00000000..60be962d --- /dev/null +++ b/core/vision/yolov5/train.py @@ -0,0 +1,643 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Train a YOLOv5 model on a custom dataset. + +Models and datasets download automatically from the latest YOLOv5 release. +Models: https://github.com/ultralytics/yolov5/tree/master/models +Datasets: https://github.com/ultralytics/yolov5/tree/master/data +Tutorial: https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data + +Usage: + $ python path/to/train.py --data coco128.yaml --weights yolov5s.pt --img 640 # from pretrained (RECOMMENDED) + $ python path/to/train.py --data coco128.yaml --weights '' --cfg yolov5s.yaml --img 640 # from scratch +""" + +import argparse +import math +import os +import random +import sys +import time +from copy import deepcopy +from datetime import datetime +from pathlib import Path + +import numpy as np +import torch +import torch.distributed as dist +import torch.nn as nn +import yaml +from torch.cuda import amp +from torch.nn.parallel import DistributedDataParallel as DDP +from torch.optim import SGD, Adam, AdamW, lr_scheduler +from tqdm import tqdm + +FILE = Path(__file__).resolve() +ROOT = FILE.parents[0] # YOLOv5 root directory +if str(ROOT) not in sys.path: + sys.path.append(str(ROOT)) # add ROOT to PATH +ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative + +import val # for end-of-epoch mAP +from models.experimental import attempt_load +from models.yolo import Model +from utils.autoanchor import check_anchors +from utils.autobatch import check_train_batch_size +from utils.callbacks import Callbacks +from utils.datasets import create_dataloader +from utils.downloads import attempt_download +from utils.general import (LOGGER, check_dataset, check_file, check_git_status, check_img_size, check_requirements, + check_suffix, check_yaml, colorstr, get_latest_run, increment_path, init_seeds, + intersect_dicts, labels_to_class_weights, labels_to_image_weights, methods, one_cycle, + print_args, print_mutation, strip_optimizer) +from utils.loggers import Loggers +from utils.loggers.wandb.wandb_utils import check_wandb_resume +from utils.loss import ComputeLoss +from utils.metrics import fitness +from utils.plots import plot_evolve, plot_labels +from utils.torch_utils import EarlyStopping, ModelEMA, de_parallel, select_device, torch_distributed_zero_first + +LOCAL_RANK = int(os.getenv('LOCAL_RANK', -1)) # https://pytorch.org/docs/stable/elastic/run.html +RANK = int(os.getenv('RANK', -1)) +WORLD_SIZE = int(os.getenv('WORLD_SIZE', 1)) + + +def train(hyp, # path/to/hyp.yaml or hyp dictionary + opt, + device, + callbacks + ): + save_dir, epochs, batch_size, weights, single_cls, evolve, data, cfg, resume, noval, nosave, workers, freeze = \ + Path(opt.save_dir), opt.epochs, opt.batch_size, opt.weights, opt.single_cls, opt.evolve, opt.data, opt.cfg, \ + opt.resume, opt.noval, opt.nosave, opt.workers, opt.freeze + + # Directories + w = save_dir / 'weights' # weights dir + (w.parent if evolve else w).mkdir(parents=True, exist_ok=True) # make dir + last, best = w / 'last.pt', w / 'best.pt' + + # Hyperparameters + if isinstance(hyp, str): + with open(hyp, errors='ignore') as f: + hyp = yaml.safe_load(f) # load hyps dict + LOGGER.info(colorstr('hyperparameters: ') + ', '.join(f'{k}={v}' for k, v in hyp.items())) + + # Save run settings + if not evolve: + with open(save_dir / 'hyp.yaml', 'w') as f: + yaml.safe_dump(hyp, f, sort_keys=False) + with open(save_dir / 'opt.yaml', 'w') as f: + yaml.safe_dump(vars(opt), f, sort_keys=False) + + # Loggers + data_dict = None + if RANK in [-1, 0]: + loggers = Loggers(save_dir, weights, opt, hyp, LOGGER) # loggers instance + if loggers.wandb: + data_dict = loggers.wandb.data_dict + if resume: + weights, epochs, hyp, batch_size = opt.weights, opt.epochs, opt.hyp, opt.batch_size + + # Register actions + for k in methods(loggers): + callbacks.register_action(k, callback=getattr(loggers, k)) + + # Config + plots = not evolve # create plots + cuda = device.type != 'cpu' + init_seeds(1 + RANK) + with torch_distributed_zero_first(LOCAL_RANK): + data_dict = data_dict or check_dataset(data) # check if None + train_path, val_path = data_dict['train'], data_dict['val'] + nc = 1 if single_cls else int(data_dict['nc']) # number of classes + names = ['item'] if single_cls and len(data_dict['names']) != 1 else data_dict['names'] # class names + assert len(names) == nc, f'{len(names)} names found for nc={nc} dataset in {data}' # check + is_coco = isinstance(val_path, str) and val_path.endswith('coco/val2017.txt') # COCO dataset + + # Model + check_suffix(weights, '.pt') # check weights + pretrained = weights.endswith('.pt') + if pretrained: + with torch_distributed_zero_first(LOCAL_RANK): + weights = attempt_download(weights) # download if not found locally + ckpt = torch.load(weights, map_location='cpu') # load checkpoint to CPU to avoid CUDA memory leak + model = Model(cfg or ckpt['model'].yaml, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create + exclude = ['anchor'] if (cfg or hyp.get('anchors')) and not resume else [] # exclude keys + csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32 + csd = intersect_dicts(csd, model.state_dict(), exclude=exclude) # intersect + model.load_state_dict(csd, strict=False) # load + LOGGER.info(f'Transferred {len(csd)}/{len(model.state_dict())} items from {weights}') # report + else: + model = Model(cfg, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create + + # Freeze + freeze = [f'model.{x}.' for x in (freeze if len(freeze) > 1 else range(freeze[0]))] # layers to freeze + for k, v in model.named_parameters(): + v.requires_grad = True # train all layers + if any(x in k for x in freeze): + LOGGER.info(f'freezing {k}') + v.requires_grad = False + + # Image size + gs = max(int(model.stride.max()), 32) # grid size (max stride) + imgsz = check_img_size(opt.imgsz, gs, floor=gs * 2) # verify imgsz is gs-multiple + + # Batch size + if RANK == -1 and batch_size == -1: # single-GPU only, estimate best batch size + batch_size = check_train_batch_size(model, imgsz) + loggers.on_params_update({"batch_size": batch_size}) + + # Optimizer + nbs = 64 # nominal batch size + accumulate = max(round(nbs / batch_size), 1) # accumulate loss before optimizing + hyp['weight_decay'] *= batch_size * accumulate / nbs # scale weight_decay + LOGGER.info(f"Scaled weight_decay = {hyp['weight_decay']}") + + g0, g1, g2 = [], [], [] # optimizer parameter groups + for v in model.modules(): + if hasattr(v, 'bias') and isinstance(v.bias, nn.Parameter): # bias + g2.append(v.bias) + if isinstance(v, nn.BatchNorm2d): # weight (no decay) + g0.append(v.weight) + elif hasattr(v, 'weight') and isinstance(v.weight, nn.Parameter): # weight (with decay) + g1.append(v.weight) + + if opt.optimizer == 'Adam': + optimizer = Adam(g0, lr=hyp['lr0'], betas=(hyp['momentum'], 0.999)) # adjust beta1 to momentum + elif opt.optimizer == 'AdamW': + optimizer = AdamW(g0, lr=hyp['lr0'], betas=(hyp['momentum'], 0.999)) # adjust beta1 to momentum + else: + optimizer = SGD(g0, lr=hyp['lr0'], momentum=hyp['momentum'], nesterov=True) + + optimizer.add_param_group({'params': g1, 'weight_decay': hyp['weight_decay']}) # add g1 with weight_decay + optimizer.add_param_group({'params': g2}) # add g2 (biases) + LOGGER.info(f"{colorstr('optimizer:')} {type(optimizer).__name__} with parameter groups " + f"{len(g0)} weight (no decay), {len(g1)} weight, {len(g2)} bias") + del g0, g1, g2 + + # Scheduler + if opt.cos_lr: + lf = one_cycle(1, hyp['lrf'], epochs) # cosine 1->hyp['lrf'] + else: + lf = lambda x: (1 - x / epochs) * (1.0 - hyp['lrf']) + hyp['lrf'] # linear + scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf) # plot_lr_scheduler(optimizer, scheduler, epochs) + + # EMA + ema = ModelEMA(model) if RANK in [-1, 0] else None + + # Resume + start_epoch, best_fitness = 0, 0.0 + if pretrained: + # Optimizer + if ckpt['optimizer'] is not None: + optimizer.load_state_dict(ckpt['optimizer']) + best_fitness = ckpt['best_fitness'] + + # EMA + if ema and ckpt.get('ema'): + ema.ema.load_state_dict(ckpt['ema'].float().state_dict()) + ema.updates = ckpt['updates'] + + # Epochs + start_epoch = ckpt['epoch'] + 1 + if resume: + assert start_epoch > 0, f'{weights} training to {epochs} epochs is finished, nothing to resume.' + if epochs < start_epoch: + LOGGER.info(f"{weights} has been trained for {ckpt['epoch']} epochs. Fine-tuning for {epochs} more epochs.") + epochs += ckpt['epoch'] # finetune additional epochs + + del ckpt, csd + + # DP mode + if cuda and RANK == -1 and torch.cuda.device_count() > 1: + LOGGER.warning('WARNING: DP not recommended, use torch.distributed.run for best DDP Multi-GPU results.\n' + 'See Multi-GPU Tutorial at https://github.com/ultralytics/yolov5/issues/475 to get started.') + model = torch.nn.DataParallel(model) + + # SyncBatchNorm + if opt.sync_bn and cuda and RANK != -1: + model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model).to(device) + LOGGER.info('Using SyncBatchNorm()') + + # Trainloader + train_loader, dataset = create_dataloader(train_path, imgsz, batch_size // WORLD_SIZE, gs, single_cls, + hyp=hyp, augment=True, cache=None if opt.cache == 'val' else opt.cache, + rect=opt.rect, rank=LOCAL_RANK, workers=workers, + image_weights=opt.image_weights, quad=opt.quad, + prefix=colorstr('train: '), shuffle=True) + mlc = int(np.concatenate(dataset.labels, 0)[:, 0].max()) # max label class + nb = len(train_loader) # number of batches + assert mlc < nc, f'Label class {mlc} exceeds nc={nc} in {data}. Possible class labels are 0-{nc - 1}' + + # Process 0 + if RANK in [-1, 0]: + val_loader = create_dataloader(val_path, imgsz, batch_size // WORLD_SIZE * 2, gs, single_cls, + hyp=hyp, cache=None if noval else opt.cache, + rect=True, rank=-1, workers=workers * 2, pad=0.5, + prefix=colorstr('val: '))[0] + + if not resume: + labels = np.concatenate(dataset.labels, 0) + # c = torch.tensor(labels[:, 0]) # classes + # cf = torch.bincount(c.long(), minlength=nc) + 1. # frequency + # model._initialize_biases(cf.to(device)) + if plots: + plot_labels(labels, names, save_dir) + + # Anchors + if not opt.noautoanchor: + check_anchors(dataset, model=model, thr=hyp['anchor_t'], imgsz=imgsz) + model.half().float() # pre-reduce anchor precision + + callbacks.run('on_pretrain_routine_end') + + # DDP mode + if cuda and RANK != -1: + model = DDP(model, device_ids=[LOCAL_RANK], output_device=LOCAL_RANK) + + # Model attributes + nl = de_parallel(model).model[-1].nl # number of detection layers (to scale hyps) + hyp['box'] *= 3 / nl # scale to layers + hyp['cls'] *= nc / 80 * 3 / nl # scale to classes and layers + hyp['obj'] *= (imgsz / 640) ** 2 * 3 / nl # scale to image size and layers + hyp['label_smoothing'] = opt.label_smoothing + model.nc = nc # attach number of classes to model + model.hyp = hyp # attach hyperparameters to model + model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) * nc # attach class weights + model.names = names + + # Start training + t0 = time.time() + nw = max(round(hyp['warmup_epochs'] * nb), 100) # number of warmup iterations, max(3 epochs, 100 iterations) + # nw = min(nw, (epochs - start_epoch) / 2 * nb) # limit warmup to < 1/2 of training + last_opt_step = -1 + maps = np.zeros(nc) # mAP per class + results = (0, 0, 0, 0, 0, 0, 0) # P, R, mAP@.5, mAP@.5-.95, val_loss(box, obj, cls) + scheduler.last_epoch = start_epoch - 1 # do not move + scaler = amp.GradScaler(enabled=cuda) + stopper = EarlyStopping(patience=opt.patience) + compute_loss = ComputeLoss(model) # init loss class + LOGGER.info(f'Image sizes {imgsz} train, {imgsz} val\n' + f'Using {train_loader.num_workers * WORLD_SIZE} dataloader workers\n' + f"Logging results to {colorstr('bold', save_dir)}\n" + f'Starting training for {epochs} epochs...') + for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------ + model.train() + + # Update image weights (optional, single-GPU only) + if opt.image_weights: + cw = model.class_weights.cpu().numpy() * (1 - maps) ** 2 / nc # class weights + iw = labels_to_image_weights(dataset.labels, nc=nc, class_weights=cw) # image weights + dataset.indices = random.choices(range(dataset.n), weights=iw, k=dataset.n) # rand weighted idx + + # Update mosaic border (optional) + # b = int(random.uniform(0.25 * imgsz, 0.75 * imgsz + gs) // gs * gs) + # dataset.mosaic_border = [b - imgsz, -b] # height, width borders + + mloss = torch.zeros(3, device=device) # mean losses + if RANK != -1: + train_loader.sampler.set_epoch(epoch) + pbar = enumerate(train_loader) + LOGGER.info(('\n' + '%10s' * 7) % ('Epoch', 'gpu_mem', 'box', 'obj', 'cls', 'labels', 'img_size')) + if RANK in [-1, 0]: + pbar = tqdm(pbar, total=nb, bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}') # progress bar + optimizer.zero_grad() + for i, (imgs, targets, paths, _) in pbar: # batch ------------------------------------------------------------- + ni = i + nb * epoch # number integrated batches (since train start) + imgs = imgs.to(device, non_blocking=True).float() / 255 # uint8 to float32, 0-255 to 0.0-1.0 + + # Warmup + if ni <= nw: + xi = [0, nw] # x interp + # compute_loss.gr = np.interp(ni, xi, [0.0, 1.0]) # iou loss ratio (obj_loss = 1.0 or iou) + accumulate = max(1, np.interp(ni, xi, [1, nbs / batch_size]).round()) + for j, x in enumerate(optimizer.param_groups): + # bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0 + x['lr'] = np.interp(ni, xi, [hyp['warmup_bias_lr'] if j == 2 else 0.0, x['initial_lr'] * lf(epoch)]) + if 'momentum' in x: + x['momentum'] = np.interp(ni, xi, [hyp['warmup_momentum'], hyp['momentum']]) + + # Multi-scale + if opt.multi_scale: + sz = random.randrange(imgsz * 0.5, imgsz * 1.5 + gs) // gs * gs # size + sf = sz / max(imgs.shape[2:]) # scale factor + if sf != 1: + ns = [math.ceil(x * sf / gs) * gs for x in imgs.shape[2:]] # new shape (stretched to gs-multiple) + imgs = nn.functional.interpolate(imgs, size=ns, mode='bilinear', align_corners=False) + + # Forward + with amp.autocast(enabled=cuda): + pred = model(imgs) # forward + loss, loss_items = compute_loss(pred, targets.to(device)) # loss scaled by batch_size + if RANK != -1: + loss *= WORLD_SIZE # gradient averaged between devices in DDP mode + if opt.quad: + loss *= 4. + + # Backward + scaler.scale(loss).backward() + + # Optimize + if ni - last_opt_step >= accumulate: + scaler.step(optimizer) # optimizer.step + scaler.update() + optimizer.zero_grad() + if ema: + ema.update(model) + last_opt_step = ni + + # Log + if RANK in [-1, 0]: + mloss = (mloss * i + loss_items) / (i + 1) # update mean losses + mem = f'{torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0:.3g}G' # (GB) + pbar.set_description(('%10s' * 2 + '%10.4g' * 5) % ( + f'{epoch}/{epochs - 1}', mem, *mloss, targets.shape[0], imgs.shape[-1])) + callbacks.run('on_train_batch_end', ni, model, imgs, targets, paths, plots, opt.sync_bn) + if callbacks.stop_training: + return + # end batch ------------------------------------------------------------------------------------------------ + + # Scheduler + lr = [x['lr'] for x in optimizer.param_groups] # for loggers + scheduler.step() + + if RANK in [-1, 0]: + # mAP + callbacks.run('on_train_epoch_end', epoch=epoch) + ema.update_attr(model, include=['yaml', 'nc', 'hyp', 'names', 'stride', 'class_weights']) + final_epoch = (epoch + 1 == epochs) or stopper.possible_stop + if not noval or final_epoch: # Calculate mAP + results, maps, _ = val.run(data_dict, + batch_size=batch_size // WORLD_SIZE * 2, + imgsz=imgsz, + model=ema.ema, + single_cls=single_cls, + dataloader=val_loader, + save_dir=save_dir, + plots=False, + callbacks=callbacks, + compute_loss=compute_loss) + + # Update best mAP + fi = fitness(np.array(results).reshape(1, -1)) # weighted combination of [P, R, mAP@.5, mAP@.5-.95] + if fi > best_fitness: + best_fitness = fi + log_vals = list(mloss) + list(results) + lr + callbacks.run('on_fit_epoch_end', log_vals, epoch, best_fitness, fi) + + # Save model + if (not nosave) or (final_epoch and not evolve): # if save + ckpt = {'epoch': epoch, + 'best_fitness': best_fitness, + 'model': deepcopy(de_parallel(model)).half(), + 'ema': deepcopy(ema.ema).half(), + 'updates': ema.updates, + 'optimizer': optimizer.state_dict(), + 'wandb_id': loggers.wandb.wandb_run.id if loggers.wandb else None, + 'date': datetime.now().isoformat()} + + # Save last, best and delete + torch.save(ckpt, last) + if best_fitness == fi: + torch.save(ckpt, best) + if (epoch > 0) and (opt.save_period > 0) and (epoch % opt.save_period == 0): + torch.save(ckpt, w / f'epoch{epoch}.pt') + del ckpt + callbacks.run('on_model_save', last, epoch, final_epoch, best_fitness, fi) + + # Stop Single-GPU + if RANK == -1 and stopper(epoch=epoch, fitness=fi): + break + + # Stop DDP TODO: known issues shttps://github.com/ultralytics/yolov5/pull/4576 + # stop = stopper(epoch=epoch, fitness=fi) + # if RANK == 0: + # dist.broadcast_object_list([stop], 0) # broadcast 'stop' to all ranks + + # Stop DPP + # with torch_distributed_zero_first(RANK): + # if stop: + # break # must break all DDP ranks + + # end epoch ---------------------------------------------------------------------------------------------------- + # end training ----------------------------------------------------------------------------------------------------- + if RANK in [-1, 0]: + LOGGER.info(f'\n{epoch - start_epoch + 1} epochs completed in {(time.time() - t0) / 3600:.3f} hours.') + for f in last, best: + if f.exists(): + strip_optimizer(f) # strip optimizers + if f is best: + LOGGER.info(f'\nValidating {f}...') + results, _, _ = val.run(data_dict, + batch_size=batch_size // WORLD_SIZE * 2, + imgsz=imgsz, + model=attempt_load(f, device).half(), + iou_thres=0.65 if is_coco else 0.60, # best pycocotools results at 0.65 + single_cls=single_cls, + dataloader=val_loader, + save_dir=save_dir, + save_json=is_coco, + verbose=True, + plots=True, + callbacks=callbacks, + compute_loss=compute_loss) # val best model with plots + if is_coco: + callbacks.run('on_fit_epoch_end', list(mloss) + list(results) + lr, epoch, best_fitness, fi) + + callbacks.run('on_train_end', last, best, plots, epoch, results) + LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}") + + torch.cuda.empty_cache() + return results + + +def parse_opt(known=False): + parser = argparse.ArgumentParser() + parser.add_argument('--weights', type=str, default=ROOT / 'yolov5s.pt', help='initial weights path') + parser.add_argument('--cfg', type=str, default='', help='model.yaml path') + parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path') + parser.add_argument('--hyp', type=str, default=ROOT / 'data/hyps/hyp.scratch-low.yaml', help='hyperparameters path') + parser.add_argument('--epochs', type=int, default=300) + parser.add_argument('--batch-size', type=int, default=16, help='total batch size for all GPUs, -1 for autobatch') + parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='train, val image size (pixels)') + parser.add_argument('--rect', action='store_true', help='rectangular training') + parser.add_argument('--resume', nargs='?', const=True, default=False, help='resume most recent training') + parser.add_argument('--nosave', action='store_true', help='only save final checkpoint') + parser.add_argument('--noval', action='store_true', help='only validate final epoch') + parser.add_argument('--noautoanchor', action='store_true', help='disable AutoAnchor') + parser.add_argument('--evolve', type=int, nargs='?', const=300, help='evolve hyperparameters for x generations') + parser.add_argument('--bucket', type=str, default='', help='gsutil bucket') + parser.add_argument('--cache', type=str, nargs='?', const='ram', help='--cache images in "ram" (default) or "disk"') + parser.add_argument('--image-weights', action='store_true', help='use weighted image selection for training') + parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') + parser.add_argument('--multi-scale', action='store_true', help='vary img-size +/- 50%%') + parser.add_argument('--single-cls', action='store_true', help='train multi-class data as single-class') + parser.add_argument('--optimizer', type=str, choices=['SGD', 'Adam', 'AdamW'], default='SGD', help='optimizer') + parser.add_argument('--sync-bn', action='store_true', help='use SyncBatchNorm, only available in DDP mode') + parser.add_argument('--workers', type=int, default=8, help='max dataloader workers (per RANK in DDP mode)') + parser.add_argument('--project', default=ROOT / 'runs/train', help='save to project/name') + parser.add_argument('--name', default='exp', help='save to project/name') + parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment') + parser.add_argument('--quad', action='store_true', help='quad dataloader') + parser.add_argument('--cos-lr', action='store_true', help='cosine LR scheduler') + parser.add_argument('--label-smoothing', type=float, default=0.0, help='Label smoothing epsilon') + parser.add_argument('--patience', type=int, default=100, help='EarlyStopping patience (epochs without improvement)') + parser.add_argument('--freeze', nargs='+', type=int, default=[0], help='Freeze layers: backbone=10, first3=0 1 2') + parser.add_argument('--save-period', type=int, default=-1, help='Save checkpoint every x epochs (disabled if < 1)') + parser.add_argument('--local_rank', type=int, default=-1, help='DDP parameter, do not modify') + + # Weights & Biases arguments + parser.add_argument('--entity', default=None, help='W&B: Entity') + parser.add_argument('--upload_dataset', nargs='?', const=True, default=False, help='W&B: Upload data, "val" option') + parser.add_argument('--bbox_interval', type=int, default=-1, help='W&B: Set bounding-box image logging interval') + parser.add_argument('--artifact_alias', type=str, default='latest', help='W&B: Version of dataset artifact to use') + + opt = parser.parse_known_args()[0] if known else parser.parse_args() + return opt + + +def main(opt, callbacks=Callbacks()): + # Checks + if RANK in [-1, 0]: + print_args(FILE.stem, opt) + check_git_status() + check_requirements(exclude=['thop']) + + # Resume + if opt.resume and not check_wandb_resume(opt) and not opt.evolve: # resume an interrupted run + ckpt = opt.resume if isinstance(opt.resume, str) else get_latest_run() # specified or most recent path + assert os.path.isfile(ckpt), 'ERROR: --resume checkpoint does not exist' + with open(Path(ckpt).parent.parent / 'opt.yaml', errors='ignore') as f: + opt = argparse.Namespace(**yaml.safe_load(f)) # replace + opt.cfg, opt.weights, opt.resume = '', ckpt, True # reinstate + LOGGER.info(f'Resuming training from {ckpt}') + else: + opt.data, opt.cfg, opt.hyp, opt.weights, opt.project = \ + check_file(opt.data), check_yaml(opt.cfg), check_yaml(opt.hyp), str(opt.weights), str(opt.project) # checks + assert len(opt.cfg) or len(opt.weights), 'either --cfg or --weights must be specified' + if opt.evolve: + if opt.project == str(ROOT / 'runs/train'): # if default project name, rename to runs/evolve + opt.project = str(ROOT / 'runs/evolve') + opt.exist_ok, opt.resume = opt.resume, False # pass resume to exist_ok and disable resume + opt.save_dir = str(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok)) + + # DDP mode + device = select_device(opt.device, batch_size=opt.batch_size) + if LOCAL_RANK != -1: + msg = 'is not compatible with YOLOv5 Multi-GPU DDP training' + assert not opt.image_weights, f'--image-weights {msg}' + assert not opt.evolve, f'--evolve {msg}' + assert opt.batch_size != -1, f'AutoBatch with --batch-size -1 {msg}, please pass a valid --batch-size' + assert opt.batch_size % WORLD_SIZE == 0, f'--batch-size {opt.batch_size} must be multiple of WORLD_SIZE' + assert torch.cuda.device_count() > LOCAL_RANK, 'insufficient CUDA devices for DDP command' + torch.cuda.set_device(LOCAL_RANK) + device = torch.device('cuda', LOCAL_RANK) + dist.init_process_group(backend="nccl" if dist.is_nccl_available() else "gloo") + + # Train + if not opt.evolve: + train(opt.hyp, opt, device, callbacks) + if WORLD_SIZE > 1 and RANK == 0: + LOGGER.info('Destroying process group... ') + dist.destroy_process_group() + + # Evolve hyperparameters (optional) + else: + # Hyperparameter evolution metadata (mutation scale 0-1, lower_limit, upper_limit) + meta = {'lr0': (1, 1e-5, 1e-1), # initial learning rate (SGD=1E-2, Adam=1E-3) + 'lrf': (1, 0.01, 1.0), # final OneCycleLR learning rate (lr0 * lrf) + 'momentum': (0.3, 0.6, 0.98), # SGD momentum/Adam beta1 + 'weight_decay': (1, 0.0, 0.001), # optimizer weight decay + 'warmup_epochs': (1, 0.0, 5.0), # warmup epochs (fractions ok) + 'warmup_momentum': (1, 0.0, 0.95), # warmup initial momentum + 'warmup_bias_lr': (1, 0.0, 0.2), # warmup initial bias lr + 'box': (1, 0.02, 0.2), # box loss gain + 'cls': (1, 0.2, 4.0), # cls loss gain + 'cls_pw': (1, 0.5, 2.0), # cls BCELoss positive_weight + 'obj': (1, 0.2, 4.0), # obj loss gain (scale with pixels) + 'obj_pw': (1, 0.5, 2.0), # obj BCELoss positive_weight + 'iou_t': (0, 0.1, 0.7), # IoU training threshold + 'anchor_t': (1, 2.0, 8.0), # anchor-multiple threshold + 'anchors': (2, 2.0, 10.0), # anchors per output grid (0 to ignore) + 'fl_gamma': (0, 0.0, 2.0), # focal loss gamma (efficientDet default gamma=1.5) + 'hsv_h': (1, 0.0, 0.1), # image HSV-Hue augmentation (fraction) + 'hsv_s': (1, 0.0, 0.9), # image HSV-Saturation augmentation (fraction) + 'hsv_v': (1, 0.0, 0.9), # image HSV-Value augmentation (fraction) + 'degrees': (1, 0.0, 45.0), # image rotation (+/- deg) + 'translate': (1, 0.0, 0.9), # image translation (+/- fraction) + 'scale': (1, 0.0, 0.9), # image scale (+/- gain) + 'shear': (1, 0.0, 10.0), # image shear (+/- deg) + 'perspective': (0, 0.0, 0.001), # image perspective (+/- fraction), range 0-0.001 + 'flipud': (1, 0.0, 1.0), # image flip up-down (probability) + 'fliplr': (0, 0.0, 1.0), # image flip left-right (probability) + 'mosaic': (1, 0.0, 1.0), # image mixup (probability) + 'mixup': (1, 0.0, 1.0), # image mixup (probability) + 'copy_paste': (1, 0.0, 1.0)} # segment copy-paste (probability) + + with open(opt.hyp, errors='ignore') as f: + hyp = yaml.safe_load(f) # load hyps dict + if 'anchors' not in hyp: # anchors commented in hyp.yaml + hyp['anchors'] = 3 + opt.noval, opt.nosave, save_dir = True, True, Path(opt.save_dir) # only val/save final epoch + # ei = [isinstance(x, (int, float)) for x in hyp.values()] # evolvable indices + evolve_yaml, evolve_csv = save_dir / 'hyp_evolve.yaml', save_dir / 'evolve.csv' + if opt.bucket: + os.system(f'gsutil cp gs://{opt.bucket}/evolve.csv {evolve_csv}') # download evolve.csv if exists + + for _ in range(opt.evolve): # generations to evolve + if evolve_csv.exists(): # if evolve.csv exists: select best hyps and mutate + # Select parent(s) + parent = 'single' # parent selection method: 'single' or 'weighted' + x = np.loadtxt(evolve_csv, ndmin=2, delimiter=',', skiprows=1) + n = min(5, len(x)) # number of previous results to consider + x = x[np.argsort(-fitness(x))][:n] # top n mutations + w = fitness(x) - fitness(x).min() + 1E-6 # weights (sum > 0) + if parent == 'single' or len(x) == 1: + # x = x[random.randint(0, n - 1)] # random selection + x = x[random.choices(range(n), weights=w)[0]] # weighted selection + elif parent == 'weighted': + x = (x * w.reshape(n, 1)).sum(0) / w.sum() # weighted combination + + # Mutate + mp, s = 0.8, 0.2 # mutation probability, sigma + npr = np.random + npr.seed(int(time.time())) + g = np.array([meta[k][0] for k in hyp.keys()]) # gains 0-1 + ng = len(meta) + v = np.ones(ng) + while all(v == 1): # mutate until a change occurs (prevent duplicates) + v = (g * (npr.random(ng) < mp) * npr.randn(ng) * npr.random() * s + 1).clip(0.3, 3.0) + for i, k in enumerate(hyp.keys()): # plt.hist(v.ravel(), 300) + hyp[k] = float(x[i + 7] * v[i]) # mutate + + # Constrain to limits + for k, v in meta.items(): + hyp[k] = max(hyp[k], v[1]) # lower limit + hyp[k] = min(hyp[k], v[2]) # upper limit + hyp[k] = round(hyp[k], 5) # significant digits + + # Train mutation + results = train(hyp.copy(), opt, device, callbacks) + callbacks = Callbacks() + # Write mutation results + print_mutation(results, hyp.copy(), save_dir, opt.bucket) + + # Plot results + plot_evolve(evolve_csv) + LOGGER.info(f'Hyperparameter evolution finished {opt.evolve} generations\n' + f"Results saved to {colorstr('bold', save_dir)}\n" + f'Usage example: $ python train.py --hyp {evolve_yaml}') + + +def run(**kwargs): + # Usage: import train; train.run(data='coco128.yaml', imgsz=320, weights='yolov5m.pt') + opt = parse_opt(True) + for k, v in kwargs.items(): + setattr(opt, k, v) + main(opt) + return opt + + +if __name__ == "__main__": + opt = parse_opt() + main(opt) diff --git a/core/vision/yolov5/tutorial.ipynb b/core/vision/yolov5/tutorial.ipynb new file mode 100644 index 00000000..1479a164 --- /dev/null +++ b/core/vision/yolov5/tutorial.ipynb @@ -0,0 +1,1102 @@ +{ + "nbformat": 4, + "nbformat_minor": 0, + "metadata": { + "colab": { + "name": "YOLOv5 Tutorial", + "provenance": [], + "collapsed_sections": [], + "include_colab_link": true + }, + "kernelspec": { + "name": "python3", + "display_name": "Python 3" + }, + "accelerator": "GPU", + "widgets": { + "application/vnd.jupyter.widget-state+json": { + "eb95db7cae194218b3fcefb439b6352f": { + "model_module": "@jupyter-widgets/controls", + "model_name": "HBoxModel", + "model_module_version": "1.5.0", + "state": { + "_view_name": "HBoxView", + "_dom_classes": [], + "_model_name": "HBoxModel", + "_view_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_view_count": null, + "_view_module_version": "1.5.0", + "box_style": "", + "layout": "IPY_MODEL_769ecde6f2e64bacb596ce972f8d3d2d", + "_model_module": "@jupyter-widgets/controls", + "children": [ + "IPY_MODEL_384a001876054c93b0af45cd1e960bfe", + "IPY_MODEL_dded0aeae74440f7ba2ffa0beb8dd612", + "IPY_MODEL_5296d28be75740b2892ae421bbec3657" + ] + } + }, + "769ecde6f2e64bacb596ce972f8d3d2d": { + "model_module": "@jupyter-widgets/base", + "model_name": "LayoutModel", + "model_module_version": "1.2.0", + "state": { + "_view_name": "LayoutView", + "grid_template_rows": null, + "right": null, + "justify_content": null, + "_view_module": "@jupyter-widgets/base", + "overflow": null, + "_model_module_version": "1.2.0", + "_view_count": null, + "flex_flow": null, + "width": null, + "min_width": null, + "border": null, + "align_items": null, + "bottom": null, + "_model_module": "@jupyter-widgets/base", + "top": null, + "grid_column": null, + "overflow_y": null, + "overflow_x": null, + "grid_auto_flow": null, + "grid_area": null, + "grid_template_columns": null, + "flex": null, + "_model_name": "LayoutModel", + "justify_items": null, + "grid_row": null, + "max_height": null, + "align_content": null, + "visibility": null, + "align_self": null, + "height": null, + "min_height": null, + "padding": null, + "grid_auto_rows": null, + "grid_gap": null, + "max_width": null, + "order": null, + "_view_module_version": "1.2.0", + "grid_template_areas": null, + "object_position": null, + "object_fit": null, + "grid_auto_columns": null, + "margin": null, + "display": null, + "left": null + } + }, + "384a001876054c93b0af45cd1e960bfe": { + "model_module": "@jupyter-widgets/controls", + "model_name": "HTMLModel", + "model_module_version": "1.5.0", + "state": { + "_view_name": "HTMLView", + "style": "IPY_MODEL_9f09facb2a6c4a7096810d327c8b551c", + "_dom_classes": [], + "description": "", + "_model_name": "HTMLModel", + "placeholder": "​", + "_view_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "value": "100%", + "_view_count": null, + "_view_module_version": "1.5.0", + "description_tooltip": null, + "_model_module": "@jupyter-widgets/controls", + "layout": "IPY_MODEL_25621cff5d16448cb7260e839fd0f543" + } + }, + "dded0aeae74440f7ba2ffa0beb8dd612": { + "model_module": "@jupyter-widgets/controls", + "model_name": "FloatProgressModel", + "model_module_version": "1.5.0", + "state": { + "_view_name": "ProgressView", + "style": "IPY_MODEL_0ce7164fc0c74bb9a2b5c7037375a727", + "_dom_classes": [], + "description": "", + "_model_name": "FloatProgressModel", + "bar_style": "success", + "max": 818322941, + "_view_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "value": 818322941, + "_view_count": null, + "_view_module_version": "1.5.0", + "orientation": "horizontal", + "min": 0, + "description_tooltip": null, + "_model_module": "@jupyter-widgets/controls", + "layout": "IPY_MODEL_c4c4593c10904cb5b8a5724d60c7e181" + } + }, + "5296d28be75740b2892ae421bbec3657": { + "model_module": "@jupyter-widgets/controls", + "model_name": "HTMLModel", + "model_module_version": "1.5.0", + "state": { + "_view_name": "HTMLView", + "style": "IPY_MODEL_473371611126476c88d5d42ec7031ed6", + "_dom_classes": [], + "description": "", + "_model_name": "HTMLModel", + "placeholder": "​", + "_view_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "value": " 780M/780M [00:11<00:00, 91.9MB/s]", + "_view_count": null, + "_view_module_version": "1.5.0", + "description_tooltip": null, + "_model_module": "@jupyter-widgets/controls", + "layout": "IPY_MODEL_65efdfd0d26c46e79c8c5ff3b77126cc" + } + }, + "9f09facb2a6c4a7096810d327c8b551c": { + "model_module": "@jupyter-widgets/controls", + "model_name": "DescriptionStyleModel", + "model_module_version": "1.5.0", + "state": { + "_view_name": "StyleView", + "_model_name": "DescriptionStyleModel", + "description_width": "", + "_view_module": "@jupyter-widgets/base", + "_model_module_version": "1.5.0", + "_view_count": null, + "_view_module_version": "1.2.0", + "_model_module": "@jupyter-widgets/controls" + } + }, + "25621cff5d16448cb7260e839fd0f543": { + "model_module": "@jupyter-widgets/base", + "model_name": "LayoutModel", + "model_module_version": "1.2.0", + "state": { + "_view_name": "LayoutView", + "grid_template_rows": null, + "right": null, + "justify_content": null, + "_view_module": "@jupyter-widgets/base", + "overflow": null, + "_model_module_version": "1.2.0", + "_view_count": null, + "flex_flow": null, + "width": null, + "min_width": null, + "border": null, + "align_items": null, + "bottom": null, + "_model_module": "@jupyter-widgets/base", + "top": null, + "grid_column": null, + "overflow_y": null, + "overflow_x": null, + "grid_auto_flow": null, + "grid_area": null, + "grid_template_columns": null, + "flex": null, + "_model_name": "LayoutModel", + "justify_items": null, + "grid_row": null, + "max_height": null, + "align_content": null, + "visibility": null, + "align_self": null, + "height": null, + "min_height": null, + "padding": null, + "grid_auto_rows": null, + "grid_gap": null, + "max_width": null, + "order": null, + "_view_module_version": "1.2.0", + "grid_template_areas": null, + "object_position": null, + "object_fit": null, + "grid_auto_columns": null, + "margin": null, + "display": null, + "left": null + } + }, + "0ce7164fc0c74bb9a2b5c7037375a727": { + "model_module": "@jupyter-widgets/controls", + "model_name": "ProgressStyleModel", + "model_module_version": "1.5.0", + "state": { + "_view_name": "StyleView", + "_model_name": "ProgressStyleModel", + "description_width": "", + "_view_module": "@jupyter-widgets/base", + "_model_module_version": "1.5.0", + "_view_count": null, + "_view_module_version": "1.2.0", + "bar_color": null, + "_model_module": "@jupyter-widgets/controls" + } + }, + "c4c4593c10904cb5b8a5724d60c7e181": { + "model_module": "@jupyter-widgets/base", + "model_name": "LayoutModel", + "model_module_version": "1.2.0", + "state": { + "_view_name": "LayoutView", + "grid_template_rows": null, + "right": null, + "justify_content": null, + "_view_module": "@jupyter-widgets/base", + "overflow": null, + "_model_module_version": "1.2.0", + "_view_count": null, + "flex_flow": null, + "width": null, + "min_width": null, + "border": null, + "align_items": null, + "bottom": null, + "_model_module": "@jupyter-widgets/base", + "top": null, + "grid_column": null, + "overflow_y": null, + "overflow_x": null, + "grid_auto_flow": null, + "grid_area": null, + "grid_template_columns": null, + "flex": null, + "_model_name": "LayoutModel", + "justify_items": null, + "grid_row": null, + "max_height": null, + "align_content": null, + "visibility": null, + "align_self": null, + "height": null, + "min_height": null, + "padding": null, + "grid_auto_rows": null, + "grid_gap": null, + "max_width": null, + "order": null, + "_view_module_version": "1.2.0", + "grid_template_areas": null, + "object_position": null, + "object_fit": null, + "grid_auto_columns": null, + "margin": null, + "display": null, + "left": null + } + }, + "473371611126476c88d5d42ec7031ed6": { + "model_module": "@jupyter-widgets/controls", + "model_name": "DescriptionStyleModel", + "model_module_version": "1.5.0", + "state": { + "_view_name": "StyleView", + "_model_name": "DescriptionStyleModel", + "description_width": "", + "_view_module": "@jupyter-widgets/base", + "_model_module_version": "1.5.0", + "_view_count": null, + "_view_module_version": "1.2.0", + "_model_module": "@jupyter-widgets/controls" + } + }, + "65efdfd0d26c46e79c8c5ff3b77126cc": { + "model_module": "@jupyter-widgets/base", + "model_name": "LayoutModel", + "model_module_version": "1.2.0", + "state": { + "_view_name": "LayoutView", + "grid_template_rows": null, + "right": null, + "justify_content": null, + "_view_module": "@jupyter-widgets/base", + "overflow": null, + "_model_module_version": "1.2.0", + "_view_count": null, + "flex_flow": null, + "width": null, + "min_width": null, + "border": null, + "align_items": null, + "bottom": null, + "_model_module": "@jupyter-widgets/base", + "top": null, + "grid_column": null, + "overflow_y": null, + "overflow_x": null, + "grid_auto_flow": null, + "grid_area": null, + "grid_template_columns": null, + "flex": null, + "_model_name": "LayoutModel", + "justify_items": null, + "grid_row": null, + "max_height": null, + "align_content": null, + "visibility": null, + "align_self": null, + "height": null, + "min_height": null, + "padding": null, + "grid_auto_rows": null, + "grid_gap": null, + "max_width": null, + "order": null, + "_view_module_version": "1.2.0", + "grid_template_areas": null, + "object_position": null, + "object_fit": null, + "grid_auto_columns": null, + "margin": null, + "display": null, + "left": null + } + } + } + } + }, + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "id": "view-in-github", + "colab_type": "text" + }, + "source": [ + "\"Open" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "t6MPjfT5NrKQ" + }, + "source": [ + "\n", + "\n", + "\n", + "This is the **official YOLOv5 🚀 notebook** by **Ultralytics**, and is freely available for redistribution under the [GPL-3.0 license](https://choosealicense.com/licenses/gpl-3.0/). \n", + "For more information please visit https://github.com/ultralytics/yolov5 and https://ultralytics.com. Thank you!" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "7mGmQbAO5pQb" + }, + "source": [ + "# Setup\n", + "\n", + "Clone repo, install dependencies and check PyTorch and GPU." + ] + }, + { + "cell_type": "code", + "metadata": { + "id": "wbvMlHd_QwMG", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "3809e5a9-dd41-4577-fe62-5531abf7cca2" + }, + "source": [ + "!git clone https://github.com/ultralytics/yolov5 # clone\n", + "%cd yolov5\n", + "%pip install -qr requirements.txt # install\n", + "\n", + "import torch\n", + "from yolov5 import utils\n", + "display = utils.notebook_init() # checks" + ], + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "YOLOv5 🚀 v6.0-48-g84a8099 torch 1.10.0+cu102 CUDA:0 (Tesla V100-SXM2-16GB, 16160MiB)\n", + "Setup complete ✅ (2 CPUs, 12.7 GB RAM, 42.2/166.8 GB disk)\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "4JnkELT0cIJg" + }, + "source": [ + "# 1. Inference\n", + "\n", + "`detect.py` runs YOLOv5 inference on a variety of sources, downloading models automatically from the [latest YOLOv5 release](https://github.com/ultralytics/yolov5/releases), and saving results to `runs/detect`. Example inference sources are:\n", + "\n", + "```shell\n", + "python detect.py --source 0 # webcam\n", + " img.jpg # image \n", + " vid.mp4 # video\n", + " path/ # directory\n", + " path/*.jpg # glob\n", + " 'https://youtu.be/Zgi9g1ksQHc' # YouTube\n", + " 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream\n", + "```" + ] + }, + { + "cell_type": "code", + "metadata": { + "id": "zR9ZbuQCH7FX", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "8f7e6588-215d-4ebd-93af-88b871e770a7" + }, + "source": [ + "!python detect.py --weights yolov5s.pt --img 640 --conf 0.25 --source data/images\n", + "display.Image(filename='runs/detect/exp/zidane.jpg', width=600)" + ], + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "\u001b[34m\u001b[1mdetect: \u001b[0mweights=['yolov5s.pt'], source=data/images, imgsz=[640, 640], conf_thres=0.25, iou_thres=0.45, max_det=1000, device=, view_img=False, save_txt=False, save_conf=False, save_crop=False, nosave=False, classes=None, agnostic_nms=False, augment=False, visualize=False, update=False, project=runs/detect, name=exp, exist_ok=False, line_thickness=3, hide_labels=False, hide_conf=False, half=False, dnn=False\n", + "YOLOv5 🚀 v6.0-48-g84a8099 torch 1.10.0+cu102 CUDA:0 (Tesla V100-SXM2-16GB, 16160MiB)\n", + "\n", + "Fusing layers... \n", + "Model Summary: 213 layers, 7225885 parameters, 0 gradients\n", + "image 1/2 /content/yolov5/data/images/bus.jpg: 640x480 4 persons, 1 bus, Done. (0.007s)\n", + "image 2/2 /content/yolov5/data/images/zidane.jpg: 384x640 2 persons, 1 tie, Done. (0.007s)\n", + "Speed: 0.5ms pre-process, 6.9ms inference, 1.3ms NMS per image at shape (1, 3, 640, 640)\n", + "Results saved to \u001b[1mruns/detect/exp\u001b[0m\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "hkAzDWJ7cWTr" + }, + "source": [ + "        \n", + "" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "0eq1SMWl6Sfn" + }, + "source": [ + "# 2. Validate\n", + "Validate a model's accuracy on [COCO](https://cocodataset.org/#home) val or test-dev datasets. Models are downloaded automatically from the [latest YOLOv5 release](https://github.com/ultralytics/yolov5/releases). To show results by class use the `--verbose` flag. Note that `pycocotools` metrics may be ~1% better than the equivalent repo metrics, as is visible below, due to slight differences in mAP computation." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "eyTZYGgRjnMc" + }, + "source": [ + "## COCO val\n", + "Download [COCO val 2017](https://github.com/ultralytics/yolov5/blob/74b34872fdf41941cddcf243951cdb090fbac17b/data/coco.yaml#L14) dataset (1GB - 5000 images), and test model accuracy." + ] + }, + { + "cell_type": "code", + "metadata": { + "id": "WQPtK1QYVaD_", + "colab": { + "base_uri": "https://localhost:8080/", + "height": 48, + "referenced_widgets": [ + "eb95db7cae194218b3fcefb439b6352f", + "769ecde6f2e64bacb596ce972f8d3d2d", + "384a001876054c93b0af45cd1e960bfe", + "dded0aeae74440f7ba2ffa0beb8dd612", + "5296d28be75740b2892ae421bbec3657", + "9f09facb2a6c4a7096810d327c8b551c", + "25621cff5d16448cb7260e839fd0f543", + "0ce7164fc0c74bb9a2b5c7037375a727", + "c4c4593c10904cb5b8a5724d60c7e181", + "473371611126476c88d5d42ec7031ed6", + "65efdfd0d26c46e79c8c5ff3b77126cc" + ] + }, + "outputId": "bcf9a448-1f9b-4a41-ad49-12f181faf05a" + }, + "source": [ + "# Download COCO val\n", + "torch.hub.download_url_to_file('https://ultralytics.com/assets/coco2017val.zip', 'tmp.zip')\n", + "!unzip -q tmp.zip -d ../datasets && rm tmp.zip" + ], + "execution_count": null, + "outputs": [ + { + "output_type": "display_data", + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "eb95db7cae194218b3fcefb439b6352f", + "version_minor": 0, + "version_major": 2 + }, + "text/plain": [ + " 0%| | 0.00/780M [00:00

\n", + "Close the active learning loop by sampling images from your inference conditions with the `roboflow` pip package\n", + "

\n", + "\n", + "Train a YOLOv5s model on the [COCO128](https://www.kaggle.com/ultralytics/coco128) dataset with `--data coco128.yaml`, starting from pretrained `--weights yolov5s.pt`, or from randomly initialized `--weights '' --cfg yolov5s.yaml`.\n", + "\n", + "- **Pretrained [Models](https://github.com/ultralytics/yolov5/tree/master/models)** are downloaded\n", + "automatically from the [latest YOLOv5 release](https://github.com/ultralytics/yolov5/releases)\n", + "- **[Datasets](https://github.com/ultralytics/yolov5/tree/master/data)** available for autodownload include: [COCO](https://github.com/ultralytics/yolov5/blob/master/data/coco.yaml), [COCO128](https://github.com/ultralytics/yolov5/blob/master/data/coco128.yaml), [VOC](https://github.com/ultralytics/yolov5/blob/master/data/VOC.yaml), [Argoverse](https://github.com/ultralytics/yolov5/blob/master/data/Argoverse.yaml), [VisDrone](https://github.com/ultralytics/yolov5/blob/master/data/VisDrone.yaml), [GlobalWheat](https://github.com/ultralytics/yolov5/blob/master/data/GlobalWheat2020.yaml), [xView](https://github.com/ultralytics/yolov5/blob/master/data/xView.yaml), [Objects365](https://github.com/ultralytics/yolov5/blob/master/data/Objects365.yaml), [SKU-110K](https://github.com/ultralytics/yolov5/blob/master/data/SKU-110K.yaml).\n", + "- **Training Results** are saved to `runs/train/` with incrementing run directories, i.e. `runs/train/exp2`, `runs/train/exp3` etc.\n", + "

\n", + "\n", + "## Train on Custom Data with Roboflow 🌟 NEW\n", + "\n", + "[Roboflow](https://roboflow.com/?ref=ultralytics) enables you to easily **organize, label, and prepare** a high quality dataset with your own custom data. Roboflow also makes it easy to establish an active learning pipeline, collaborate with your team on dataset improvement, and integrate directly into your model building workflow with the `roboflow` pip package.\n", + "\n", + "- Custom Training Example: [https://blog.roboflow.com/how-to-train-yolov5-on-a-custom-dataset/](https://blog.roboflow.com/how-to-train-yolov5-on-a-custom-dataset/?ref=ultralytics)\n", + "- Custom Training Notebook: [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/roboflow-ai/yolov5-custom-training-tutorial/blob/main/yolov5-custom-training.ipynb)\n", + "
\n", + "\n", + "

Label images lightning fast (including with model-assisted labeling)" + ] + }, + { + "cell_type": "code", + "metadata": { + "id": "bOy5KI2ncnWd" + }, + "source": [ + "# Tensorboard (optional)\n", + "%load_ext tensorboard\n", + "%tensorboard --logdir runs/train" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": { + "id": "2fLAV42oNb7M" + }, + "source": [ + "# Weights & Biases (optional)\n", + "%pip install -q wandb\n", + "import wandb\n", + "wandb.login()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": { + "id": "1NcFxRcFdJ_O", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "8724d13d-6711-4a12-d96a-1c655e5c3549" + }, + "source": [ + "# Train YOLOv5s on COCO128 for 3 epochs\n", + "!python train.py --img 640 --batch 16 --epochs 3 --data coco128.yaml --weights yolov5s.pt --cache" + ], + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "\u001b[34m\u001b[1mtrain: \u001b[0mweights=yolov5s.pt, cfg=, data=coco128.yaml, hyp=data/hyps/hyp.scratch-low.yaml, epochs=3, batch_size=16, imgsz=640, rect=False, resume=False, nosave=False, noval=False, noautoanchor=False, evolve=None, bucket=, cache=ram, image_weights=False, device=, multi_scale=False, single_cls=False, adam=False, sync_bn=False, workers=8, project=runs/train, name=exp, exist_ok=False, quad=False, linear_lr=False, label_smoothing=0.0, patience=100, freeze=0, save_period=-1, local_rank=-1, entity=None, upload_dataset=False, bbox_interval=-1, artifact_alias=latest\n", + "\u001b[34m\u001b[1mgithub: \u001b[0mup to date with https://github.com/ultralytics/yolov5 ✅\n", + "YOLOv5 🚀 v6.0-48-g84a8099 torch 1.10.0+cu102 CUDA:0 (Tesla V100-SXM2-16GB, 16160MiB)\n", + "\n", + "\u001b[34m\u001b[1mhyperparameters: \u001b[0mlr0=0.01, lrf=0.1, momentum=0.937, weight_decay=0.0005, warmup_epochs=3.0, warmup_momentum=0.8, warmup_bias_lr=0.1, box=0.05, cls=0.5, cls_pw=1.0, obj=1.0, obj_pw=1.0, iou_t=0.2, anchor_t=4.0, fl_gamma=0.0, hsv_h=0.015, hsv_s=0.7, hsv_v=0.4, degrees=0.0, translate=0.1, scale=0.5, shear=0.0, perspective=0.0, flipud=0.0, fliplr=0.5, mosaic=1.0, mixup=0.0, copy_paste=0.0\n", + "\u001b[34m\u001b[1mWeights & Biases: \u001b[0mrun 'pip install wandb' to automatically track and visualize YOLOv5 🚀 runs (RECOMMENDED)\n", + "\u001b[34m\u001b[1mTensorBoard: \u001b[0mStart with 'tensorboard --logdir runs/train', view at http://localhost:6006/\n", + "\n", + " from n params module arguments \n", + " 0 -1 1 3520 models.common.Conv [3, 32, 6, 2, 2] \n", + " 1 -1 1 18560 models.common.Conv [32, 64, 3, 2] \n", + " 2 -1 1 18816 models.common.C3 [64, 64, 1] \n", + " 3 -1 1 73984 models.common.Conv [64, 128, 3, 2] \n", + " 4 -1 2 115712 models.common.C3 [128, 128, 2] \n", + " 5 -1 1 295424 models.common.Conv [128, 256, 3, 2] \n", + " 6 -1 3 625152 models.common.C3 [256, 256, 3] \n", + " 7 -1 1 1180672 models.common.Conv [256, 512, 3, 2] \n", + " 8 -1 1 1182720 models.common.C3 [512, 512, 1] \n", + " 9 -1 1 656896 models.common.SPPF [512, 512, 5] \n", + " 10 -1 1 131584 models.common.Conv [512, 256, 1, 1] \n", + " 11 -1 1 0 torch.nn.modules.upsampling.Upsample [None, 2, 'nearest'] \n", + " 12 [-1, 6] 1 0 models.common.Concat [1] \n", + " 13 -1 1 361984 models.common.C3 [512, 256, 1, False] \n", + " 14 -1 1 33024 models.common.Conv [256, 128, 1, 1] \n", + " 15 -1 1 0 torch.nn.modules.upsampling.Upsample [None, 2, 'nearest'] \n", + " 16 [-1, 4] 1 0 models.common.Concat [1] \n", + " 17 -1 1 90880 models.common.C3 [256, 128, 1, False] \n", + " 18 -1 1 147712 models.common.Conv [128, 128, 3, 2] \n", + " 19 [-1, 14] 1 0 models.common.Concat [1] \n", + " 20 -1 1 296448 models.common.C3 [256, 256, 1, False] \n", + " 21 -1 1 590336 models.common.Conv [256, 256, 3, 2] \n", + " 22 [-1, 10] 1 0 models.common.Concat [1] \n", + " 23 -1 1 1182720 models.common.C3 [512, 512, 1, False] \n", + " 24 [17, 20, 23] 1 229245 models.yolo.Detect [80, [[10, 13, 16, 30, 33, 23], [30, 61, 62, 45, 59, 119], [116, 90, 156, 198, 373, 326]], [128, 256, 512]]\n", + "Model Summary: 270 layers, 7235389 parameters, 7235389 gradients, 16.5 GFLOPs\n", + "\n", + "Transferred 349/349 items from yolov5s.pt\n", + "Scaled weight_decay = 0.0005\n", + "\u001b[34m\u001b[1moptimizer:\u001b[0m SGD with parameter groups 57 weight, 60 weight (no decay), 60 bias\n", + "\u001b[34m\u001b[1malbumentations: \u001b[0mversion 1.0.3 required by YOLOv5, but version 0.1.12 is currently installed\n", + "\u001b[34m\u001b[1mtrain: \u001b[0mScanning '../datasets/coco128/labels/train2017.cache' images and labels... 128 found, 0 missing, 2 empty, 0 corrupted: 100% 128/128 [00:00\"Weights

" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "-WPvRbS5Swl6" + }, + "source": [ + "## Local Logging\n", + "\n", + "All results are logged by default to `runs/train`, with a new experiment directory created for each new training as `runs/train/exp2`, `runs/train/exp3`, etc. View train and val jpgs to see mosaics, labels, predictions and augmentation effects. Note an Ultralytics **Mosaic Dataloader** is used for training (shown below), which combines 4 images into 1 mosaic during training.\n", + "\n", + "> \n", + "`train_batch0.jpg` shows train batch 0 mosaics and labels\n", + "\n", + "> \n", + "`test_batch0_labels.jpg` shows val batch 0 labels\n", + "\n", + "> \n", + "`test_batch0_pred.jpg` shows val batch 0 _predictions_\n", + "\n", + "Training results are automatically logged to [Tensorboard](https://www.tensorflow.org/tensorboard) and [CSV](https://github.com/ultralytics/yolov5/pull/4148) as `results.csv`, which is plotted as `results.png` (below) after training completes. You can also plot any `results.csv` file manually:\n", + "\n", + "```python\n", + "from utils.plots import plot_results \n", + "plot_results('path/to/results.csv') # plot 'results.csv' as 'results.png'\n", + "```\n", + "\n", + "\"COCO128" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "Zelyeqbyt3GD" + }, + "source": [ + "# Environments\n", + "\n", + "YOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including [CUDA](https://developer.nvidia.com/cuda)/[CUDNN](https://developer.nvidia.com/cudnn), [Python](https://www.python.org/) and [PyTorch](https://pytorch.org/) preinstalled):\n", + "\n", + "- **Google Colab and Kaggle** notebooks with free GPU: \"Open \"Open\n", + "- **Google Cloud** Deep Learning VM. See [GCP Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/GCP-Quickstart)\n", + "- **Amazon** Deep Learning AMI. See [AWS Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/AWS-Quickstart)\n", + "- **Docker Image**. See [Docker Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/Docker-Quickstart) \"Docker\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "6Qu7Iesl0p54" + }, + "source": [ + "# Status\n", + "\n", + "![CI CPU testing](https://github.com/ultralytics/yolov5/workflows/CI%20CPU%20testing/badge.svg)\n", + "\n", + "If this badge is green, all [YOLOv5 GitHub Actions](https://github.com/ultralytics/yolov5/actions) Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 training ([train.py](https://github.com/ultralytics/yolov5/blob/master/train.py)), testing ([val.py](https://github.com/ultralytics/yolov5/blob/master/val.py)), inference ([detect.py](https://github.com/ultralytics/yolov5/blob/master/detect.py)) and export ([export.py](https://github.com/ultralytics/yolov5/blob/master/export.py)) on MacOS, Windows, and Ubuntu every 24 hours and on every commit.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "IEijrePND_2I" + }, + "source": [ + "# Appendix\n", + "\n", + "Optional extras below. Unit tests validate repo functionality and should be run on any PRs submitted.\n" + ] + }, + { + "cell_type": "code", + "metadata": { + "id": "mcKoSIK2WSzj" + }, + "source": [ + "# Reproduce\n", + "for x in 'yolov5n', 'yolov5s', 'yolov5m', 'yolov5l', 'yolov5x':\n", + " !python val.py --weights {x}.pt --data coco.yaml --img 640 --task speed # speed\n", + " !python val.py --weights {x}.pt --data coco.yaml --img 640 --conf 0.001 --iou 0.65 # mAP" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": { + "id": "GMusP4OAxFu6" + }, + "source": [ + "# PyTorch Hub\n", + "import torch\n", + "\n", + "# Model\n", + "model = torch.hub.load('ultralytics/yolov5', 'yolov5s')\n", + "\n", + "# Images\n", + "dir = 'https://ultralytics.com/images/'\n", + "imgs = [dir + f for f in ('zidane.jpg', 'bus.jpg')] # batch of images\n", + "\n", + "# Inference\n", + "results = model(imgs)\n", + "results.print() # or .show(), .save()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": { + "id": "FGH0ZjkGjejy" + }, + "source": [ + "# CI Checks\n", + "%%shell\n", + "export PYTHONPATH=\"$PWD\" # to run *.py. files in subdirectories\n", + "rm -rf runs # remove runs/\n", + "for m in yolov5n; do # models\n", + " python train.py --img 64 --batch 32 --weights $m.pt --epochs 1 --device 0 # train pretrained\n", + " python train.py --img 64 --batch 32 --weights '' --cfg $m.yaml --epochs 1 --device 0 # train scratch\n", + " for d in 0 cpu; do # devices\n", + " python val.py --weights $m.pt --device $d # val official\n", + " python val.py --weights runs/train/exp/weights/best.pt --device $d # val custom\n", + " python detect.py --weights $m.pt --device $d # detect official\n", + " python detect.py --weights runs/train/exp/weights/best.pt --device $d # detect custom\n", + " done\n", + " python hubconf.py # hub\n", + " python models/yolo.py --cfg $m.yaml # build PyTorch model\n", + " python models/tf.py --weights $m.pt # build TensorFlow model\n", + " python export.py --img 64 --batch 1 --weights $m.pt --include torchscript onnx # export\n", + "done" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": { + "id": "gogI-kwi3Tye" + }, + "source": [ + "# Profile\n", + "from utils.torch_utils import profile\n", + "\n", + "m1 = lambda x: x * torch.sigmoid(x)\n", + "m2 = torch.nn.SiLU()\n", + "results = profile(input=torch.randn(16, 3, 640, 640), ops=[m1, m2], n=100)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": { + "id": "RVRSOhEvUdb5" + }, + "source": [ + "# Evolve\n", + "!python train.py --img 640 --batch 64 --epochs 100 --data coco128.yaml --weights yolov5s.pt --cache --noautoanchor --evolve\n", + "!d=runs/train/evolve && cp evolve.* $d && zip -r evolve.zip $d && gsutil mv evolve.zip gs://bucket # upload results (optional)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": { + "id": "BSgFCAcMbk1R" + }, + "source": [ + "# VOC\n", + "for b, m in zip([64, 64, 32, 16], ['yolov5s', 'yolov5m', 'yolov5l', 'yolov5x']): # zip(batch_size, model)\n", + " !python train.py --batch {b} --weights {m}.pt --data VOC.yaml --epochs 50 --cache --img 512 --nosave --hyp hyp.VOC.yaml --project VOC --name {m}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": { + "id": "VTRwsvA9u7ln" + }, + "source": [ + "# TensorRT \n", + "# https://docs.nvidia.com/deeplearning/tensorrt/install-guide/index.html#installing-pip\n", + "!pip install -U nvidia-tensorrt --index-url https://pypi.ngc.nvidia.com # install\n", + "!python export.py --weights yolov5s.pt --include engine --imgsz 640 640 --device 0 # export\n", + "!python detect.py --weights yolov5s.engine --imgsz 640 640 --device 0 # inference" + ], + "execution_count": null, + "outputs": [] + } + ] +} diff --git a/core/vision/yolov5/utils/__init__.py b/core/vision/yolov5/utils/__init__.py new file mode 100644 index 00000000..68e5e152 --- /dev/null +++ b/core/vision/yolov5/utils/__init__.py @@ -0,0 +1,36 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +utils/initialization +""" + + +def notebook_init(verbose=True): + # Check system software and hardware + print("Checking setup...") + + import os + import shutil + + from utils.general import check_requirements, emojis, is_colab + from utils.torch_utils import select_device # imports + + check_requirements(("psutil", "IPython")) + import psutil + from IPython import display # to display images and clear console output + + if is_colab(): + shutil.rmtree("/content/sample_data", ignore_errors=True) # remove colab /sample_data directory + + # System info + if verbose: + gb = 1 << 30 # bytes to GiB (1024 ** 3) + ram = psutil.virtual_memory().total + total, used, free = shutil.disk_usage("/") + display.clear_output() + s = f"({os.cpu_count()} CPUs, {ram / gb:.1f} GB RAM, {(total - free) / gb:.1f}/{total / gb:.1f} GB disk)" + else: + s = "" + + select_device(newline=False) + print(emojis(f"Setup complete ✅ {s}")) + return display diff --git a/core/vision/yolov5/utils/activations.py b/core/vision/yolov5/utils/activations.py new file mode 100644 index 00000000..a4ff789c --- /dev/null +++ b/core/vision/yolov5/utils/activations.py @@ -0,0 +1,101 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Activation functions +""" + +import torch +import torch.nn as nn +import torch.nn.functional as F + + +# SiLU https://arxiv.org/pdf/1606.08415.pdf ---------------------------------------------------------------------------- +class SiLU(nn.Module): # export-friendly version of nn.SiLU() + @staticmethod + def forward(x): + return x * torch.sigmoid(x) + + +class Hardswish(nn.Module): # export-friendly version of nn.Hardswish() + @staticmethod + def forward(x): + # return x * F.hardsigmoid(x) # for TorchScript and CoreML + return x * F.hardtanh(x + 3, 0.0, 6.0) / 6.0 # for TorchScript, CoreML and ONNX + + +# Mish https://github.com/digantamisra98/Mish -------------------------------------------------------------------------- +class Mish(nn.Module): + @staticmethod + def forward(x): + return x * F.softplus(x).tanh() + + +class MemoryEfficientMish(nn.Module): + class F(torch.autograd.Function): + @staticmethod + def forward(ctx, x): + ctx.save_for_backward(x) + return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x))) + + @staticmethod + def backward(ctx, grad_output): + x = ctx.saved_tensors[0] + sx = torch.sigmoid(x) + fx = F.softplus(x).tanh() + return grad_output * (fx + x * sx * (1 - fx * fx)) + + def forward(self, x): + return self.F.apply(x) + + +# FReLU https://arxiv.org/abs/2007.11824 ------------------------------------------------------------------------------- +class FReLU(nn.Module): + def __init__(self, c1, k=3): # ch_in, kernel + super().__init__() + self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False) + self.bn = nn.BatchNorm2d(c1) + + def forward(self, x): + return torch.max(x, self.bn(self.conv(x))) + + +# ACON https://arxiv.org/pdf/2009.04759.pdf ---------------------------------------------------------------------------- +class AconC(nn.Module): + r""" ACON activation (activate or not). + AconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is a learnable parameter + according to "Activate or Not: Learning Customized Activation" . + """ + + def __init__(self, c1): + super().__init__() + self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1)) + self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1)) + self.beta = nn.Parameter(torch.ones(1, c1, 1, 1)) + + def forward(self, x): + dpx = (self.p1 - self.p2) * x + return dpx * torch.sigmoid(self.beta * dpx) + self.p2 * x + + +class MetaAconC(nn.Module): + r""" ACON activation (activate or not). + MetaAconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is generated by a small network + according to "Activate or Not: Learning Customized Activation" . + """ + + def __init__(self, c1, k=1, s=1, r=16): # ch_in, kernel, stride, r + super().__init__() + c2 = max(r, c1 // r) + self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1)) + self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1)) + self.fc1 = nn.Conv2d(c1, c2, k, s, bias=True) + self.fc2 = nn.Conv2d(c2, c1, k, s, bias=True) + # self.bn1 = nn.BatchNorm2d(c2) + # self.bn2 = nn.BatchNorm2d(c1) + + def forward(self, x): + y = x.mean(dim=2, keepdims=True).mean(dim=3, keepdims=True) + # batch-size 1 bug/instabilities https://github.com/ultralytics/yolov5/issues/2891 + # beta = torch.sigmoid(self.bn2(self.fc2(self.bn1(self.fc1(y))))) # bug/unstable + beta = torch.sigmoid(self.fc2(self.fc1(y))) # bug patch BN layers removed + dpx = (self.p1 - self.p2) * x + return dpx * torch.sigmoid(beta * dpx) + self.p2 * x diff --git a/core/vision/yolov5/utils/augmentations.py b/core/vision/yolov5/utils/augmentations.py new file mode 100644 index 00000000..1fe377f4 --- /dev/null +++ b/core/vision/yolov5/utils/augmentations.py @@ -0,0 +1,282 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Image augmentation functions +""" + +import math +import random + +import cv2 +import numpy as np + +from utils.general import LOGGER, check_version, colorstr, resample_segments, segment2box +from utils.metrics import bbox_ioa + + +class Albumentations: + # YOLOv5 Albumentations class (optional, only used if package is installed) + def __init__(self): + self.transform = None + try: + import albumentations as A + + check_version(A.__version__, "1.0.3", hard=True) # version requirement + + self.transform = A.Compose( + [ + A.Blur(p=0.01), + A.MedianBlur(p=0.01), + A.ToGray(p=0.01), + A.CLAHE(p=0.01), + A.RandomBrightnessContrast(p=0.0), + A.RandomGamma(p=0.0), + A.ImageCompression(quality_lower=75, p=0.0), + ], + bbox_params=A.BboxParams(format="yolo", label_fields=["class_labels"]), + ) + + LOGGER.info(colorstr("albumentations: ") + ", ".join(f"{x}" for x in self.transform.transforms if x.p)) + except ImportError: # package not installed, skip + pass + except Exception as e: + LOGGER.info(colorstr("albumentations: ") + f"{e}") + + def __call__(self, im, labels, p=1.0): + if self.transform and random.random() < p: + new = self.transform(image=im, bboxes=labels[:, 1:], class_labels=labels[:, 0]) # transformed + im, labels = new["image"], np.array([[c, *b] for c, b in zip(new["class_labels"], new["bboxes"])]) + return im, labels + + +def augment_hsv(im, hgain=0.5, sgain=0.5, vgain=0.5): + # HSV color-space augmentation + if hgain or sgain or vgain: + r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains + hue, sat, val = cv2.split(cv2.cvtColor(im, cv2.COLOR_BGR2HSV)) + dtype = im.dtype # uint8 + + x = np.arange(0, 256, dtype=r.dtype) + lut_hue = ((x * r[0]) % 180).astype(dtype) + lut_sat = np.clip(x * r[1], 0, 255).astype(dtype) + lut_val = np.clip(x * r[2], 0, 255).astype(dtype) + + im_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))) + cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR, dst=im) # no return needed + + +def hist_equalize(im, clahe=True, bgr=False): + # Equalize histogram on BGR image 'im' with im.shape(n,m,3) and range 0-255 + yuv = cv2.cvtColor(im, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV) + if clahe: + c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)) + yuv[:, :, 0] = c.apply(yuv[:, :, 0]) + else: + yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0]) # equalize Y channel histogram + return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB) # convert YUV image to RGB + + +def replicate(im, labels): + # Replicate labels + h, w = im.shape[:2] + boxes = labels[:, 1:].astype(int) + x1, y1, x2, y2 = boxes.T + s = ((x2 - x1) + (y2 - y1)) / 2 # side length (pixels) + for i in s.argsort()[: round(s.size * 0.5)]: # smallest indices + x1b, y1b, x2b, y2b = boxes[i] + bh, bw = y2b - y1b, x2b - x1b + yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw)) # offset x, y + x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh] + im[y1a:y2a, x1a:x2a] = im[y1b:y2b, x1b:x2b] # im4[ymin:ymax, xmin:xmax] + labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0) + + return im, labels + + +def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32): + # Resize and pad image while meeting stride-multiple constraints + shape = im.shape[:2] # current shape [height, width] + if isinstance(new_shape, int): + new_shape = (new_shape, new_shape) + + # Scale ratio (new / old) + r = min(new_shape[0] / shape[0], new_shape[1] / shape[1]) + if not scaleup: # only scale down, do not scale up (for better val mAP) + r = min(r, 1.0) + + # Compute padding + ratio = r, r # width, height ratios + new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r)) + dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding + if auto: # minimum rectangle + dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding + elif scaleFill: # stretch + dw, dh = 0.0, 0.0 + new_unpad = (new_shape[1], new_shape[0]) + ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios + + dw /= 2 # divide padding into 2 sides + dh /= 2 + + if shape[::-1] != new_unpad: # resize + im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR) + top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1)) + left, right = int(round(dw - 0.1)), int(round(dw + 0.1)) + im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border + return im, ratio, (dw, dh) + + +def random_perspective( + im, targets=(), segments=(), degrees=10, translate=0.1, scale=0.1, shear=10, perspective=0.0, border=(0, 0) +): + # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(0.1, 0.1), scale=(0.9, 1.1), shear=(-10, 10)) + # targets = [cls, xyxy] + + height = im.shape[0] + border[0] * 2 # shape(h,w,c) + width = im.shape[1] + border[1] * 2 + + # Center + C = np.eye(3) + C[0, 2] = -im.shape[1] / 2 # x translation (pixels) + C[1, 2] = -im.shape[0] / 2 # y translation (pixels) + + # Perspective + P = np.eye(3) + P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y) + P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x) + + # Rotation and Scale + R = np.eye(3) + a = random.uniform(-degrees, degrees) + # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations + s = random.uniform(1 - scale, 1 + scale) + # s = 2 ** random.uniform(-scale, scale) + R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s) + + # Shear + S = np.eye(3) + S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg) + S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg) + + # Translation + T = np.eye(3) + T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels) + T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels) + + # Combined rotation matrix + M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT + if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed + if perspective: + im = cv2.warpPerspective(im, M, dsize=(width, height), borderValue=(114, 114, 114)) + else: # affine + im = cv2.warpAffine(im, M[:2], dsize=(width, height), borderValue=(114, 114, 114)) + + # Visualize + # import matplotlib.pyplot as plt + # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel() + # ax[0].imshow(im[:, :, ::-1]) # base + # ax[1].imshow(im2[:, :, ::-1]) # warped + + # Transform label coordinates + n = len(targets) + if n: + use_segments = any(x.any() for x in segments) + new = np.zeros((n, 4)) + if use_segments: # warp segments + segments = resample_segments(segments) # upsample + for i, segment in enumerate(segments): + xy = np.ones((len(segment), 3)) + xy[:, :2] = segment + xy = xy @ M.T # transform + xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2] # perspective rescale or affine + + # clip + new[i] = segment2box(xy, width, height) + + else: # warp boxes + xy = np.ones((n * 4, 3)) + xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1 + xy = xy @ M.T # transform + xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine + + # create new boxes + x = xy[:, [0, 2, 4, 6]] + y = xy[:, [1, 3, 5, 7]] + new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T + + # clip + new[:, [0, 2]] = new[:, [0, 2]].clip(0, width) + new[:, [1, 3]] = new[:, [1, 3]].clip(0, height) + + # filter candidates + i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10) + targets = targets[i] + targets[:, 1:5] = new[i] + + return im, targets + + +def copy_paste(im, labels, segments, p=0.5): + # Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy) + n = len(segments) + if p and n: + h, w, c = im.shape # height, width, channels + im_new = np.zeros(im.shape, np.uint8) + for j in random.sample(range(n), k=round(p * n)): + l, s = labels[j], segments[j] + box = w - l[3], l[2], w - l[1], l[4] + ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area + if (ioa < 0.30).all(): # allow 30% obscuration of existing labels + labels = np.concatenate((labels, [[l[0], *box]]), 0) + segments.append(np.concatenate((w - s[:, 0:1], s[:, 1:2]), 1)) + cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (255, 255, 255), cv2.FILLED) + + result = cv2.bitwise_and(src1=im, src2=im_new) + result = cv2.flip(result, 1) # augment segments (flip left-right) + i = result > 0 # pixels to replace + # i[:, :] = result.max(2).reshape(h, w, 1) # act over ch + im[i] = result[i] # cv2.imwrite('debug.jpg', im) # debug + + return im, labels, segments + + +def cutout(im, labels, p=0.5): + # Applies image cutout augmentation https://arxiv.org/abs/1708.04552 + if random.random() < p: + h, w = im.shape[:2] + scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction + for s in scales: + mask_h = random.randint(1, int(h * s)) # create random masks + mask_w = random.randint(1, int(w * s)) + + # box + xmin = max(0, random.randint(0, w) - mask_w // 2) + ymin = max(0, random.randint(0, h) - mask_h // 2) + xmax = min(w, xmin + mask_w) + ymax = min(h, ymin + mask_h) + + # apply random color mask + im[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)] + + # return unobscured labels + if len(labels) and s > 0.03: + box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32) + ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area + labels = labels[ioa < 0.60] # remove >60% obscured labels + + return labels + + +def mixup(im, labels, im2, labels2): + # Applies MixUp augmentation https://arxiv.org/pdf/1710.09412.pdf + r = np.random.beta(32.0, 32.0) # mixup ratio, alpha=beta=32.0 + im = (im * r + im2 * (1 - r)).astype(np.uint8) + labels = np.concatenate((labels, labels2), 0) + return im, labels + + +def box_candidates(box1, box2, wh_thr=2, ar_thr=100, area_thr=0.1, eps=1e-16): # box1(4,n), box2(4,n) + # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio + w1, h1 = box1[2] - box1[0], box1[3] - box1[1] + w2, h2 = box2[2] - box2[0], box2[3] - box2[1] + ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio + return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates diff --git a/core/vision/yolov5/utils/autoanchor.py b/core/vision/yolov5/utils/autoanchor.py new file mode 100644 index 00000000..77518abe --- /dev/null +++ b/core/vision/yolov5/utils/autoanchor.py @@ -0,0 +1,170 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +AutoAnchor utils +""" + +import random + +import numpy as np +import torch +import yaml +from tqdm import tqdm + +from utils.general import LOGGER, colorstr, emojis + +PREFIX = colorstr('AutoAnchor: ') + + +def check_anchor_order(m): + # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary + a = m.anchors.prod(-1).mean(-1).view(-1) # mean anchor area per output layer + da = a[-1] - a[0] # delta a + ds = m.stride[-1] - m.stride[0] # delta s + if da and (da.sign() != ds.sign()): # same order + LOGGER.info(f'{PREFIX}Reversing anchor order') + m.anchors[:] = m.anchors.flip(0) + + +def check_anchors(dataset, model, thr=4.0, imgsz=640): + # Check anchor fit to data, recompute if necessary + m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect() + shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True) + scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale + wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh + + def metric(k): # compute metric + r = wh[:, None] / k[None] + x = torch.min(r, 1 / r).min(2)[0] # ratio metric + best = x.max(1)[0] # best_x + aat = (x > 1 / thr).float().sum(1).mean() # anchors above threshold + bpr = (best > 1 / thr).float().mean() # best possible recall + return bpr, aat + + stride = m.stride.to(m.anchors.device).view(-1, 1, 1) # model strides + anchors = m.anchors.clone() * stride # current anchors + bpr, aat = metric(anchors.cpu().view(-1, 2)) + s = f'\n{PREFIX}{aat:.2f} anchors/target, {bpr:.3f} Best Possible Recall (BPR). ' + if bpr > 0.98: # threshold to recompute + LOGGER.info(emojis(f'{s}Current anchors are a good fit to dataset ✅')) + else: + LOGGER.info(emojis(f'{s}Anchors are a poor fit to dataset ⚠️, attempting to improve...')) + na = m.anchors.numel() // 2 # number of anchors + try: + anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False) + except Exception as e: + LOGGER.info(f'{PREFIX}ERROR: {e}') + new_bpr = metric(anchors)[0] + if new_bpr > bpr: # replace anchors + anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors) + m.anchors[:] = anchors.clone().view_as(m.anchors) + check_anchor_order(m) # must be in pixel-space (not grid-space) + m.anchors /= stride + s = f'{PREFIX}Done ✅ (optional: update model *.yaml to use these anchors in the future)' + else: + s = f'{PREFIX}Done ⚠️ (original anchors better than new anchors, proceeding with original anchors)' + LOGGER.info(emojis(s)) + + +def kmean_anchors(dataset='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True): + """ Creates kmeans-evolved anchors from training dataset + + Arguments: + dataset: path to data.yaml, or a loaded dataset + n: number of anchors + img_size: image size used for training + thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0 + gen: generations to evolve anchors using genetic algorithm + verbose: print all results + + Return: + k: kmeans evolved anchors + + Usage: + from utils.autoanchor import *; _ = kmean_anchors() + """ + from scipy.cluster.vq import kmeans + + npr = np.random + thr = 1 / thr + + def metric(k, wh): # compute metrics + r = wh[:, None] / k[None] + x = torch.min(r, 1 / r).min(2)[0] # ratio metric + # x = wh_iou(wh, torch.tensor(k)) # iou metric + return x, x.max(1)[0] # x, best_x + + def anchor_fitness(k): # mutation fitness + _, best = metric(torch.tensor(k, dtype=torch.float32), wh) + return (best * (best > thr).float()).mean() # fitness + + def print_results(k, verbose=True): + k = k[np.argsort(k.prod(1))] # sort small to large + x, best = metric(k, wh0) + bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr + s = f'{PREFIX}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr\n' \ + f'{PREFIX}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, ' \ + f'past_thr={x[x > thr].mean():.3f}-mean: ' + for i, x in enumerate(k): + s += '%i,%i, ' % (round(x[0]), round(x[1])) + if verbose: + LOGGER.info(s[:-2]) + return k + + if isinstance(dataset, str): # *.yaml file + with open(dataset, errors='ignore') as f: + data_dict = yaml.safe_load(f) # model dict + from utils.datasets import LoadImagesAndLabels + dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True) + + # Get label wh + shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True) + wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh + + # Filter + i = (wh0 < 3.0).any(1).sum() + if i: + LOGGER.info(f'{PREFIX}WARNING: Extremely small objects found: {i} of {len(wh0)} labels are < 3 pixels in size') + wh = wh0[(wh0 >= 2.0).any(1)] # filter > 2 pixels + # wh = wh * (npr.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1 + + # Kmeans init + try: + LOGGER.info(f'{PREFIX}Running kmeans for {n} anchors on {len(wh)} points...') + assert n <= len(wh) # apply overdetermined constraint + s = wh.std(0) # sigmas for whitening + k = kmeans(wh / s, n, iter=30)[0] * s # points + assert n == len(k) # kmeans may return fewer points than requested if wh is insufficient or too similar + except Exception: + LOGGER.warning(f'{PREFIX}WARNING: switching strategies from kmeans to random init') + k = np.sort(npr.rand(n * 2)).reshape(n, 2) * img_size # random init + wh, wh0 = (torch.tensor(x, dtype=torch.float32) for x in (wh, wh0)) + k = print_results(k, verbose=False) + + # Plot + # k, d = [None] * 20, [None] * 20 + # for i in tqdm(range(1, 21)): + # k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance + # fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True) + # ax = ax.ravel() + # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.') + # fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh + # ax[0].hist(wh[wh[:, 0]<100, 0],400) + # ax[1].hist(wh[wh[:, 1]<100, 1],400) + # fig.savefig('wh.png', dpi=200) + + # Evolve + f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma + pbar = tqdm(range(gen), bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}') # progress bar + for _ in pbar: + v = np.ones(sh) + while (v == 1).all(): # mutate until a change occurs (prevent duplicates) + v = ((npr.random(sh) < mp) * random.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0) + kg = (k.copy() * v).clip(min=2.0) + fg = anchor_fitness(kg) + if fg > f: + f, k = fg, kg.copy() + pbar.desc = f'{PREFIX}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}' + if verbose: + print_results(k, verbose) + + return print_results(k) diff --git a/core/vision/yolov5/utils/autobatch.py b/core/vision/yolov5/utils/autobatch.py new file mode 100644 index 00000000..e53b4787 --- /dev/null +++ b/core/vision/yolov5/utils/autobatch.py @@ -0,0 +1,58 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Auto-batch utils +""" + +from copy import deepcopy + +import numpy as np +import torch +from torch.cuda import amp + +from utils.general import LOGGER, colorstr +from utils.torch_utils import profile + + +def check_train_batch_size(model, imgsz=640): + # Check YOLOv5 training batch size + with amp.autocast(): + return autobatch(deepcopy(model).train(), imgsz) # compute optimal batch size + + +def autobatch(model, imgsz=640, fraction=0.9, batch_size=16): + # Automatically estimate best batch size to use `fraction` of available CUDA memory + # Usage: + # import torch + # from utils.autobatch import autobatch + # model = torch.hub.load('ultralytics/yolov5', 'yolov5s', autoshape=False) + # print(autobatch(model)) + + prefix = colorstr('AutoBatch: ') + LOGGER.info(f'{prefix}Computing optimal batch size for --imgsz {imgsz}') + device = next(model.parameters()).device # get model device + if device.type == 'cpu': + LOGGER.info(f'{prefix}CUDA not detected, using default CPU batch-size {batch_size}') + return batch_size + + gb = 1 << 30 # bytes to GiB (1024 ** 3) + d = str(device).upper() # 'CUDA:0' + properties = torch.cuda.get_device_properties(device) # device properties + t = properties.total_memory / gb # (GiB) + r = torch.cuda.memory_reserved(device) / gb # (GiB) + a = torch.cuda.memory_allocated(device) / gb # (GiB) + f = t - (r + a) # free inside reserved + LOGGER.info(f'{prefix}{d} ({properties.name}) {t:.2f}G total, {r:.2f}G reserved, {a:.2f}G allocated, {f:.2f}G free') + + batch_sizes = [1, 2, 4, 8, 16] + try: + img = [torch.zeros(b, 3, imgsz, imgsz) for b in batch_sizes] + y = profile(img, model, n=3, device=device) + except Exception as e: + LOGGER.warning(f'{prefix}{e}') + + y = [x[2] for x in y if x] # memory [2] + batch_sizes = batch_sizes[:len(y)] + p = np.polyfit(batch_sizes, y, deg=1) # first degree polynomial fit + b = int((f * fraction - p[1]) / p[0]) # y intercept (optimal batch size) + LOGGER.info(f'{prefix}Using batch-size {b} for {d} {t * fraction:.2f}G/{t:.2f}G ({fraction * 100:.0f}%)') + return b diff --git a/core/vision/yolov5/utils/aws/__init__.py b/core/vision/yolov5/utils/aws/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/core/vision/yolov5/utils/aws/mime.sh b/core/vision/yolov5/utils/aws/mime.sh new file mode 100644 index 00000000..c319a83c --- /dev/null +++ b/core/vision/yolov5/utils/aws/mime.sh @@ -0,0 +1,26 @@ +# AWS EC2 instance startup 'MIME' script https://aws.amazon.com/premiumsupport/knowledge-center/execute-user-data-ec2/ +# This script will run on every instance restart, not only on first start +# --- DO NOT COPY ABOVE COMMENTS WHEN PASTING INTO USERDATA --- + +Content-Type: multipart/mixed; boundary="//" +MIME-Version: 1.0 + +--// +Content-Type: text/cloud-config; charset="us-ascii" +MIME-Version: 1.0 +Content-Transfer-Encoding: 7bit +Content-Disposition: attachment; filename="cloud-config.txt" + +#cloud-config +cloud_final_modules: +- [scripts-user, always] + +--// +Content-Type: text/x-shellscript; charset="us-ascii" +MIME-Version: 1.0 +Content-Transfer-Encoding: 7bit +Content-Disposition: attachment; filename="userdata.txt" + +#!/bin/bash +# --- paste contents of userdata.sh here --- +--// diff --git a/core/vision/yolov5/utils/aws/resume.py b/core/vision/yolov5/utils/aws/resume.py new file mode 100644 index 00000000..b21731c9 --- /dev/null +++ b/core/vision/yolov5/utils/aws/resume.py @@ -0,0 +1,40 @@ +# Resume all interrupted trainings in yolov5/ dir including DDP trainings +# Usage: $ python utils/aws/resume.py + +import os +import sys +from pathlib import Path + +import torch +import yaml + +FILE = Path(__file__).resolve() +ROOT = FILE.parents[2] # YOLOv5 root directory +if str(ROOT) not in sys.path: + sys.path.append(str(ROOT)) # add ROOT to PATH + +port = 0 # --master_port +path = Path('').resolve() +for last in path.rglob('*/**/last.pt'): + ckpt = torch.load(last) + if ckpt['optimizer'] is None: + continue + + # Load opt.yaml + with open(last.parent.parent / 'opt.yaml', errors='ignore') as f: + opt = yaml.safe_load(f) + + # Get device count + d = opt['device'].split(',') # devices + nd = len(d) # number of devices + ddp = nd > 1 or (nd == 0 and torch.cuda.device_count() > 1) # distributed data parallel + + if ddp: # multi-GPU + port += 1 + cmd = f'python -m torch.distributed.run --nproc_per_node {nd} --master_port {port} train.py --resume {last}' + else: # single-GPU + cmd = f'python train.py --resume {last}' + + cmd += ' > /dev/null 2>&1 &' # redirect output to dev/null and run in daemon thread + print(cmd) + os.system(cmd) diff --git a/core/vision/yolov5/utils/aws/userdata.sh b/core/vision/yolov5/utils/aws/userdata.sh new file mode 100644 index 00000000..5fc1332a --- /dev/null +++ b/core/vision/yolov5/utils/aws/userdata.sh @@ -0,0 +1,27 @@ +#!/bin/bash +# AWS EC2 instance startup script https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html +# This script will run only once on first instance start (for a re-start script see mime.sh) +# /home/ubuntu (ubuntu) or /home/ec2-user (amazon-linux) is working dir +# Use >300 GB SSD + +cd home/ubuntu +if [ ! -d yolov5 ]; then + echo "Running first-time script." # install dependencies, download COCO, pull Docker + git clone https://github.com/ultralytics/yolov5 -b master && sudo chmod -R 777 yolov5 + cd yolov5 + bash data/scripts/get_coco.sh && echo "COCO done." & + sudo docker pull ultralytics/yolov5:latest && echo "Docker done." & + python -m pip install --upgrade pip && pip install -r requirements.txt && python detect.py && echo "Requirements done." & + wait && echo "All tasks done." # finish background tasks +else + echo "Running re-start script." # resume interrupted runs + i=0 + list=$(sudo docker ps -qa) # container list i.e. $'one\ntwo\nthree\nfour' + while IFS= read -r id; do + ((i++)) + echo "restarting container $i: $id" + sudo docker start $id + # sudo docker exec -it $id python train.py --resume # single-GPU + sudo docker exec -d $id python utils/aws/resume.py # multi-scenario + done <<<"$list" +fi diff --git a/core/vision/yolov5/utils/benchmarks.py b/core/vision/yolov5/utils/benchmarks.py new file mode 100644 index 00000000..bdbbdc43 --- /dev/null +++ b/core/vision/yolov5/utils/benchmarks.py @@ -0,0 +1,104 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Run YOLOv5 benchmarks on all supported export formats + +Format | `export.py --include` | Model +--- | --- | --- +PyTorch | - | yolov5s.pt +TorchScript | `torchscript` | yolov5s.torchscript +ONNX | `onnx` | yolov5s.onnx +OpenVINO | `openvino` | yolov5s_openvino_model/ +TensorRT | `engine` | yolov5s.engine +CoreML | `coreml` | yolov5s.mlmodel +TensorFlow SavedModel | `saved_model` | yolov5s_saved_model/ +TensorFlow GraphDef | `pb` | yolov5s.pb +TensorFlow Lite | `tflite` | yolov5s.tflite +TensorFlow Edge TPU | `edgetpu` | yolov5s_edgetpu.tflite +TensorFlow.js | `tfjs` | yolov5s_web_model/ + +Requirements: + $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu # CPU + $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow # GPU + $ pip install -U nvidia-tensorrt --index-url https://pypi.ngc.nvidia.com # TensorRT + +Usage: + $ python utils/benchmarks.py --weights yolov5s.pt --img 640 +""" + +import argparse +import sys +import time +from pathlib import Path + +import pandas as pd + +FILE = Path(__file__).resolve() +ROOT = FILE.parents[1] # YOLOv5 root directory +if str(ROOT) not in sys.path: + sys.path.append(str(ROOT)) # add ROOT to PATH +# ROOT = ROOT.relative_to(Path.cwd()) # relative + +import export +import val +from utils import notebook_init +from utils.general import LOGGER, print_args +from utils.torch_utils import select_device + + +def run(weights=ROOT / 'yolov5s.pt', # weights path + imgsz=640, # inference size (pixels) + batch_size=1, # batch size + data=ROOT / 'data/coco128.yaml', # dataset.yaml path + device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu + half=False, # use FP16 half-precision inference + ): + y, t = [], time.time() + formats = export.export_formats() + device = select_device(device) + for i, (name, f, suffix, gpu) in formats.iterrows(): # index, (name, file, suffix, gpu-capable) + try: + if device.type != 'cpu': + assert gpu, f'{name} inference not supported on GPU' + if f == '-': + w = weights # PyTorch format + else: + w = export.run(weights=weights, imgsz=[imgsz], include=[f], device=device, half=half)[-1] # all others + assert suffix in str(w), 'export failed' + result = val.run(data, w, batch_size, imgsz, plots=False, device=device, task='benchmark', half=half) + metrics = result[0] # metrics (mp, mr, map50, map, *losses(box, obj, cls)) + speeds = result[2] # times (preprocess, inference, postprocess) + y.append([name, metrics[3], speeds[1]]) # mAP, t_inference + except Exception as e: + LOGGER.warning(f'WARNING: Benchmark failure for {name}: {e}') + y.append([name, None, None]) # mAP, t_inference + + # Print results + LOGGER.info('\n') + parse_opt() + notebook_init() # print system info + py = pd.DataFrame(y, columns=['Format', 'mAP@0.5:0.95', 'Inference time (ms)']) + LOGGER.info(f'\nBenchmarks complete ({time.time() - t:.2f}s)') + LOGGER.info(str(py)) + return py + + +def parse_opt(): + parser = argparse.ArgumentParser() + parser.add_argument('--weights', type=str, default=ROOT / 'yolov5s.pt', help='weights path') + parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='inference size (pixels)') + parser.add_argument('--batch-size', type=int, default=1, help='batch size') + parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path') + parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') + parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference') + opt = parser.parse_args() + print_args(FILE.stem, opt) + return opt + + +def main(opt): + run(**vars(opt)) + + +if __name__ == "__main__": + opt = parse_opt() + main(opt) diff --git a/core/vision/yolov5/utils/callbacks.py b/core/vision/yolov5/utils/callbacks.py new file mode 100644 index 00000000..c51c268f --- /dev/null +++ b/core/vision/yolov5/utils/callbacks.py @@ -0,0 +1,78 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Callback utils +""" + + +class Callbacks: + """" + Handles all registered callbacks for YOLOv5 Hooks + """ + + def __init__(self): + # Define the available callbacks + self._callbacks = { + 'on_pretrain_routine_start': [], + 'on_pretrain_routine_end': [], + + 'on_train_start': [], + 'on_train_epoch_start': [], + 'on_train_batch_start': [], + 'optimizer_step': [], + 'on_before_zero_grad': [], + 'on_train_batch_end': [], + 'on_train_epoch_end': [], + + 'on_val_start': [], + 'on_val_batch_start': [], + 'on_val_image_end': [], + 'on_val_batch_end': [], + 'on_val_end': [], + + 'on_fit_epoch_end': [], # fit = train + val + 'on_model_save': [], + 'on_train_end': [], + 'on_params_update': [], + 'teardown': [], + } + self.stop_training = False # set True to interrupt training + + def register_action(self, hook, name='', callback=None): + """ + Register a new action to a callback hook + + Args: + hook The callback hook name to register the action to + name The name of the action for later reference + callback The callback to fire + """ + assert hook in self._callbacks, f"hook '{hook}' not found in callbacks {self._callbacks}" + assert callable(callback), f"callback '{callback}' is not callable" + self._callbacks[hook].append({'name': name, 'callback': callback}) + + def get_registered_actions(self, hook=None): + """" + Returns all the registered actions by callback hook + + Args: + hook The name of the hook to check, defaults to all + """ + if hook: + return self._callbacks[hook] + else: + return self._callbacks + + def run(self, hook, *args, **kwargs): + """ + Loop through the registered actions and fire all callbacks + + Args: + hook The name of the hook to check, defaults to all + args Arguments to receive from YOLOv5 + kwargs Keyword Arguments to receive from YOLOv5 + """ + + assert hook in self._callbacks, f"hook '{hook}' not found in callbacks {self._callbacks}" + + for logger in self._callbacks[hook]: + logger['callback'](*args, **kwargs) diff --git a/core/vision/yolov5/utils/datasets.py b/core/vision/yolov5/utils/datasets.py new file mode 100644 index 00000000..d4cd5292 --- /dev/null +++ b/core/vision/yolov5/utils/datasets.py @@ -0,0 +1,1119 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Dataloaders and dataset utils +""" + +import glob +import hashlib +import json +import math +import os +import random +import shutil +import time +from itertools import repeat +from multiprocessing.pool import Pool, ThreadPool +from pathlib import Path +from threading import Thread +from urllib.parse import urlparse +from zipfile import ZipFile + +import cv2 +import numpy as np +import torch +import torch.nn.functional as F +import yaml +from PIL import ExifTags, Image, ImageOps +from torch.utils.data import DataLoader, Dataset, dataloader, distributed +from tqdm import tqdm + +from utils.augmentations import Albumentations, augment_hsv, copy_paste, letterbox, mixup, random_perspective +from utils.general import ( + DATASETS_DIR, + LOGGER, + NUM_THREADS, + check_dataset, + check_requirements, + check_yaml, + clean_str, + segments2boxes, + xyn2xy, + xywh2xyxy, + xywhn2xyxy, + xyxy2xywhn, +) +from utils.torch_utils import torch_distributed_zero_first + +# Parameters +HELP_URL = "https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data" +IMG_FORMATS = "bmp", "dng", "jpeg", "jpg", "mpo", "png", "tif", "tiff", "webp" # include image suffixes +VID_FORMATS = "asf", "avi", "gif", "m4v", "mkv", "mov", "mp4", "mpeg", "mpg", "ts", "wmv" # include video suffixes +BAR_FORMAT = "{l_bar}{bar:10}{r_bar}{bar:-10b}" # tqdm bar format + +# Get orientation exif tag +for orientation in ExifTags.TAGS.keys(): + if ExifTags.TAGS[orientation] == "Orientation": + break + + +def get_hash(paths): + # Returns a single hash value of a list of paths (files or dirs) + size = sum(os.path.getsize(p) for p in paths if os.path.exists(p)) # sizes + h = hashlib.md5(str(size).encode()) # hash sizes + h.update("".join(paths).encode()) # hash paths + return h.hexdigest() # return hash + + +def exif_size(img): + # Returns exif-corrected PIL size + s = img.size # (width, height) + try: + rotation = dict(img._getexif().items())[orientation] + if rotation == 6: # rotation 270 + s = (s[1], s[0]) + elif rotation == 8: # rotation 90 + s = (s[1], s[0]) + except Exception: + pass + + return s + + +def exif_transpose(image): + """ + Transpose a PIL image accordingly if it has an EXIF Orientation tag. + Inplace version of https://github.com/python-pillow/Pillow/blob/master/src/PIL/ImageOps.py exif_transpose() + + :param image: The image to transpose. + :return: An image. + """ + exif = image.getexif() + orientation = exif.get(0x0112, 1) # default 1 + if orientation > 1: + method = { + 2: Image.FLIP_LEFT_RIGHT, + 3: Image.ROTATE_180, + 4: Image.FLIP_TOP_BOTTOM, + 5: Image.TRANSPOSE, + 6: Image.ROTATE_270, + 7: Image.TRANSVERSE, + 8: Image.ROTATE_90, + }.get(orientation) + if method is not None: + image = image.transpose(method) + del exif[0x0112] + image.info["exif"] = exif.tobytes() + return image + + +def create_dataloader( + path, + imgsz, + batch_size, + stride, + single_cls=False, + hyp=None, + augment=False, + cache=False, + pad=0.0, + rect=False, + rank=-1, + workers=8, + image_weights=False, + quad=False, + prefix="", + shuffle=False, +): + if rect and shuffle: + LOGGER.warning("WARNING: --rect is incompatible with DataLoader shuffle, setting shuffle=False") + shuffle = False + with torch_distributed_zero_first(rank): # init dataset *.cache only once if DDP + dataset = LoadImagesAndLabels( + path, + imgsz, + batch_size, + augment=augment, # augmentation + hyp=hyp, # hyperparameters + rect=rect, # rectangular batches + cache_images=cache, + single_cls=single_cls, + stride=int(stride), + pad=pad, + image_weights=image_weights, + prefix=prefix, + ) + + batch_size = min(batch_size, len(dataset)) + nd = torch.cuda.device_count() # number of CUDA devices + nw = min([os.cpu_count() // max(nd, 1), batch_size if batch_size > 1 else 0, workers]) # number of workers + sampler = None if rank == -1 else distributed.DistributedSampler(dataset, shuffle=shuffle) + loader = DataLoader if image_weights else InfiniteDataLoader # only DataLoader allows for attribute updates + return ( + loader( + dataset, + batch_size=batch_size, + shuffle=shuffle and sampler is None, + num_workers=nw, + sampler=sampler, + pin_memory=True, + collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn, + ), + dataset, + ) + + +class InfiniteDataLoader(dataloader.DataLoader): + """Dataloader that reuses workers + + Uses same syntax as vanilla DataLoader + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + object.__setattr__(self, "batch_sampler", _RepeatSampler(self.batch_sampler)) + self.iterator = super().__iter__() + + def __len__(self): + return len(self.batch_sampler.sampler) + + def __iter__(self): + for i in range(len(self)): + yield next(self.iterator) + + +class _RepeatSampler: + """Sampler that repeats forever + + Args: + sampler (Sampler) + """ + + def __init__(self, sampler): + self.sampler = sampler + + def __iter__(self): + while True: + yield from iter(self.sampler) + + +class LoadImages: + # YOLOv5 image/video dataloader, i.e. `python detect.py --source image.jpg/vid.mp4` + def __init__(self, path, img_size=640, stride=32, auto=True): + p = str(Path(path).resolve()) # os-agnostic absolute path + if "*" in p: + files = sorted(glob.glob(p, recursive=True)) # glob + elif os.path.isdir(p): + files = sorted(glob.glob(os.path.join(p, "*.*"))) # dir + elif os.path.isfile(p): + files = [p] # files + else: + raise Exception(f"ERROR: {p} does not exist") + + images = [x for x in files if x.split(".")[-1].lower() in IMG_FORMATS] + videos = [x for x in files if x.split(".")[-1].lower() in VID_FORMATS] + ni, nv = len(images), len(videos) + + self.img_size = img_size + self.stride = stride + self.files = images + videos + self.nf = ni + nv # number of files + self.video_flag = [False] * ni + [True] * nv + self.mode = "image" + self.auto = auto + if any(videos): + self.new_video(videos[0]) # new video + else: + self.cap = None + assert self.nf > 0, ( + f"No images or videos found in {p}. " + f"Supported formats are:\nimages: {IMG_FORMATS}\nvideos: {VID_FORMATS}" + ) + + def __iter__(self): + self.count = 0 + return self + + def __next__(self): + if self.count == self.nf: + raise StopIteration + path = self.files[self.count] + + if self.video_flag[self.count]: + # Read video + self.mode = "video" + ret_val, img0 = self.cap.read() + while not ret_val: + self.count += 1 + self.cap.release() + if self.count == self.nf: # last video + raise StopIteration + else: + path = self.files[self.count] + self.new_video(path) + ret_val, img0 = self.cap.read() + + self.frame += 1 + s = f"video {self.count + 1}/{self.nf} ({self.frame}/{self.frames}) {path}: " + + else: + # Read image + self.count += 1 + img0 = cv2.imread(path) # BGR + assert img0 is not None, f"Image Not Found {path}" + s = f"image {self.count}/{self.nf} {path}: " + + # Padded resize + img = letterbox(img0, self.img_size, stride=self.stride, auto=self.auto)[0] + + # Convert + img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB + img = np.ascontiguousarray(img) + + return path, img, img0, self.cap, s + + def new_video(self, path): + self.frame = 0 + self.cap = cv2.VideoCapture(path) + self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT)) + + def __len__(self): + return self.nf # number of files + + +class LoadWebcam: # for inference + # YOLOv5 local webcam dataloader, i.e. `python detect.py --source 0` + def __init__(self, pipe="0", img_size=640, stride=32): + self.img_size = img_size + self.stride = stride + self.pipe = eval(pipe) if pipe.isnumeric() else pipe + self.cap = cv2.VideoCapture(self.pipe) # video capture object + self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3) # set buffer size + + def __iter__(self): + self.count = -1 + return self + + def __next__(self): + self.count += 1 + if cv2.waitKey(1) == ord("q"): # q to quit + self.cap.release() + cv2.destroyAllWindows() + raise StopIteration + + # Read frame + ret_val, img0 = self.cap.read() + img0 = cv2.flip(img0, 1) # flip left-right + + # Print + assert ret_val, f"Camera Error {self.pipe}" + img_path = "webcam.jpg" + s = f"webcam {self.count}: " + + # Padded resize + img = letterbox(img0, self.img_size, stride=self.stride)[0] + + # Convert + img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB + img = np.ascontiguousarray(img) + + return img_path, img, img0, None, s + + def __len__(self): + return 0 + + +class LoadStreams: + # YOLOv5 streamloader, i.e. `python detect.py --source 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP streams` + def __init__(self, sources="streams.txt", img_size=640, stride=32, auto=True): + self.mode = "stream" + self.img_size = img_size + self.stride = stride + + if os.path.isfile(sources): + with open(sources) as f: + sources = [x.strip() for x in f.read().strip().splitlines() if len(x.strip())] + else: + sources = [sources] + + n = len(sources) + self.imgs, self.fps, self.frames, self.threads = [None] * n, [0] * n, [0] * n, [None] * n + self.sources = [clean_str(x) for x in sources] # clean source names for later + self.auto = auto + for i, s in enumerate(sources): # index, source + # Start thread to read frames from video stream + st = f"{i + 1}/{n}: {s}... " + if urlparse(s).hostname in ("youtube.com", "youtu.be"): # if source is YouTube video + check_requirements(("pafy", "youtube_dl==2020.12.2")) + import pafy + + s = pafy.new(s).getbest(preftype="mp4").url # YouTube URL + s = eval(s) if s.isnumeric() else s # i.e. s = '0' local webcam + cap = cv2.VideoCapture(s) + assert cap.isOpened(), f"{st}Failed to open {s}" + w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + fps = cap.get(cv2.CAP_PROP_FPS) # warning: may return 0 or nan + self.frames[i] = max(int(cap.get(cv2.CAP_PROP_FRAME_COUNT)), 0) or float("inf") # infinite stream fallback + self.fps[i] = max((fps if math.isfinite(fps) else 0) % 100, 0) or 30 # 30 FPS fallback + + _, self.imgs[i] = cap.read() # guarantee first frame + self.threads[i] = Thread(target=self.update, args=([i, cap, s]), daemon=True) + LOGGER.info(f"{st} Success ({self.frames[i]} frames {w}x{h} at {self.fps[i]:.2f} FPS)") + self.threads[i].start() + LOGGER.info("") # newline + + # check for common shapes + s = np.stack([letterbox(x, self.img_size, stride=self.stride, auto=self.auto)[0].shape for x in self.imgs]) + self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal + if not self.rect: + LOGGER.warning("WARNING: Stream shapes differ. For optimal performance supply similarly-shaped streams.") + + def update(self, i, cap, stream): + # Read stream `i` frames in daemon thread + n, f, read = 0, self.frames[i], 1 # frame number, frame array, inference every 'read' frame + while cap.isOpened() and n < f: + n += 1 + # _, self.imgs[index] = cap.read() + cap.grab() + if n % read == 0: + success, im = cap.retrieve() + if success: + self.imgs[i] = im + else: + LOGGER.warning("WARNING: Video stream unresponsive, please check your IP camera connection.") + self.imgs[i] = np.zeros_like(self.imgs[i]) + cap.open(stream) # re-open stream if signal was lost + time.sleep(1 / self.fps[i]) # wait time + + def __iter__(self): + self.count = -1 + return self + + def __next__(self): + self.count += 1 + if not all(x.is_alive() for x in self.threads) or cv2.waitKey(1) == ord("q"): # q to quit + cv2.destroyAllWindows() + raise StopIteration + + # Letterbox + img0 = self.imgs.copy() + img = [letterbox(x, self.img_size, stride=self.stride, auto=self.rect and self.auto)[0] for x in img0] + + # Stack + img = np.stack(img, 0) + + # Convert + img = img[..., ::-1].transpose((0, 3, 1, 2)) # BGR to RGB, BHWC to BCHW + img = np.ascontiguousarray(img) + + return self.sources, img, img0, None, "" + + def __len__(self): + return len(self.sources) # 1E12 frames = 32 streams at 30 FPS for 30 years + + +def img2label_paths(img_paths): + # Define label paths as a function of image paths + sa, sb = os.sep + "images" + os.sep, os.sep + "labels" + os.sep # /images/, /labels/ substrings + return [sb.join(x.rsplit(sa, 1)).rsplit(".", 1)[0] + ".txt" for x in img_paths] + + +class LoadImagesAndLabels(Dataset): + # YOLOv5 train_loader/val_loader, loads images and labels for training and validation + cache_version = 0.6 # dataset labels *.cache version + + def __init__( + self, + path, + img_size=640, + batch_size=16, + augment=False, + hyp=None, + rect=False, + image_weights=False, + cache_images=False, + single_cls=False, + stride=32, + pad=0.0, + prefix="", + ): + self.img_size = img_size + self.augment = augment + self.hyp = hyp + self.image_weights = image_weights + self.rect = False if image_weights else rect + self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training) + self.mosaic_border = [-img_size // 2, -img_size // 2] + self.stride = stride + self.path = path + self.albumentations = Albumentations() if augment else None + + try: + f = [] # image files + for p in path if isinstance(path, list) else [path]: + p = Path(p) # os-agnostic + if p.is_dir(): # dir + f += glob.glob(str(p / "**" / "*.*"), recursive=True) + # f = list(p.rglob('*.*')) # pathlib + elif p.is_file(): # file + with open(p) as t: + t = t.read().strip().splitlines() + parent = str(p.parent) + os.sep + f += [x.replace("./", parent) if x.startswith("./") else x for x in t] # local to global path + # f += [p.parent / x.lstrip(os.sep) for x in t] # local to global path (pathlib) + else: + raise Exception(f"{prefix}{p} does not exist") + self.im_files = sorted(x.replace("/", os.sep) for x in f if x.split(".")[-1].lower() in IMG_FORMATS) + # self.img_files = sorted([x for x in f if x.suffix[1:].lower() in IMG_FORMATS]) # pathlib + assert self.im_files, f"{prefix}No images found" + except Exception as e: + raise Exception(f"{prefix}Error loading data from {path}: {e}\nSee {HELP_URL}") + + # Check cache + self.label_files = img2label_paths(self.im_files) # labels + cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix(".cache") + try: + cache, exists = np.load(cache_path, allow_pickle=True).item(), True # load dict + assert cache["version"] == self.cache_version # same version + assert cache["hash"] == get_hash(self.label_files + self.im_files) # same hash + except Exception: + cache, exists = self.cache_labels(cache_path, prefix), False # cache + + # Display cache + nf, nm, ne, nc, n = cache.pop("results") # found, missing, empty, corrupt, total + if exists: + d = f"Scanning '{cache_path}' images and labels... {nf} found, {nm} missing, {ne} empty, {nc} corrupt" + tqdm(None, desc=prefix + d, total=n, initial=n, bar_format=BAR_FORMAT) # display cache results + if cache["msgs"]: + LOGGER.info("\n".join(cache["msgs"])) # display warnings + assert nf > 0 or not augment, f"{prefix}No labels in {cache_path}. Can not train without labels. See {HELP_URL}" + + # Read cache + [cache.pop(k) for k in ("hash", "version", "msgs")] # remove items + labels, shapes, self.segments = zip(*cache.values()) + self.labels = list(labels) + self.shapes = np.array(shapes, dtype=np.float64) + self.im_files = list(cache.keys()) # update + self.label_files = img2label_paths(cache.keys()) # update + n = len(shapes) # number of images + bi = np.floor(np.arange(n) / batch_size).astype(np.int) # batch index + nb = bi[-1] + 1 # number of batches + self.batch = bi # batch index of image + self.n = n + self.indices = range(n) + + # Update labels + include_class = [] # filter labels to include only these classes (optional) + include_class_array = np.array(include_class).reshape(1, -1) + for i, (label, segment) in enumerate(zip(self.labels, self.segments)): + if include_class: + j = (label[:, 0:1] == include_class_array).any(1) + self.labels[i] = label[j] + if segment: + self.segments[i] = segment[j] + if single_cls: # single-class training, merge all classes into 0 + self.labels[i][:, 0] = 0 + if segment: + self.segments[i][:, 0] = 0 + + # Rectangular Training + if self.rect: + # Sort by aspect ratio + s = self.shapes # wh + ar = s[:, 1] / s[:, 0] # aspect ratio + irect = ar.argsort() + self.im_files = [self.im_files[i] for i in irect] + self.label_files = [self.label_files[i] for i in irect] + self.labels = [self.labels[i] for i in irect] + self.shapes = s[irect] # wh + ar = ar[irect] + + # Set training image shapes + shapes = [[1, 1]] * nb + for i in range(nb): + ari = ar[bi == i] + mini, maxi = ari.min(), ari.max() + if maxi < 1: + shapes[i] = [maxi, 1] + elif mini > 1: + shapes[i] = [1, 1 / mini] + + self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int) * stride + + # Cache images into RAM/disk for faster training (WARNING: large datasets may exceed system resources) + self.ims = [None] * n + self.npy_files = [Path(f).with_suffix(".npy") for f in self.im_files] + if cache_images: + gb = 0 # Gigabytes of cached images + self.im_hw0, self.im_hw = [None] * n, [None] * n + fcn = self.cache_images_to_disk if cache_images == "disk" else self.load_image + results = ThreadPool(NUM_THREADS).imap(fcn, range(n)) + pbar = tqdm(enumerate(results), total=n, bar_format=BAR_FORMAT) + for i, x in pbar: + if cache_images == "disk": + gb += self.npy_files[i].stat().st_size + else: # 'ram' + self.ims[i], self.im_hw0[i], self.im_hw[i] = x # im, hw_orig, hw_resized = load_image(self, i) + gb += self.ims[i].nbytes + pbar.desc = f"{prefix}Caching images ({gb / 1E9:.1f}GB {cache_images})" + pbar.close() + + def cache_labels(self, path=Path("./labels.cache"), prefix=""): + # Cache dataset labels, check images and read shapes + x = {} # dict + nm, nf, ne, nc, msgs = 0, 0, 0, 0, [] # number missing, found, empty, corrupt, messages + desc = f"{prefix}Scanning '{path.parent / path.stem}' images and labels..." + with Pool(NUM_THREADS) as pool: + pbar = tqdm( + pool.imap(verify_image_label, zip(self.im_files, self.label_files, repeat(prefix))), + desc=desc, + total=len(self.im_files), + bar_format=BAR_FORMAT, + ) + for im_file, lb, shape, segments, nm_f, nf_f, ne_f, nc_f, msg in pbar: + nm += nm_f + nf += nf_f + ne += ne_f + nc += nc_f + if im_file: + x[im_file] = [lb, shape, segments] + if msg: + msgs.append(msg) + pbar.desc = f"{desc}{nf} found, {nm} missing, {ne} empty, {nc} corrupt" + + pbar.close() + if msgs: + LOGGER.info("\n".join(msgs)) + if nf == 0: + LOGGER.warning(f"{prefix}WARNING: No labels found in {path}. See {HELP_URL}") + x["hash"] = get_hash(self.label_files + self.im_files) + x["results"] = nf, nm, ne, nc, len(self.im_files) + x["msgs"] = msgs # warnings + x["version"] = self.cache_version # cache version + try: + np.save(path, x) # save cache for next time + path.with_suffix(".cache.npy").rename(path) # remove .npy suffix + LOGGER.info(f"{prefix}New cache created: {path}") + except Exception as e: + LOGGER.warning(f"{prefix}WARNING: Cache directory {path.parent} is not writeable: {e}") # not writeable + return x + + def __len__(self): + return len(self.im_files) + + # def __iter__(self): + # self.count = -1 + # print('ran dataset iter') + # #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF) + # return self + + def __getitem__(self, index): + index = self.indices[index] # linear, shuffled, or image_weights + + hyp = self.hyp + mosaic = self.mosaic and random.random() < hyp["mosaic"] + if mosaic: + # Load mosaic + img, labels = self.load_mosaic(index) + shapes = None + + # MixUp augmentation + if random.random() < hyp["mixup"]: + img, labels = mixup(img, labels, *self.load_mosaic(random.randint(0, self.n - 1))) + + else: + # Load image + img, (h0, w0), (h, w) = self.load_image(index) + + # Letterbox + shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape + img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment) + shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling + + labels = self.labels[index].copy() + if labels.size: # normalized xywh to pixel xyxy format + labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1]) + + if self.augment: + img, labels = random_perspective( + img, + labels, + degrees=hyp["degrees"], + translate=hyp["translate"], + scale=hyp["scale"], + shear=hyp["shear"], + perspective=hyp["perspective"], + ) + + nl = len(labels) # number of labels + if nl: + labels[:, 1:5] = xyxy2xywhn(labels[:, 1:5], w=img.shape[1], h=img.shape[0], clip=True, eps=1e-3) + + if self.augment: + # Albumentations + img, labels = self.albumentations(img, labels) + nl = len(labels) # update after albumentations + + # HSV color-space + augment_hsv(img, hgain=hyp["hsv_h"], sgain=hyp["hsv_s"], vgain=hyp["hsv_v"]) + + # Flip up-down + if random.random() < hyp["flipud"]: + img = np.flipud(img) + if nl: + labels[:, 2] = 1 - labels[:, 2] + + # Flip left-right + if random.random() < hyp["fliplr"]: + img = np.fliplr(img) + if nl: + labels[:, 1] = 1 - labels[:, 1] + + # Cutouts + # labels = cutout(img, labels, p=0.5) + # nl = len(labels) # update after cutout + + labels_out = torch.zeros((nl, 6)) + if nl: + labels_out[:, 1:] = torch.from_numpy(labels) + + # Convert + img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB + img = np.ascontiguousarray(img) + + return torch.from_numpy(img), labels_out, self.im_files[index], shapes + + def load_image(self, i): + # Loads 1 image from dataset index 'i', returns (im, original hw, resized hw) + im, f, fn = ( + self.ims[i], + self.im_files[i], + self.npy_files[i], + ) + if im is None: # not cached in RAM + if fn.exists(): # load npy + im = np.load(fn) + else: # read image + im = cv2.imread(f) # BGR + assert im is not None, f"Image Not Found {f}" + h0, w0 = im.shape[:2] # orig hw + r = self.img_size / max(h0, w0) # ratio + if r != 1: # if sizes are not equal + im = cv2.resize( + im, + (int(w0 * r), int(h0 * r)), + interpolation=cv2.INTER_LINEAR if (self.augment or r > 1) else cv2.INTER_AREA, + ) + return im, (h0, w0), im.shape[:2] # im, hw_original, hw_resized + else: + return self.ims[i], self.im_hw0[i], self.im_hw[i] # im, hw_original, hw_resized + + def cache_images_to_disk(self, i): + # Saves an image as an *.npy file for faster loading + f = self.npy_files[i] + if not f.exists(): + np.save(f.as_posix(), cv2.imread(self.im_files[i])) + + def load_mosaic(self, index): + # YOLOv5 4-mosaic loader. Loads 1 image + 3 random images into a 4-image mosaic + labels4, segments4 = [], [] + s = self.img_size + yc, xc = (int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border) # mosaic center x, y + indices = [index] + random.choices(self.indices, k=3) # 3 additional image indices + random.shuffle(indices) + for i, index in enumerate(indices): + # Load image + img, _, (h, w) = self.load_image(index) + + # place img in img4 + if i == 0: # top left + img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles + x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image) + x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image) + elif i == 1: # top right + x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc + x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h + elif i == 2: # bottom left + x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h) + x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h) + elif i == 3: # bottom right + x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h) + x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h) + + img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax] + padw = x1a - x1b + padh = y1a - y1b + + # Labels + labels, segments = self.labels[index].copy(), self.segments[index].copy() + if labels.size: + labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh) # normalized xywh to pixel xyxy format + segments = [xyn2xy(x, w, h, padw, padh) for x in segments] + labels4.append(labels) + segments4.extend(segments) + + # Concat/clip labels + labels4 = np.concatenate(labels4, 0) + for x in (labels4[:, 1:], *segments4): + np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective() + # img4, labels4 = replicate(img4, labels4) # replicate + + # Augment + img4, labels4, segments4 = copy_paste(img4, labels4, segments4, p=self.hyp["copy_paste"]) + img4, labels4 = random_perspective( + img4, + labels4, + segments4, + degrees=self.hyp["degrees"], + translate=self.hyp["translate"], + scale=self.hyp["scale"], + shear=self.hyp["shear"], + perspective=self.hyp["perspective"], + border=self.mosaic_border, + ) # border to remove + + return img4, labels4 + + def load_mosaic9(self, index): + # YOLOv5 9-mosaic loader. Loads 1 image + 8 random images into a 9-image mosaic + labels9, segments9 = [], [] + s = self.img_size + indices = [index] + random.choices(self.indices, k=8) # 8 additional image indices + random.shuffle(indices) + hp, wp = -1, -1 # height, width previous + for i, index in enumerate(indices): + # Load image + img, _, (h, w) = self.load_image(index) + + # place img in img9 + if i == 0: # center + img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles + h0, w0 = h, w + c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates + elif i == 1: # top + c = s, s - h, s + w, s + elif i == 2: # top right + c = s + wp, s - h, s + wp + w, s + elif i == 3: # right + c = s + w0, s, s + w0 + w, s + h + elif i == 4: # bottom right + c = s + w0, s + hp, s + w0 + w, s + hp + h + elif i == 5: # bottom + c = s + w0 - w, s + h0, s + w0, s + h0 + h + elif i == 6: # bottom left + c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h + elif i == 7: # left + c = s - w, s + h0 - h, s, s + h0 + elif i == 8: # top left + c = s - w, s + h0 - hp - h, s, s + h0 - hp + + padx, pady = c[:2] + x1, y1, x2, y2 = (max(x, 0) for x in c) # allocate coords + + # Labels + labels, segments = self.labels[index].copy(), self.segments[index].copy() + if labels.size: + labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padx, pady) # normalized xywh to pixel xyxy format + segments = [xyn2xy(x, w, h, padx, pady) for x in segments] + labels9.append(labels) + segments9.extend(segments) + + # Image + img9[y1:y2, x1:x2] = img[y1 - pady :, x1 - padx :] # img9[ymin:ymax, xmin:xmax] + hp, wp = h, w # height, width previous + + # Offset + yc, xc = (int(random.uniform(0, s)) for _ in self.mosaic_border) # mosaic center x, y + img9 = img9[yc : yc + 2 * s, xc : xc + 2 * s] + + # Concat/clip labels + labels9 = np.concatenate(labels9, 0) + labels9[:, [1, 3]] -= xc + labels9[:, [2, 4]] -= yc + c = np.array([xc, yc]) # centers + segments9 = [x - c for x in segments9] + + for x in (labels9[:, 1:], *segments9): + np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective() + # img9, labels9 = replicate(img9, labels9) # replicate + + # Augment + img9, labels9 = random_perspective( + img9, + labels9, + segments9, + degrees=self.hyp["degrees"], + translate=self.hyp["translate"], + scale=self.hyp["scale"], + shear=self.hyp["shear"], + perspective=self.hyp["perspective"], + border=self.mosaic_border, + ) # border to remove + + return img9, labels9 + + @staticmethod + def collate_fn(batch): + im, label, path, shapes = zip(*batch) # transposed + for i, lb in enumerate(label): + lb[:, 0] = i # add target image index for build_targets() + return torch.stack(im, 0), torch.cat(label, 0), path, shapes + + @staticmethod + def collate_fn4(batch): + img, label, path, shapes = zip(*batch) # transposed + n = len(shapes) // 4 + im4, label4, path4, shapes4 = [], [], path[:n], shapes[:n] + + ho = torch.tensor([[0.0, 0, 0, 1, 0, 0]]) + wo = torch.tensor([[0.0, 0, 1, 0, 0, 0]]) + s = torch.tensor([[1, 1, 0.5, 0.5, 0.5, 0.5]]) # scale + for i in range(n): # zidane torch.zeros(16,3,720,1280) # BCHW + i *= 4 + if random.random() < 0.5: + im = F.interpolate(img[i].unsqueeze(0).float(), scale_factor=2.0, mode="bilinear", align_corners=False)[ + 0 + ].type(img[i].type()) + lb = label[i] + else: + im = torch.cat((torch.cat((img[i], img[i + 1]), 1), torch.cat((img[i + 2], img[i + 3]), 1)), 2) + lb = torch.cat((label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0) * s + im4.append(im) + label4.append(lb) + + for i, lb in enumerate(label4): + lb[:, 0] = i # add target image index for build_targets() + + return torch.stack(im4, 0), torch.cat(label4, 0), path4, shapes4 + + +# Ancillary functions -------------------------------------------------------------------------------------------------- +def create_folder(path="./new"): + # Create folder + if os.path.exists(path): + shutil.rmtree(path) # delete output folder + os.makedirs(path) # make new output folder + + +def flatten_recursive(path=DATASETS_DIR / "coco128"): + # Flatten a recursive directory by bringing all files to top level + new_path = Path(str(path) + "_flat") + create_folder(new_path) + for file in tqdm(glob.glob(str(Path(path)) + "/**/*.*", recursive=True)): + shutil.copyfile(file, new_path / Path(file).name) + + +def extract_boxes(path=DATASETS_DIR / "coco128"): # from utils.datasets import *; extract_boxes() + # Convert detection dataset into classification dataset, with one directory per class + path = Path(path) # images dir + shutil.rmtree(path / "classifier") if (path / "classifier").is_dir() else None # remove existing + files = list(path.rglob("*.*")) + n = len(files) # number of files + for im_file in tqdm(files, total=n): + if im_file.suffix[1:] in IMG_FORMATS: + # image + im = cv2.imread(str(im_file))[..., ::-1] # BGR to RGB + h, w = im.shape[:2] + + # labels + lb_file = Path(img2label_paths([str(im_file)])[0]) + if Path(lb_file).exists(): + with open(lb_file) as f: + lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32) # labels + + for j, x in enumerate(lb): + c = int(x[0]) # class + f = (path / "classifier") / f"{c}" / f"{path.stem}_{im_file.stem}_{j}.jpg" # new filename + if not f.parent.is_dir(): + f.parent.mkdir(parents=True) + + b = x[1:] * [w, h, w, h] # box + # b[2:] = b[2:].max() # rectangle to square + b[2:] = b[2:] * 1.2 + 3 # pad + b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int) + + b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image + b[[1, 3]] = np.clip(b[[1, 3]], 0, h) + assert cv2.imwrite(str(f), im[b[1] : b[3], b[0] : b[2]]), f"box failure in {f}" + + +def autosplit(path=DATASETS_DIR / "coco128/images", weights=(0.9, 0.1, 0.0), annotated_only=False): + """Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files + Usage: from utils.datasets import *; autosplit() + Arguments + path: Path to images directory + weights: Train, val, test weights (list, tuple) + annotated_only: Only use images with an annotated txt file + """ + path = Path(path) # images dir + files = sorted(x for x in path.rglob("*.*") if x.suffix[1:].lower() in IMG_FORMATS) # image files only + n = len(files) # number of files + random.seed(0) # for reproducibility + indices = random.choices([0, 1, 2], weights=weights, k=n) # assign each image to a split + + txt = ["autosplit_train.txt", "autosplit_val.txt", "autosplit_test.txt"] # 3 txt files + [(path.parent / x).unlink(missing_ok=True) for x in txt] # remove existing + + print(f"Autosplitting images from {path}" + ", using *.txt labeled images only" * annotated_only) + for i, img in tqdm(zip(indices, files), total=n): + if not annotated_only or Path(img2label_paths([str(img)])[0]).exists(): # check label + with open(path.parent / txt[i], "a") as f: + f.write("./" + img.relative_to(path.parent).as_posix() + "\n") # add image to txt file + + +def verify_image_label(args): + # Verify one image-label pair + im_file, lb_file, prefix = args + nm, nf, ne, nc, msg, segments = 0, 0, 0, 0, "", [] # number (missing, found, empty, corrupt), message, segments + try: + # verify images + im = Image.open(im_file) + im.verify() # PIL verify + shape = exif_size(im) # image size + assert (shape[0] > 9) & (shape[1] > 9), f"image size {shape} <10 pixels" + assert im.format.lower() in IMG_FORMATS, f"invalid image format {im.format}" + if im.format.lower() in ("jpg", "jpeg"): + with open(im_file, "rb") as f: + f.seek(-2, 2) + if f.read() != b"\xff\xd9": # corrupt JPEG + ImageOps.exif_transpose(Image.open(im_file)).save(im_file, "JPEG", subsampling=0, quality=100) + msg = f"{prefix}WARNING: {im_file}: corrupt JPEG restored and saved" + + # verify labels + if os.path.isfile(lb_file): + nf = 1 # label found + with open(lb_file) as f: + lb = [x.split() for x in f.read().strip().splitlines() if len(x)] + if any(len(x) > 6 for x in lb): # is segment + classes = np.array([x[0] for x in lb], dtype=np.float32) + segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in lb] # (cls, xy1...) + lb = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh) + lb = np.array(lb, dtype=np.float32) + nl = len(lb) + if nl: + assert lb.shape[1] == 5, f"labels require 5 columns, {lb.shape[1]} columns detected" + assert (lb >= 0).all(), f"negative label values {lb[lb < 0]}" + assert (lb[:, 1:] <= 1).all(), f"non-normalized or out of bounds coordinates {lb[:, 1:][lb[:, 1:] > 1]}" + _, i = np.unique(lb, axis=0, return_index=True) + if len(i) < nl: # duplicate row check + lb = lb[i] # remove duplicates + if segments: + segments = segments[i] + msg = f"{prefix}WARNING: {im_file}: {nl - len(i)} duplicate labels removed" + else: + ne = 1 # label empty + lb = np.zeros((0, 5), dtype=np.float32) + else: + nm = 1 # label missing + lb = np.zeros((0, 5), dtype=np.float32) + return im_file, lb, shape, segments, nm, nf, ne, nc, msg + except Exception as e: + nc = 1 + msg = f"{prefix}WARNING: {im_file}: ignoring corrupt image/label: {e}" + return [None, None, None, None, nm, nf, ne, nc, msg] + + +def dataset_stats(path="coco128.yaml", autodownload=False, verbose=False, profile=False, hub=False): + """Return dataset statistics dictionary with images and instances counts per split per class + To run in parent directory: export PYTHONPATH="$PWD/yolov5" + Usage1: from utils.datasets import *; dataset_stats('coco128.yaml', autodownload=True) + Usage2: from utils.datasets import *; dataset_stats('path/to/coco128_with_yaml.zip') + Arguments + path: Path to data.yaml or data.zip (with data.yaml inside data.zip) + autodownload: Attempt to download dataset if not found locally + verbose: Print stats dictionary + """ + + def round_labels(labels): + # Update labels to integer class and 6 decimal place floats + return [[int(c), *(round(x, 4) for x in points)] for c, *points in labels] + + def unzip(path): + # Unzip data.zip TODO: CONSTRAINT: path/to/abc.zip MUST unzip to 'path/to/abc/' + if str(path).endswith(".zip"): # path is data.zip + assert Path(path).is_file(), f"Error unzipping {path}, file not found" + ZipFile(path).extractall(path=path.parent) # unzip + dir = path.with_suffix("") # dataset directory == zip name + return True, str(dir), next(dir.rglob("*.yaml")) # zipped, data_dir, yaml_path + else: # path is data.yaml + return False, None, path + + def hub_ops(f, max_dim=1920): + # HUB ops for 1 image 'f': resize and save at reduced quality in /dataset-hub for web/app viewing + f_new = im_dir / Path(f).name # dataset-hub image filename + try: # use PIL + im = Image.open(f) + r = max_dim / max(im.height, im.width) # ratio + if r < 1.0: # image too large + im = im.resize((int(im.width * r), int(im.height * r))) + im.save(f_new, "JPEG", quality=75, optimize=True) # save + except Exception as e: # use OpenCV + print(f"WARNING: HUB ops PIL failure {f}: {e}") + im = cv2.imread(f) + im_height, im_width = im.shape[:2] + r = max_dim / max(im_height, im_width) # ratio + if r < 1.0: # image too large + im = cv2.resize(im, (int(im_width * r), int(im_height * r)), interpolation=cv2.INTER_AREA) + cv2.imwrite(str(f_new), im) + + zipped, data_dir, yaml_path = unzip(Path(path)) + with open(check_yaml(yaml_path), errors="ignore") as f: + data = yaml.safe_load(f) # data dict + if zipped: + data["path"] = data_dir # TODO: should this be dir.resolve()? + check_dataset(data, autodownload) # download dataset if missing + hub_dir = Path(data["path"] + ("-hub" if hub else "")) + stats = {"nc": data["nc"], "names": data["names"]} # statistics dictionary + for split in "train", "val", "test": + if data.get(split) is None: + stats[split] = None # i.e. no test set + continue + x = [] + dataset = LoadImagesAndLabels(data[split]) # load dataset + for label in tqdm(dataset.labels, total=dataset.n, desc="Statistics"): + x.append(np.bincount(label[:, 0].astype(int), minlength=data["nc"])) + x = np.array(x) # shape(128x80) + stats[split] = { + "instance_stats": {"total": int(x.sum()), "per_class": x.sum(0).tolist()}, + "image_stats": { + "total": dataset.n, + "unlabelled": int(np.all(x == 0, 1).sum()), + "per_class": (x > 0).sum(0).tolist(), + }, + "labels": [{str(Path(k).name): round_labels(v.tolist())} for k, v in zip(dataset.im_files, dataset.labels)], + } + + if hub: + im_dir = hub_dir / "images" + im_dir.mkdir(parents=True, exist_ok=True) + for _ in tqdm(ThreadPool(NUM_THREADS).imap(hub_ops, dataset.im_files), total=dataset.n, desc="HUB Ops"): + pass + + # Profile + stats_path = hub_dir / "stats.json" + if profile: + for _ in range(1): + file = stats_path.with_suffix(".npy") + t1 = time.time() + np.save(file, stats) + t2 = time.time() + x = np.load(file, allow_pickle=True) + print(f"stats.npy times: {time.time() - t2:.3f}s read, {t2 - t1:.3f}s write") + + file = stats_path.with_suffix(".json") + t1 = time.time() + with open(file, "w") as f: + json.dump(stats, f) # save stats *.json + t2 = time.time() + with open(file) as f: + x = json.load(f) # load hyps dict + print(f"stats.json times: {time.time() - t2:.3f}s read, {t2 - t1:.3f}s write") + + # Save, print and return + if hub: + print(f"Saving {stats_path.resolve()}...") + with open(stats_path, "w") as f: + json.dump(stats, f) # save stats.json + if verbose: + print(json.dumps(stats, indent=2, sort_keys=False)) + return stats diff --git a/core/vision/yolov5/utils/downloads.py b/core/vision/yolov5/utils/downloads.py new file mode 100644 index 00000000..d7b87cb2 --- /dev/null +++ b/core/vision/yolov5/utils/downloads.py @@ -0,0 +1,153 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Download utils +""" + +import os +import platform +import subprocess +import time +import urllib +from pathlib import Path +from zipfile import ZipFile + +import requests +import torch + + +def gsutil_getsize(url=''): + # gs://bucket/file size https://cloud.google.com/storage/docs/gsutil/commands/du + s = subprocess.check_output(f'gsutil du {url}', shell=True).decode('utf-8') + return eval(s.split(' ')[0]) if len(s) else 0 # bytes + + +def safe_download(file, url, url2=None, min_bytes=1E0, error_msg=''): + # Attempts to download file from url or url2, checks and removes incomplete downloads < min_bytes + file = Path(file) + assert_msg = f"Downloaded file '{file}' does not exist or size is < min_bytes={min_bytes}" + try: # url1 + print(f'Downloading {url} to {file}...') + torch.hub.download_url_to_file(url, str(file)) + assert file.exists() and file.stat().st_size > min_bytes, assert_msg # check + except Exception as e: # url2 + file.unlink(missing_ok=True) # remove partial downloads + print(f'ERROR: {e}\nRe-attempting {url2 or url} to {file}...') + os.system(f"curl -L '{url2 or url}' -o '{file}' --retry 3 -C -") # curl download, retry and resume on fail + finally: + if not file.exists() or file.stat().st_size < min_bytes: # check + file.unlink(missing_ok=True) # remove partial downloads + print(f"ERROR: {assert_msg}\n{error_msg}") + print('') + + +def attempt_download(file, repo='ultralytics/yolov5'): # from utils.downloads import *; attempt_download() + # Attempt file download if does not exist + file = Path(str(file).strip().replace("'", '')) + + if not file.exists(): + # URL specified + name = Path(urllib.parse.unquote(str(file))).name # decode '%2F' to '/' etc. + if str(file).startswith(('http:/', 'https:/')): # download + url = str(file).replace(':/', '://') # Pathlib turns :// -> :/ + file = name.split('?')[0] # parse authentication https://url.com/file.txt?auth... + if Path(file).is_file(): + print(f'Found {url} locally at {file}') # file already exists + else: + safe_download(file=file, url=url, min_bytes=1E5) + return file + + # GitHub assets + file.parent.mkdir(parents=True, exist_ok=True) # make parent dir (if required) + try: + response = requests.get(f'https://api.github.com/repos/{repo}/releases/latest').json() # github api + assets = [x['name'] for x in response['assets']] # release assets, i.e. ['yolov5s.pt', 'yolov5m.pt', ...] + tag = response['tag_name'] # i.e. 'v1.0' + except Exception: # fallback plan + assets = ['yolov5n.pt', 'yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt', + 'yolov5n6.pt', 'yolov5s6.pt', 'yolov5m6.pt', 'yolov5l6.pt', 'yolov5x6.pt'] + try: + tag = subprocess.check_output('git tag', shell=True, stderr=subprocess.STDOUT).decode().split()[-1] + except Exception: + tag = 'v6.0' # current release + + if name in assets: + safe_download(file, + url=f'https://github.com/{repo}/releases/download/{tag}/{name}', + # url2=f'https://storage.googleapis.com/{repo}/ckpt/{name}', # backup url (optional) + min_bytes=1E5, + error_msg=f'{file} missing, try downloading from https://github.com/{repo}/releases/') + + return str(file) + + +def gdrive_download(id='16TiPfZj7htmTyhntwcZyEEAejOUxuT6m', file='tmp.zip'): + # Downloads a file from Google Drive. from yolov5.utils.downloads import *; gdrive_download() + t = time.time() + file = Path(file) + cookie = Path('cookie') # gdrive cookie + print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='') + file.unlink(missing_ok=True) # remove existing file + cookie.unlink(missing_ok=True) # remove existing cookie + + # Attempt file download + out = "NUL" if platform.system() == "Windows" else "/dev/null" + os.system(f'curl -c ./cookie -s -L "drive.google.com/uc?export=download&id={id}" > {out}') + if os.path.exists('cookie'): # large file + s = f'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm={get_token()}&id={id}" -o {file}' + else: # small file + s = f'curl -s -L -o {file} "drive.google.com/uc?export=download&id={id}"' + r = os.system(s) # execute, capture return + cookie.unlink(missing_ok=True) # remove existing cookie + + # Error check + if r != 0: + file.unlink(missing_ok=True) # remove partial + print('Download error ') # raise Exception('Download error') + return r + + # Unzip if archive + if file.suffix == '.zip': + print('unzipping... ', end='') + ZipFile(file).extractall(path=file.parent) # unzip + file.unlink() # remove zip + + print(f'Done ({time.time() - t:.1f}s)') + return r + + +def get_token(cookie="./cookie"): + with open(cookie) as f: + for line in f: + if "download" in line: + return line.split()[-1] + return "" + +# Google utils: https://cloud.google.com/storage/docs/reference/libraries ---------------------------------------------- +# +# +# def upload_blob(bucket_name, source_file_name, destination_blob_name): +# # Uploads a file to a bucket +# # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python +# +# storage_client = storage.Client() +# bucket = storage_client.get_bucket(bucket_name) +# blob = bucket.blob(destination_blob_name) +# +# blob.upload_from_filename(source_file_name) +# +# print('File {} uploaded to {}.'.format( +# source_file_name, +# destination_blob_name)) +# +# +# def download_blob(bucket_name, source_blob_name, destination_file_name): +# # Uploads a blob from a bucket +# storage_client = storage.Client() +# bucket = storage_client.get_bucket(bucket_name) +# blob = bucket.blob(source_blob_name) +# +# blob.download_to_filename(destination_file_name) +# +# print('Blob {} downloaded to {}.'.format( +# source_blob_name, +# destination_file_name)) diff --git a/core/vision/yolov5/utils/flask_rest_api/README.md b/core/vision/yolov5/utils/flask_rest_api/README.md new file mode 100644 index 00000000..a726acbd --- /dev/null +++ b/core/vision/yolov5/utils/flask_rest_api/README.md @@ -0,0 +1,73 @@ +# Flask REST API + +[REST](https://en.wikipedia.org/wiki/Representational_state_transfer) [API](https://en.wikipedia.org/wiki/API)s are +commonly used to expose Machine Learning (ML) models to other services. This folder contains an example REST API +created using Flask to expose the YOLOv5s model from [PyTorch Hub](https://pytorch.org/hub/ultralytics_yolov5/). + +## Requirements + +[Flask](https://palletsprojects.com/p/flask/) is required. Install with: + +```shell +$ pip install Flask +``` + +## Run + +After Flask installation run: + +```shell +$ python3 restapi.py --port 5000 +``` + +Then use [curl](https://curl.se/) to perform a request: + +```shell +$ curl -X POST -F image=@zidane.jpg 'http://localhost:5000/v1/object-detection/yolov5s' +``` + +The model inference results are returned as a JSON response: + +```json +[ + { + "class": 0, + "confidence": 0.8900438547, + "height": 0.9318675399, + "name": "person", + "width": 0.3264600933, + "xcenter": 0.7438579798, + "ycenter": 0.5207948685 + }, + { + "class": 0, + "confidence": 0.8440024257, + "height": 0.7155083418, + "name": "person", + "width": 0.6546785235, + "xcenter": 0.427829951, + "ycenter": 0.6334488392 + }, + { + "class": 27, + "confidence": 0.3771208823, + "height": 0.3902671337, + "name": "tie", + "width": 0.0696444362, + "xcenter": 0.3675483763, + "ycenter": 0.7991207838 + }, + { + "class": 27, + "confidence": 0.3527112305, + "height": 0.1540903747, + "name": "tie", + "width": 0.0336618312, + "xcenter": 0.7814827561, + "ycenter": 0.5065554976 + } +] +``` + +An example python script to perform inference using [requests](https://docs.python-requests.org/en/master/) is given +in `example_request.py` diff --git a/core/vision/yolov5/utils/flask_rest_api/example_request.py b/core/vision/yolov5/utils/flask_rest_api/example_request.py new file mode 100644 index 00000000..ff21f30f --- /dev/null +++ b/core/vision/yolov5/utils/flask_rest_api/example_request.py @@ -0,0 +1,13 @@ +"""Perform test request""" +import pprint + +import requests + +DETECTION_URL = "http://localhost:5000/v1/object-detection/yolov5s" +TEST_IMAGE = "zidane.jpg" + +image_data = open(TEST_IMAGE, "rb").read() + +response = requests.post(DETECTION_URL, files={"image": image_data}).json() + +pprint.pprint(response) diff --git a/core/vision/yolov5/utils/flask_rest_api/restapi.py b/core/vision/yolov5/utils/flask_rest_api/restapi.py new file mode 100644 index 00000000..b93ad16a --- /dev/null +++ b/core/vision/yolov5/utils/flask_rest_api/restapi.py @@ -0,0 +1,37 @@ +""" +Run a rest API exposing the yolov5s object detection model +""" +import argparse +import io + +import torch +from flask import Flask, request +from PIL import Image + +app = Flask(__name__) + +DETECTION_URL = "/v1/object-detection/yolov5s" + + +@app.route(DETECTION_URL, methods=["POST"]) +def predict(): + if not request.method == "POST": + return + + if request.files.get("image"): + image_file = request.files["image"] + image_bytes = image_file.read() + + img = Image.open(io.BytesIO(image_bytes)) + + results = model(img, size=640) # reduce size=320 for faster inference + return results.pandas().xyxy[0].to_json(orient="records") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Flask API exposing YOLOv5 model") + parser.add_argument("--port", default=5000, type=int, help="port number") + args = parser.parse_args() + + model = torch.hub.load("ultralytics/yolov5", "yolov5s", force_reload=True) # force_reload to recache + app.run(host="0.0.0.0", port=args.port) # debug=True causes Restarting with stat diff --git a/core/vision/yolov5/utils/general.py b/core/vision/yolov5/utils/general.py new file mode 100644 index 00000000..233e88e3 --- /dev/null +++ b/core/vision/yolov5/utils/general.py @@ -0,0 +1,1017 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +General utils +""" + +import contextlib +import glob +import logging +import math +import os +import platform +import random +import re +import shutil +import signal +import time +import urllib +from datetime import datetime +from itertools import repeat +from multiprocessing.pool import ThreadPool +from pathlib import Path +from subprocess import check_output +from zipfile import ZipFile + +import cv2 +import numpy as np +import pandas as pd +import pkg_resources as pkg +import torch +import torchvision +import yaml + +from utils.downloads import gsutil_getsize +from utils.metrics import box_iou, fitness + +# Settings +FILE = Path(__file__).resolve() +ROOT = FILE.parents[1] # YOLOv5 root directory +DATASETS_DIR = ROOT.parent / "datasets" # YOLOv5 datasets directory +NUM_THREADS = min(8, max(1, os.cpu_count() - 1)) # number of YOLOv5 multiprocessing threads +VERBOSE = str(os.getenv("YOLOv5_VERBOSE", True)).lower() == "true" # global verbose mode +FONT = "Arial.ttf" # https://ultralytics.com/assets/Arial.ttf + +torch.set_printoptions(linewidth=320, precision=5, profile="long") +np.set_printoptions(linewidth=320, formatter={"float_kind": "{:11.5g}".format}) # format short g, %precision=5 +pd.options.display.max_columns = 10 +cv2.setNumThreads(0) # prevent OpenCV from multithreading (incompatible with PyTorch DataLoader) +os.environ["NUMEXPR_MAX_THREADS"] = str(NUM_THREADS) # NumExpr max threads +os.environ["OMP_NUM_THREADS"] = str(NUM_THREADS) # OpenMP max threads (PyTorch and SciPy) + + +def is_kaggle(): + # Is environment a Kaggle Notebook? + try: + assert os.environ.get("PWD") == "/kaggle/working" + assert os.environ.get("KAGGLE_URL_BASE") == "https://www.kaggle.com" + return True + except AssertionError: + return False + + +def is_writeable(dir, test=False): + # Return True if directory has write permissions, test opening a file with write permissions if test=True + if test: # method 1 + file = Path(dir) / "tmp.txt" + try: + with open(file, "w"): # open file with write permissions + pass + file.unlink() # remove file + return True + except OSError: + return False + else: # method 2 + return os.access(dir, os.R_OK) # possible issues on Windows + + +def set_logging(name=None, verbose=VERBOSE): + # Sets level and returns logger + if is_kaggle(): + for h in logging.root.handlers: + logging.root.removeHandler(h) # remove all handlers associated with the root logger object + rank = int(os.getenv("RANK", -1)) # rank in world for Multi-GPU trainings + logging.basicConfig(format="%(message)s", level=logging.INFO if (verbose and rank in (-1, 0)) else logging.WARNING) + return logging.getLogger(name) + + +LOGGER = set_logging("yolov5") # define globally (used in train.py, val.py, detect.py, etc.) + + +def user_config_dir(dir="Ultralytics", env_var="YOLOV5_CONFIG_DIR"): + # Return path of user configuration directory. Prefer environment variable if exists. Make dir if required. + env = os.getenv(env_var) + if env: + path = Path(env) # use environment variable + else: + cfg = {"Windows": "AppData/Roaming", "Linux": ".config", "Darwin": "Library/Application Support"} # 3 OS dirs + path = Path.home() / cfg.get(platform.system(), "") # OS-specific config dir + path = (path if is_writeable(path) else Path("/tmp")) / dir # GCP and AWS lambda fix, only /tmp is writeable + path.mkdir(exist_ok=True) # make if required + return path + + +CONFIG_DIR = user_config_dir() # Ultralytics settings dir + + +class Profile(contextlib.ContextDecorator): + # Usage: @Profile() decorator or 'with Profile():' context manager + def __enter__(self): + self.start = time.time() + + def __exit__(self, type, value, traceback): + print(f"Profile results: {time.time() - self.start:.5f}s") + + +class Timeout(contextlib.ContextDecorator): + # Usage: @Timeout(seconds) decorator or 'with Timeout(seconds):' context manager + def __init__(self, seconds, *, timeout_msg="", suppress_timeout_errors=True): + self.seconds = int(seconds) + self.timeout_message = timeout_msg + self.suppress = bool(suppress_timeout_errors) + + def _timeout_handler(self, signum, frame): + raise TimeoutError(self.timeout_message) + + def __enter__(self): + if platform.system() != "Windows": # not supported on Windows + signal.signal(signal.SIGALRM, self._timeout_handler) # Set handler for SIGALRM + signal.alarm(self.seconds) # start countdown for SIGALRM to be raised + + def __exit__(self, exc_type, exc_val, exc_tb): + if platform.system() != "Windows": + signal.alarm(0) # Cancel SIGALRM if it's scheduled + if self.suppress and exc_type is TimeoutError: # Suppress TimeoutError + return True + + +class WorkingDirectory(contextlib.ContextDecorator): + # Usage: @WorkingDirectory(dir) decorator or 'with WorkingDirectory(dir):' context manager + def __init__(self, new_dir): + self.dir = new_dir # new dir + self.cwd = Path.cwd().resolve() # current dir + + def __enter__(self): + os.chdir(self.dir) + + def __exit__(self, exc_type, exc_val, exc_tb): + os.chdir(self.cwd) + + +def try_except(func): + # try-except function. Usage: @try_except decorator + def handler(*args, **kwargs): + try: + func(*args, **kwargs) + except Exception as e: + print(e) + + return handler + + +def methods(instance): + # Get class/instance methods + return [f for f in dir(instance) if callable(getattr(instance, f)) and not f.startswith("__")] + + +def print_args(name, opt): + # Print argparser arguments + LOGGER.info(colorstr(f"{name}: ") + ", ".join(f"{k}={v}" for k, v in vars(opt).items())) + + +def init_seeds(seed=0): + # Initialize random number generator (RNG) seeds https://pytorch.org/docs/stable/notes/randomness.html + # cudnn seed 0 settings are slower and more reproducible, else faster and less reproducible + import torch.backends.cudnn as cudnn + + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + cudnn.benchmark, cudnn.deterministic = (False, True) if seed == 0 else (True, False) + + +def intersect_dicts(da, db, exclude=()): + # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values + return {k: v for k, v in da.items() if k in db and not any(x in k for x in exclude) and v.shape == db[k].shape} + + +def get_latest_run(search_dir="."): + # Return path to most recent 'last.pt' in /runs (i.e. to --resume from) + last_list = glob.glob(f"{search_dir}/**/last*.pt", recursive=True) + return max(last_list, key=os.path.getctime) if last_list else "" + + +def is_docker(): + # Is environment a Docker container? + return Path("/workspace").exists() # or Path('/.dockerenv').exists() + + +def is_colab(): + # Is environment a Google Colab instance? + try: + import google.colab + + return True + except ImportError: + return False + + +def is_pip(): + # Is file in a pip package? + return "site-packages" in Path(__file__).resolve().parts + + +def is_ascii(s=""): + # Is string composed of all ASCII (no UTF) characters? (note str().isascii() introduced in python 3.7) + s = str(s) # convert list, tuple, None, etc. to str + return len(s.encode().decode("ascii", "ignore")) == len(s) + + +def is_chinese(s="人工智能"): + # Is string composed of any Chinese characters? + return True if re.search("[\u4e00-\u9fff]", str(s)) else False + + +def emojis(str=""): + # Return platform-dependent emoji-safe version of string + return str.encode().decode("ascii", "ignore") if platform.system() == "Windows" else str + + +def file_age(path=__file__): + # Return days since last file update + dt = datetime.now() - datetime.fromtimestamp(Path(path).stat().st_mtime) # delta + return dt.days # + dt.seconds / 86400 # fractional days + + +def file_update_date(path=__file__): + # Return human-readable file modification date, i.e. '2021-3-26' + t = datetime.fromtimestamp(Path(path).stat().st_mtime) + return f"{t.year}-{t.month}-{t.day}" + + +def file_size(path): + # Return file/dir size (MB) + mb = 1 << 20 # bytes to MiB (1024 ** 2) + path = Path(path) + if path.is_file(): + return path.stat().st_size / mb + elif path.is_dir(): + return sum(f.stat().st_size for f in path.glob("**/*") if f.is_file()) / mb + else: + return 0.0 + + +def check_online(): + # Check internet connectivity + import socket + + try: + socket.create_connection(("1.1.1.1", 443), 5) # check host accessibility + return True + except OSError: + return False + + +def git_describe(path=ROOT): # path must be a directory + # Return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe + try: + return check_output(f"git -C {path} describe --tags --long --always", shell=True).decode()[:-1] + except Exception: + return "" + + +@try_except +@WorkingDirectory(ROOT) +def check_git_status(): + # Recommend 'git pull' if code is out of date + msg = ", for updates see https://github.com/ultralytics/yolov5" + s = colorstr("github: ") # string + assert Path(".git").exists(), s + "skipping check (not a git repository)" + msg + assert not is_docker(), s + "skipping check (Docker image)" + msg + assert check_online(), s + "skipping check (offline)" + msg + + cmd = "git fetch && git config --get remote.origin.url" + url = check_output(cmd, shell=True, timeout=5).decode().strip().rstrip(".git") # git fetch + branch = check_output("git rev-parse --abbrev-ref HEAD", shell=True).decode().strip() # checked out + n = int(check_output(f"git rev-list {branch}..origin/master --count", shell=True)) # commits behind + if n > 0: + s += f"⚠️ YOLOv5 is out of date by {n} commit{'s' * (n > 1)}. Use `git pull` or `git clone {url}` to update." + else: + s += f"up to date with {url} ✅" + LOGGER.info(emojis(s)) # emoji-safe + + +def check_python(minimum="3.6.2"): + # Check current python version vs. required python version + check_version(platform.python_version(), minimum, name="Python ", hard=True) + + +def check_version(current="0.0.0", minimum="0.0.0", name="version ", pinned=False, hard=False, verbose=False): + # Check version vs. required version + current, minimum = (pkg.parse_version(x) for x in (current, minimum)) + result = (current == minimum) if pinned else (current >= minimum) # bool + s = f"{name}{minimum} required by YOLOv5, but {name}{current} is currently installed" # string + if hard: + assert result, s # assert min requirements met + if verbose and not result: + LOGGER.warning(s) + return result + + +@try_except +def check_requirements(requirements=ROOT / "requirements.txt", exclude=(), install=True): + # Check installed dependencies meet requirements (pass *.txt file or list of packages) + prefix = colorstr("red", "bold", "requirements:") + check_python() # check python version + if isinstance(requirements, (str, Path)): # requirements.txt file + file = Path(requirements) + assert file.exists(), f"{prefix} {file.resolve()} not found, check failed." + with file.open() as f: + requirements = [f"{x.name}{x.specifier}" for x in pkg.parse_requirements(f) if x.name not in exclude] + else: # list or tuple of packages + requirements = [x for x in requirements if x not in exclude] + + n = 0 # number of packages updates + for r in requirements: + try: + pkg.require(r) + except Exception: # DistributionNotFound or VersionConflict if requirements not met + s = f"{prefix} {r} not found and is required by YOLOv5" + if install: + LOGGER.info(f"{s}, attempting auto-update...") + try: + assert check_online(), f"'pip install {r}' skipped (offline)" + LOGGER.info(check_output(f"pip install '{r}'", shell=True).decode()) + n += 1 + except Exception as e: + LOGGER.warning(f"{prefix} {e}") + else: + LOGGER.info(f"{s}. Please install and rerun your command.") + + if n: # if packages updated + source = file.resolve() if "file" in locals() else requirements + s = ( + f"{prefix} {n} package{'s' * (n > 1)} updated per {source}\n" + f"{prefix} ⚠️ {colorstr('bold', 'Restart runtime or rerun command for updates to take effect')}\n" + ) + LOGGER.info(emojis(s)) + + +def check_img_size(imgsz, s=32, floor=0): + # Verify image size is a multiple of stride s in each dimension + if isinstance(imgsz, int): # integer i.e. img_size=640 + new_size = max(make_divisible(imgsz, int(s)), floor) + else: # list i.e. img_size=[640, 480] + new_size = [max(make_divisible(x, int(s)), floor) for x in imgsz] + if new_size != imgsz: + LOGGER.warning(f"WARNING: --img-size {imgsz} must be multiple of max stride {s}, updating to {new_size}") + return new_size + + +def check_imshow(): + # Check if environment supports image displays + try: + assert not is_docker(), "cv2.imshow() is disabled in Docker environments" + assert not is_colab(), "cv2.imshow() is disabled in Google Colab environments" + cv2.imshow("test", np.zeros((1, 1, 3))) + cv2.waitKey(1) + cv2.destroyAllWindows() + cv2.waitKey(1) + return True + except Exception as e: + LOGGER.warning(f"WARNING: Environment does not support cv2.imshow() or PIL Image.show() image displays\n{e}") + return False + + +def check_suffix(file="yolov5s.pt", suffix=(".pt",), msg=""): + # Check file(s) for acceptable suffix + if file and suffix: + if isinstance(suffix, str): + suffix = [suffix] + for f in file if isinstance(file, (list, tuple)) else [file]: + s = Path(f).suffix.lower() # file suffix + if len(s): + assert s in suffix, f"{msg}{f} acceptable suffix is {suffix}" + + +def check_yaml(file, suffix=(".yaml", ".yml")): + # Search/download YAML file (if necessary) and return path, checking suffix + return check_file(file, suffix) + + +def check_file(file, suffix=""): + # Search/download file (if necessary) and return path + check_suffix(file, suffix) # optional + file = str(file) # convert to str() + if Path(file).is_file() or file == "": # exists + return file + elif file.startswith(("http:/", "https:/")): # download + url = str(Path(file)).replace(":/", "://") # Pathlib turns :// -> :/ + file = Path(urllib.parse.unquote(file).split("?")[0]).name # '%2F' to '/', split https://url.com/file.txt?auth + if Path(file).is_file(): + LOGGER.info(f"Found {url} locally at {file}") # file already exists + else: + LOGGER.info(f"Downloading {url} to {file}...") + torch.hub.download_url_to_file(url, file) + assert Path(file).exists() and Path(file).stat().st_size > 0, f"File download failed: {url}" # check + return file + else: # search + files = [] + for d in "data", "models", "utils": # search directories + files.extend(glob.glob(str(ROOT / d / "**" / file), recursive=True)) # find file + assert len(files), f"File not found: {file}" # assert file was found + assert len(files) == 1, f"Multiple files match '{file}', specify exact path: {files}" # assert unique + return files[0] # return file + + +def check_font(font=FONT): + # Download font to CONFIG_DIR if necessary + font = Path(font) + if not font.exists() and not (CONFIG_DIR / font.name).exists(): + url = "https://ultralytics.com/assets/" + font.name + LOGGER.info(f"Downloading {url} to {CONFIG_DIR / font.name}...") + torch.hub.download_url_to_file(url, str(font), progress=False) + + +def check_dataset(data, autodownload=True): + # Download and/or unzip dataset if not found locally + # Usage: https://github.com/ultralytics/yolov5/releases/download/v1.0/coco128_with_yaml.zip + + # Download (optional) + extract_dir = "" + if isinstance(data, (str, Path)) and str(data).endswith(".zip"): # i.e. gs://bucket/dir/coco128.zip + download(data, dir=DATASETS_DIR, unzip=True, delete=False, curl=False, threads=1) + data = next((DATASETS_DIR / Path(data).stem).rglob("*.yaml")) + extract_dir, autodownload = data.parent, False + + # Read yaml (optional) + if isinstance(data, (str, Path)): + with open(data, errors="ignore") as f: + data = yaml.safe_load(f) # dictionary + + # Resolve paths + path = Path(extract_dir or data.get("path") or "") # optional 'path' default to '.' + if not path.is_absolute(): + path = (ROOT / path).resolve() + for k in "train", "val", "test": + if data.get(k): # prepend path + data[k] = str(path / data[k]) if isinstance(data[k], str) else [str(path / x) for x in data[k]] + + # Parse yaml + assert "nc" in data, "Dataset 'nc' key missing." + if "names" not in data: + data["names"] = [f"class{i}" for i in range(data["nc"])] # assign class names if missing + train, val, test, s = (data.get(x) for x in ("train", "val", "test", "download")) + if val: + val = [Path(x).resolve() for x in (val if isinstance(val, list) else [val])] # val path + if not all(x.exists() for x in val): + LOGGER.info("\nDataset not found, missing paths: %s" % [str(x) for x in val if not x.exists()]) + if s and autodownload: # download script + root = path.parent if "path" in data else ".." # unzip directory i.e. '../' + if s.startswith("http") and s.endswith(".zip"): # URL + f = Path(s).name # filename + LOGGER.info(f"Downloading {s} to {f}...") + torch.hub.download_url_to_file(s, f) + Path(root).mkdir(parents=True, exist_ok=True) # create root + ZipFile(f).extractall(path=root) # unzip + Path(f).unlink() # remove zip + r = None # success + elif s.startswith("bash "): # bash script + LOGGER.info(f"Running {s} ...") + r = os.system(s) + else: # python script + r = exec(s, {"yaml": data}) # return None + LOGGER.info(f"Dataset autodownload {f'success, saved to {root}' if r in (0, None) else 'failure'}\n") + else: + raise Exception("Dataset not found.") + + return data # dictionary + + +def url2file(url): + # Convert URL to filename, i.e. https://url.com/file.txt?auth -> file.txt + url = str(Path(url)).replace(":/", "://") # Pathlib turns :// -> :/ + file = Path(urllib.parse.unquote(url)).name.split("?")[0] # '%2F' to '/', split https://url.com/file.txt?auth + return file + + +def download(url, dir=".", unzip=True, delete=True, curl=False, threads=1): + # Multi-threaded file download and unzip function, used in data.yaml for autodownload + def download_one(url, dir): + # Download 1 file + f = dir / Path(url).name # filename + if Path(url).is_file(): # exists in current path + Path(url).rename(f) # move to dir + elif not f.exists(): + LOGGER.info(f"Downloading {url} to {f}...") + if curl: + os.system(f"curl -L '{url}' -o '{f}' --retry 9 -C -") # curl download, retry and resume on fail + else: + torch.hub.download_url_to_file(url, f, progress=True) # torch download + if unzip and f.suffix in (".zip", ".gz"): + LOGGER.info(f"Unzipping {f}...") + if f.suffix == ".zip": + ZipFile(f).extractall(path=dir) # unzip + elif f.suffix == ".gz": + os.system(f"tar xfz {f} --directory {f.parent}") # unzip + if delete: + f.unlink() # remove zip + + dir = Path(dir) + dir.mkdir(parents=True, exist_ok=True) # make directory + if threads > 1: + pool = ThreadPool(threads) + pool.imap(lambda x: download_one(*x), zip(url, repeat(dir))) # multi-threaded + pool.close() + pool.join() + else: + for u in [url] if isinstance(url, (str, Path)) else url: + download_one(u, dir) + + +def make_divisible(x, divisor): + # Returns nearest x divisible by divisor + if isinstance(divisor, torch.Tensor): + divisor = int(divisor.max()) # to int + return math.ceil(x / divisor) * divisor + + +def clean_str(s): + # Cleans a string by replacing special characters with underscore _ + return re.sub(pattern="[|@#!¡·$€%&()=?¿^*;:,¨´><+]", repl="_", string=s) + + +def one_cycle(y1=0.0, y2=1.0, steps=100): + # lambda function for sinusoidal ramp from y1 to y2 https://arxiv.org/pdf/1812.01187.pdf + return lambda x: ((1 - math.cos(x * math.pi / steps)) / 2) * (y2 - y1) + y1 + + +def colorstr(*input): + # Colors a string https://en.wikipedia.org/wiki/ANSI_escape_code, i.e. colorstr('blue', 'hello world') + *args, string = input if len(input) > 1 else ("blue", "bold", input[0]) # color arguments, string + colors = { + "black": "\033[30m", # basic colors + "red": "\033[31m", + "green": "\033[32m", + "yellow": "\033[33m", + "blue": "\033[34m", + "magenta": "\033[35m", + "cyan": "\033[36m", + "white": "\033[37m", + "bright_black": "\033[90m", # bright colors + "bright_red": "\033[91m", + "bright_green": "\033[92m", + "bright_yellow": "\033[93m", + "bright_blue": "\033[94m", + "bright_magenta": "\033[95m", + "bright_cyan": "\033[96m", + "bright_white": "\033[97m", + "end": "\033[0m", # misc + "bold": "\033[1m", + "underline": "\033[4m", + } + return "".join(colors[x] for x in args) + f"{string}" + colors["end"] + + +def labels_to_class_weights(labels, nc=80): + # Get class weights (inverse frequency) from training labels + if labels[0] is None: # no labels loaded + return torch.Tensor() + + labels = np.concatenate(labels, 0) # labels.shape = (866643, 5) for COCO + classes = labels[:, 0].astype(np.int) # labels = [class xywh] + weights = np.bincount(classes, minlength=nc) # occurrences per class + + # Prepend gridpoint count (for uCE training) + # gpi = ((320 / 32 * np.array([1, 2, 4])) ** 2 * 3).sum() # gridpoints per image + # weights = np.hstack([gpi * len(labels) - weights.sum() * 9, weights * 9]) ** 0.5 # prepend gridpoints to start + + weights[weights == 0] = 1 # replace empty bins with 1 + weights = 1 / weights # number of targets per class + weights /= weights.sum() # normalize + return torch.from_numpy(weights) + + +def labels_to_image_weights(labels, nc=80, class_weights=np.ones(80)): + # Produces image weights based on class_weights and image contents + class_counts = np.array([np.bincount(x[:, 0].astype(np.int), minlength=nc) for x in labels]) + image_weights = (class_weights.reshape(1, nc) * class_counts).sum(1) + # index = random.choices(range(n), weights=image_weights, k=1) # weight image sample + return image_weights + + +def coco80_to_coco91_class(): # converts 80-index (val2014) to 91-index (paper) + # https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/ + # a = np.loadtxt('data/coco.names', dtype='str', delimiter='\n') + # b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='\n') + # x1 = [list(a[i] == b).index(True) + 1 for i in range(80)] # darknet to coco + # x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)] # coco to darknet + x = [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 27, + 28, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 46, + 47, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + 60, + 61, + 62, + 63, + 64, + 65, + 67, + 70, + 72, + 73, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 82, + 84, + 85, + 86, + 87, + 88, + 89, + 90, + ] + return x + + +def xyxy2xywh(x): + # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) + y[:, 0] = (x[:, 0] + x[:, 2]) / 2 # x center + y[:, 1] = (x[:, 1] + x[:, 3]) / 2 # y center + y[:, 2] = x[:, 2] - x[:, 0] # width + y[:, 3] = x[:, 3] - x[:, 1] # height + return y + + +def xywh2xyxy(x): + # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) + y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x + y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y + y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x + y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y + return y + + +def xywhn2xyxy(x, w=640, h=640, padw=0, padh=0): + # Convert nx4 boxes from [x, y, w, h] normalized to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) + y[:, 0] = w * (x[:, 0] - x[:, 2] / 2) + padw # top left x + y[:, 1] = h * (x[:, 1] - x[:, 3] / 2) + padh # top left y + y[:, 2] = w * (x[:, 0] + x[:, 2] / 2) + padw # bottom right x + y[:, 3] = h * (x[:, 1] + x[:, 3] / 2) + padh # bottom right y + return y + + +def xyxy2xywhn(x, w=640, h=640, clip=False, eps=0.0): + # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] normalized where xy1=top-left, xy2=bottom-right + if clip: + clip_coords(x, (h - eps, w - eps)) # warning: inplace clip + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) + y[:, 0] = ((x[:, 0] + x[:, 2]) / 2) / w # x center + y[:, 1] = ((x[:, 1] + x[:, 3]) / 2) / h # y center + y[:, 2] = (x[:, 2] - x[:, 0]) / w # width + y[:, 3] = (x[:, 3] - x[:, 1]) / h # height + return y + + +def xyn2xy(x, w=640, h=640, padw=0, padh=0): + # Convert normalized segments into pixel segments, shape (n,2) + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) + y[:, 0] = w * x[:, 0] + padw # top left x + y[:, 1] = h * x[:, 1] + padh # top left y + return y + + +def segment2box(segment, width=640, height=640): + # Convert 1 segment label to 1 box label, applying inside-image constraint, i.e. (xy1, xy2, ...) to (xyxy) + x, y = segment.T # segment xy + inside = (x >= 0) & (y >= 0) & (x <= width) & (y <= height) + x, y, = ( + x[inside], + y[inside], + ) + return np.array([x.min(), y.min(), x.max(), y.max()]) if any(x) else np.zeros((1, 4)) # xyxy + + +def segments2boxes(segments): + # Convert segment labels to box labels, i.e. (cls, xy1, xy2, ...) to (cls, xywh) + boxes = [] + for s in segments: + x, y = s.T # segment xy + boxes.append([x.min(), y.min(), x.max(), y.max()]) # cls, xyxy + return xyxy2xywh(np.array(boxes)) # cls, xywh + + +def resample_segments(segments, n=1000): + # Up-sample an (n,2) segment + for i, s in enumerate(segments): + x = np.linspace(0, len(s) - 1, n) + xp = np.arange(len(s)) + segments[i] = np.concatenate([np.interp(x, xp, s[:, i]) for i in range(2)]).reshape(2, -1).T # segment xy + return segments + + +def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None): + # Rescale coords (xyxy) from img1_shape to img0_shape + if ratio_pad is None: # calculate from img0_shape + gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new + pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding + else: + gain = ratio_pad[0][0] + pad = ratio_pad[1] + + coords[:, [0, 2]] -= pad[0] # x padding + coords[:, [1, 3]] -= pad[1] # y padding + coords[:, :4] /= gain + clip_coords(coords, img0_shape) + return coords + + +def clip_coords(boxes, shape): + # Clip bounding xyxy bounding boxes to image shape (height, width) + if isinstance(boxes, torch.Tensor): # faster individually + boxes[:, 0].clamp_(0, shape[1]) # x1 + boxes[:, 1].clamp_(0, shape[0]) # y1 + boxes[:, 2].clamp_(0, shape[1]) # x2 + boxes[:, 3].clamp_(0, shape[0]) # y2 + else: # np.array (faster grouped) + boxes[:, [0, 2]] = boxes[:, [0, 2]].clip(0, shape[1]) # x1, x2 + boxes[:, [1, 3]] = boxes[:, [1, 3]].clip(0, shape[0]) # y1, y2 + + +def non_max_suppression( + prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, multi_label=False, labels=(), max_det=300 +): + """Runs Non-Maximum Suppression (NMS) on inference results + + Returns: + list of detections, on (n,6) tensor per image [xyxy, conf, cls] + """ + + nc = prediction.shape[2] - 5 # number of classes + xc = prediction[..., 4] > conf_thres # candidates + + # Checks + assert 0 <= conf_thres <= 1, f"Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0" + assert 0 <= iou_thres <= 1, f"Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0" + + # Settings + min_wh, max_wh = 2, 7680 # (pixels) minimum and maximum box width and height + max_nms = 30000 # maximum number of boxes into torchvision.ops.nms() + time_limit = 10.0 # seconds to quit after + redundant = True # require redundant detections + multi_label &= nc > 1 # multiple labels per box (adds 0.5ms/img) + merge = False # use merge-NMS + + t = time.time() + output = [torch.zeros((0, 6), device=prediction.device)] * prediction.shape[0] + for xi, x in enumerate(prediction): # image index, image inference + # Apply constraints + x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height + x = x[xc[xi]] # confidence + + # Cat apriori labels if autolabelling + if labels and len(labels[xi]): + lb = labels[xi] + v = torch.zeros((len(lb), nc + 5), device=x.device) + v[:, :4] = lb[:, 1:5] # box + v[:, 4] = 1.0 # conf + v[range(len(lb)), lb[:, 0].long() + 5] = 1.0 # cls + x = torch.cat((x, v), 0) + + # If none remain process next image + if not x.shape[0]: + continue + + # Compute conf + x[:, 5:] *= x[:, 4:5] # conf = obj_conf * cls_conf + + # Box (center x, center y, width, height) to (x1, y1, x2, y2) + box = xywh2xyxy(x[:, :4]) + + # Detections matrix nx6 (xyxy, conf, cls) + if multi_label: + i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T + x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1) + else: # best class only + conf, j = x[:, 5:].max(1, keepdim=True) + x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres] + + # Filter by class + if classes is not None: + x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)] + + # Apply finite constraint + # if not torch.isfinite(x).all(): + # x = x[torch.isfinite(x).all(1)] + + # Check shape + n = x.shape[0] # number of boxes + if not n: # no boxes + continue + elif n > max_nms: # excess boxes + x = x[x[:, 4].argsort(descending=True)[:max_nms]] # sort by confidence + + # Batched NMS + c = x[:, 5:6] * (0 if agnostic else max_wh) # classes + boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores + i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS + if i.shape[0] > max_det: # limit detections + i = i[:max_det] + if merge and (1 < n < 3e3): # Merge NMS (boxes merged using weighted mean) + # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4) + iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix + weights = iou * scores[None] # box weights + x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes + if redundant: + i = i[iou.sum(1) > 1] # require redundancy + + output[xi] = x[i] + if (time.time() - t) > time_limit: + LOGGER.warning(f"WARNING: NMS time limit {time_limit}s exceeded") + break # time limit exceeded + + return output + + +def strip_optimizer(f="best.pt", s=""): # from utils.general import *; strip_optimizer() + # Strip optimizer from 'f' to finalize training, optionally save as 's' + x = torch.load(f, map_location=torch.device("cpu")) + if x.get("ema"): + x["model"] = x["ema"] # replace model with ema + for k in "optimizer", "best_fitness", "wandb_id", "ema", "updates": # keys + x[k] = None + x["epoch"] = -1 + x["model"].half() # to FP16 + for p in x["model"].parameters(): + p.requires_grad = False + torch.save(x, s or f) + mb = os.path.getsize(s or f) / 1e6 # filesize + LOGGER.info(f"Optimizer stripped from {f},{(' saved as %s,' % s) if s else ''} {mb:.1f}MB") + + +def print_mutation(results, hyp, save_dir, bucket, prefix=colorstr("evolve: ")): + evolve_csv = save_dir / "evolve.csv" + evolve_yaml = save_dir / "hyp_evolve.yaml" + keys = ( + "metrics/precision", + "metrics/recall", + "metrics/mAP_0.5", + "metrics/mAP_0.5:0.95", + "val/box_loss", + "val/obj_loss", + "val/cls_loss", + ) + tuple( + hyp.keys() + ) # [results + hyps] + keys = tuple(x.strip() for x in keys) + vals = results + tuple(hyp.values()) + n = len(keys) + + # Download (optional) + if bucket: + url = f"gs://{bucket}/evolve.csv" + if gsutil_getsize(url) > (evolve_csv.stat().st_size if evolve_csv.exists() else 0): + os.system(f"gsutil cp {url} {save_dir}") # download evolve.csv if larger than local + + # Log to evolve.csv + s = "" if evolve_csv.exists() else (("%20s," * n % keys).rstrip(",") + "\n") # add header + with open(evolve_csv, "a") as f: + f.write(s + ("%20.5g," * n % vals).rstrip(",") + "\n") + + # Save yaml + with open(evolve_yaml, "w") as f: + data = pd.read_csv(evolve_csv) + data = data.rename(columns=lambda x: x.strip()) # strip keys + i = np.argmax(fitness(data.values[:, :4])) # + generations = len(data) + f.write( + "# YOLOv5 Hyperparameter Evolution Results\n" + + f"# Best generation: {i}\n" + + f"# Last generation: {generations - 1}\n" + + "# " + + ", ".join(f"{x.strip():>20s}" for x in keys[:7]) + + "\n" + + "# " + + ", ".join(f"{x:>20.5g}" for x in data.values[i, :7]) + + "\n\n" + ) + yaml.safe_dump(data.loc[i][7:].to_dict(), f, sort_keys=False) + + # Print to screen + LOGGER.info( + prefix + + f"{generations} generations finished, current result:\n" + + prefix + + ", ".join(f"{x.strip():>20s}" for x in keys) + + "\n" + + prefix + + ", ".join(f"{x:20.5g}" for x in vals) + + "\n\n" + ) + + if bucket: + os.system(f"gsutil cp {evolve_csv} {evolve_yaml} gs://{bucket}") # upload + + +def apply_classifier(x, model, img, im0): + # Apply a second stage classifier to YOLO outputs + # Example model = torchvision.models.__dict__['efficientnet_b0'](pretrained=True).to(device).eval() + im0 = [im0] if isinstance(im0, np.ndarray) else im0 + for i, d in enumerate(x): # per image + if d is not None and len(d): + d = d.clone() + + # Reshape and pad cutouts + b = xyxy2xywh(d[:, :4]) # boxes + b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # rectangle to square + b[:, 2:] = b[:, 2:] * 1.3 + 30 # pad + d[:, :4] = xywh2xyxy(b).long() + + # Rescale boxes from img_size to im0 size + scale_coords(img.shape[2:], d[:, :4], im0[i].shape) + + # Classes + pred_cls1 = d[:, 5].long() + ims = [] + for j, a in enumerate(d): # per item + cutout = im0[i][int(a[1]) : int(a[3]), int(a[0]) : int(a[2])] + im = cv2.resize(cutout, (224, 224)) # BGR + # cv2.imwrite('example%i.jpg' % j, cutout) + + im = im[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416 + im = np.ascontiguousarray(im, dtype=np.float32) # uint8 to float32 + im /= 255 # 0 - 255 to 0.0 - 1.0 + ims.append(im) + + pred_cls2 = model(torch.Tensor(ims).to(d.device)).argmax(1) # classifier prediction + x[i] = x[i][pred_cls1 == pred_cls2] # retain matching class detections + + return x + + +def increment_path(path, exist_ok=False, sep="", mkdir=False): + # Increment file or directory path, i.e. runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc. + path = Path(path) # os-agnostic + if path.exists() and not exist_ok: + path, suffix = (path.with_suffix(""), path.suffix) if path.is_file() else (path, "") + dirs = glob.glob(f"{path}{sep}*") # similar paths + matches = [re.search(rf"%s{sep}(\d+)" % path.stem, d) for d in dirs] + i = [int(m.groups()[0]) for m in matches if m] # indices + n = max(i) + 1 if i else 2 # increment number + path = Path(f"{path}{sep}{n}{suffix}") # increment path + if mkdir: + path.mkdir(parents=True, exist_ok=True) # make directory + return path + + +# Variables +NCOLS = 0 if is_docker() else shutil.get_terminal_size().columns # terminal window size for tqdm diff --git a/core/vision/yolov5/utils/google_app_engine/Dockerfile b/core/vision/yolov5/utils/google_app_engine/Dockerfile new file mode 100644 index 00000000..0155618f --- /dev/null +++ b/core/vision/yolov5/utils/google_app_engine/Dockerfile @@ -0,0 +1,25 @@ +FROM gcr.io/google-appengine/python + +# Create a virtualenv for dependencies. This isolates these packages from +# system-level packages. +# Use -p python3 or -p python3.7 to select python version. Default is version 2. +RUN virtualenv /env -p python3 + +# Setting these environment variables are the same as running +# source /env/bin/activate. +ENV VIRTUAL_ENV /env +ENV PATH /env/bin:$PATH + +RUN apt-get update && apt-get install -y python-opencv + +# Copy the application's requirements.txt and run pip to install all +# dependencies into the virtualenv. +ADD requirements.txt /app/requirements.txt +RUN pip install -r /app/requirements.txt + +# Add the application source code. +ADD . /app + +# Run a WSGI server to serve the application. gunicorn must be declared as +# a dependency in requirements.txt. +CMD gunicorn -b :$PORT main:app diff --git a/core/vision/yolov5/utils/google_app_engine/additional_requirements.txt b/core/vision/yolov5/utils/google_app_engine/additional_requirements.txt new file mode 100644 index 00000000..42d7ffc0 --- /dev/null +++ b/core/vision/yolov5/utils/google_app_engine/additional_requirements.txt @@ -0,0 +1,4 @@ +# add these requirements in your app on top of the existing ones +pip==21.1 +Flask==1.0.2 +gunicorn==19.9.0 diff --git a/core/vision/yolov5/utils/google_app_engine/app.yaml b/core/vision/yolov5/utils/google_app_engine/app.yaml new file mode 100644 index 00000000..5056b7c1 --- /dev/null +++ b/core/vision/yolov5/utils/google_app_engine/app.yaml @@ -0,0 +1,14 @@ +runtime: custom +env: flex + +service: yolov5app + +liveness_check: + initial_delay_sec: 600 + +manual_scaling: + instances: 1 +resources: + cpu: 1 + memory_gb: 4 + disk_size_gb: 20 diff --git a/core/vision/yolov5/utils/loggers/__init__.py b/core/vision/yolov5/utils/loggers/__init__.py new file mode 100644 index 00000000..866bdc4b --- /dev/null +++ b/core/vision/yolov5/utils/loggers/__init__.py @@ -0,0 +1,168 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Logging utils +""" + +import os +import warnings +from threading import Thread + +import pkg_resources as pkg +import torch +from torch.utils.tensorboard import SummaryWriter + +from utils.general import colorstr, emojis +from utils.loggers.wandb.wandb_utils import WandbLogger +from utils.plots import plot_images, plot_results +from utils.torch_utils import de_parallel + +LOGGERS = ('csv', 'tb', 'wandb') # text-file, TensorBoard, Weights & Biases +RANK = int(os.getenv('RANK', -1)) + +try: + import wandb + + assert hasattr(wandb, '__version__') # verify package import not local dir + if pkg.parse_version(wandb.__version__) >= pkg.parse_version('0.12.2') and RANK in [0, -1]: + try: + wandb_login_success = wandb.login(timeout=30) + except wandb.errors.UsageError: # known non-TTY terminal issue + wandb_login_success = False + if not wandb_login_success: + wandb = None +except (ImportError, AssertionError): + wandb = None + + +class Loggers(): + # YOLOv5 Loggers class + def __init__(self, save_dir=None, weights=None, opt=None, hyp=None, logger=None, include=LOGGERS): + self.save_dir = save_dir + self.weights = weights + self.opt = opt + self.hyp = hyp + self.logger = logger # for printing results to console + self.include = include + self.keys = ['train/box_loss', 'train/obj_loss', 'train/cls_loss', # train loss + 'metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/mAP_0.5:0.95', # metrics + 'val/box_loss', 'val/obj_loss', 'val/cls_loss', # val loss + 'x/lr0', 'x/lr1', 'x/lr2'] # params + self.best_keys = ['best/epoch', 'best/precision', 'best/recall', 'best/mAP_0.5', 'best/mAP_0.5:0.95'] + for k in LOGGERS: + setattr(self, k, None) # init empty logger dictionary + self.csv = True # always log to csv + + # Message + if not wandb: + prefix = colorstr('Weights & Biases: ') + s = f"{prefix}run 'pip install wandb' to automatically track and visualize YOLOv5 🚀 runs (RECOMMENDED)" + self.logger.info(emojis(s)) + + # TensorBoard + s = self.save_dir + if 'tb' in self.include and not self.opt.evolve: + prefix = colorstr('TensorBoard: ') + self.logger.info(f"{prefix}Start with 'tensorboard --logdir {s.parent}', view at http://localhost:6006/") + self.tb = SummaryWriter(str(s)) + + # W&B + if wandb and 'wandb' in self.include: + wandb_artifact_resume = isinstance(self.opt.resume, str) and self.opt.resume.startswith('wandb-artifact://') + run_id = torch.load(self.weights).get('wandb_id') if self.opt.resume and not wandb_artifact_resume else None + self.opt.hyp = self.hyp # add hyperparameters + self.wandb = WandbLogger(self.opt, run_id) + else: + self.wandb = None + + def on_pretrain_routine_end(self): + # Callback runs on pre-train routine end + paths = self.save_dir.glob('*labels*.jpg') # training labels + if self.wandb: + self.wandb.log({"Labels": [wandb.Image(str(x), caption=x.name) for x in paths]}) + + def on_train_batch_end(self, ni, model, imgs, targets, paths, plots, sync_bn): + # Callback runs on train batch end + if plots: + if ni == 0: + if not sync_bn: # tb.add_graph() --sync known issue https://github.com/ultralytics/yolov5/issues/3754 + with warnings.catch_warnings(): + warnings.simplefilter('ignore') # suppress jit trace warning + self.tb.add_graph(torch.jit.trace(de_parallel(model), imgs[0:1], strict=False), []) + if ni < 3: + f = self.save_dir / f'train_batch{ni}.jpg' # filename + Thread(target=plot_images, args=(imgs, targets, paths, f), daemon=True).start() + if self.wandb and ni == 10: + files = sorted(self.save_dir.glob('train*.jpg')) + self.wandb.log({'Mosaics': [wandb.Image(str(f), caption=f.name) for f in files if f.exists()]}) + + def on_train_epoch_end(self, epoch): + # Callback runs on train epoch end + if self.wandb: + self.wandb.current_epoch = epoch + 1 + + def on_val_image_end(self, pred, predn, path, names, im): + # Callback runs on val image end + if self.wandb: + self.wandb.val_one_image(pred, predn, path, names, im) + + def on_val_end(self): + # Callback runs on val end + if self.wandb: + files = sorted(self.save_dir.glob('val*.jpg')) + self.wandb.log({"Validation": [wandb.Image(str(f), caption=f.name) for f in files]}) + + def on_fit_epoch_end(self, vals, epoch, best_fitness, fi): + # Callback runs at the end of each fit (train+val) epoch + x = {k: v for k, v in zip(self.keys, vals)} # dict + if self.csv: + file = self.save_dir / 'results.csv' + n = len(x) + 1 # number of cols + s = '' if file.exists() else (('%20s,' * n % tuple(['epoch'] + self.keys)).rstrip(',') + '\n') # add header + with open(file, 'a') as f: + f.write(s + ('%20.5g,' * n % tuple([epoch] + vals)).rstrip(',') + '\n') + + if self.tb: + for k, v in x.items(): + self.tb.add_scalar(k, v, epoch) + + if self.wandb: + if best_fitness == fi: + best_results = [epoch] + vals[3:7] + for i, name in enumerate(self.best_keys): + self.wandb.wandb_run.summary[name] = best_results[i] # log best results in the summary + self.wandb.log(x) + self.wandb.end_epoch(best_result=best_fitness == fi) + + def on_model_save(self, last, epoch, final_epoch, best_fitness, fi): + # Callback runs on model save event + if self.wandb: + if ((epoch + 1) % self.opt.save_period == 0 and not final_epoch) and self.opt.save_period != -1: + self.wandb.log_model(last.parent, self.opt, epoch, fi, best_model=best_fitness == fi) + + def on_train_end(self, last, best, plots, epoch, results): + # Callback runs on training end + if plots: + plot_results(file=self.save_dir / 'results.csv') # save results.png + files = ['results.png', 'confusion_matrix.png', *(f'{x}_curve.png' for x in ('F1', 'PR', 'P', 'R'))] + files = [(self.save_dir / f) for f in files if (self.save_dir / f).exists()] # filter + + if self.tb: + import cv2 + for f in files: + self.tb.add_image(f.stem, cv2.imread(str(f))[..., ::-1], epoch, dataformats='HWC') + + if self.wandb: + self.wandb.log({k: v for k, v in zip(self.keys[3:10], results)}) # log best.pt val results + self.wandb.log({"Results": [wandb.Image(str(f), caption=f.name) for f in files]}) + # Calling wandb.log. TODO: Refactor this into WandbLogger.log_model + if not self.opt.evolve: + wandb.log_artifact(str(best if best.exists() else last), type='model', + name='run_' + self.wandb.wandb_run.id + '_model', + aliases=['latest', 'best', 'stripped']) + self.wandb.finish_run() + + def on_params_update(self, params): + # Update hyperparams or configs of the experiment + # params: A dict containing {param: value} pairs + if self.wandb: + self.wandb.wandb_run.config.update(params, allow_val_change=True) diff --git a/core/vision/yolov5/utils/loggers/wandb/README.md b/core/vision/yolov5/utils/loggers/wandb/README.md new file mode 100644 index 00000000..63d99985 --- /dev/null +++ b/core/vision/yolov5/utils/loggers/wandb/README.md @@ -0,0 +1,152 @@ +📚 This guide explains how to use **Weights & Biases** (W&B) with YOLOv5 🚀. UPDATED 29 September 2021. +* [About Weights & Biases](#about-weights-&-biases) +* [First-Time Setup](#first-time-setup) +* [Viewing runs](#viewing-runs) +* [Disabling wandb](#disabling-wandb) +* [Advanced Usage: Dataset Versioning and Evaluation](#advanced-usage) +* [Reports: Share your work with the world!](#reports) + +## About Weights & Biases +Think of [W&B](https://wandb.ai/site?utm_campaign=repo_yolo_wandbtutorial) like GitHub for machine learning models. With a few lines of code, save everything you need to debug, compare and reproduce your models — architecture, hyperparameters, git commits, model weights, GPU usage, and even datasets and predictions. + +Used by top researchers including teams at OpenAI, Lyft, Github, and MILA, W&B is part of the new standard of best practices for machine learning. How W&B can help you optimize your machine learning workflows: + + * [Debug](https://wandb.ai/wandb/getting-started/reports/Visualize-Debug-Machine-Learning-Models--VmlldzoyNzY5MDk#Free-2) model performance in real time + * [GPU usage](https://wandb.ai/wandb/getting-started/reports/Visualize-Debug-Machine-Learning-Models--VmlldzoyNzY5MDk#System-4) visualized automatically + * [Custom charts](https://wandb.ai/wandb/customizable-charts/reports/Powerful-Custom-Charts-To-Debug-Model-Peformance--VmlldzoyNzY4ODI) for powerful, extensible visualization + * [Share insights](https://wandb.ai/wandb/getting-started/reports/Visualize-Debug-Machine-Learning-Models--VmlldzoyNzY5MDk#Share-8) interactively with collaborators + * [Optimize hyperparameters](https://docs.wandb.com/sweeps) efficiently + * [Track](https://docs.wandb.com/artifacts) datasets, pipelines, and production models + +## First-Time Setup +
+ Toggle Details +When you first train, W&B will prompt you to create a new account and will generate an **API key** for you. If you are an existing user you can retrieve your key from https://wandb.ai/authorize. This key is used to tell W&B where to log your data. You only need to supply your key once, and then it is remembered on the same device. + +W&B will create a cloud **project** (default is 'YOLOv5') for your training runs, and each new training run will be provided a unique run **name** within that project as project/name. You can also manually set your project and run name as: + + ```shell + $ python train.py --project ... --name ... + ``` + +YOLOv5 notebook example: Open In Colab Open In Kaggle +Screen Shot 2021-09-29 at 10 23 13 PM + + +
+ +## Viewing Runs +
+ Toggle Details +Run information streams from your environment to the W&B cloud console as you train. This allows you to monitor and even cancel runs in realtime . All important information is logged: + + * Training & Validation losses + * Metrics: Precision, Recall, mAP@0.5, mAP@0.5:0.95 + * Learning Rate over time + * A bounding box debugging panel, showing the training progress over time + * GPU: Type, **GPU Utilization**, power, temperature, **CUDA memory usage** + * System: Disk I/0, CPU utilization, RAM memory usage + * Your trained model as W&B Artifact + * Environment: OS and Python types, Git repository and state, **training command** + +

Weights & Biases dashboard

+
+ + ## Disabling wandb +* training after running `wandb disabled` inside that directory creates no wandb run +![Screenshot (84)](https://user-images.githubusercontent.com/15766192/143441777-c780bdd7-7cb4-4404-9559-b4316030a985.png) + +* To enable wandb again, run `wandb online` +![Screenshot (85)](https://user-images.githubusercontent.com/15766192/143441866-7191b2cb-22f0-4e0f-ae64-2dc47dc13078.png) + +## Advanced Usage +You can leverage W&B artifacts and Tables integration to easily visualize and manage your datasets, models and training evaluations. Here are some quick examples to get you started. +
+

1: Train and Log Evaluation simultaneousy

+ This is an extension of the previous section, but it'll also training after uploading the dataset. This also evaluation Table + Evaluation table compares your predictions and ground truths across the validation set for each epoch. It uses the references to the already uploaded datasets, + so no images will be uploaded from your system more than once. +
+ Usage + Code $ python train.py --upload_data val + +![Screenshot from 2021-11-21 17-40-06](https://user-images.githubusercontent.com/15766192/142761183-c1696d8c-3f38-45ab-991a-bb0dfd98ae7d.png) +
+ +

2. Visualize and Version Datasets

+ Log, visualize, dynamically query, and understand your data with W&B Tables. You can use the following command to log your dataset as a W&B Table. This will generate a {dataset}_wandb.yaml file which can be used to train from dataset artifact. +
+ Usage + Code $ python utils/logger/wandb/log_dataset.py --project ... --name ... --data .. + + ![Screenshot (64)](https://user-images.githubusercontent.com/15766192/128486078-d8433890-98a3-4d12-8986-b6c0e3fc64b9.png) +
+ +

3: Train using dataset artifact

+ When you upload a dataset as described in the first section, you get a new config file with an added `_wandb` to its name. This file contains the information that + can be used to train a model directly from the dataset artifact. This also logs evaluation +
+ Usage + Code $ python train.py --data {data}_wandb.yaml + +![Screenshot (72)](https://user-images.githubusercontent.com/15766192/128979739-4cf63aeb-a76f-483f-8861-1c0100b938a5.png) +
+ +

4: Save model checkpoints as artifacts

+ To enable saving and versioning checkpoints of your experiment, pass `--save_period n` with the base cammand, where `n` represents checkpoint interval. + You can also log both the dataset and model checkpoints simultaneously. If not passed, only the final model will be logged + +
+ Usage + Code $ python train.py --save_period 1 + +![Screenshot (68)](https://user-images.githubusercontent.com/15766192/128726138-ec6c1f60-639d-437d-b4ee-3acd9de47ef3.png) +
+ +
+ +

5: Resume runs from checkpoint artifacts.

+Any run can be resumed using artifacts if the --resume argument starts with wandb-artifact:// prefix followed by the run path, i.e, wandb-artifact://username/project/runid . This doesn't require the model checkpoint to be present on the local system. + +
+ Usage + Code $ python train.py --resume wandb-artifact://{run_path} + +![Screenshot (70)](https://user-images.githubusercontent.com/15766192/128728988-4e84b355-6c87-41ae-a591-14aecf45343e.png) +
+ +

6: Resume runs from dataset artifact & checkpoint artifacts.

+ Local dataset or model checkpoints are not required. This can be used to resume runs directly on a different device + The syntax is same as the previous section, but you'll need to lof both the dataset and model checkpoints as artifacts, i.e, set bot --upload_dataset or + train from _wandb.yaml file and set --save_period + +
+ Usage + Code $ python train.py --resume wandb-artifact://{run_path} + +![Screenshot (70)](https://user-images.githubusercontent.com/15766192/128728988-4e84b355-6c87-41ae-a591-14aecf45343e.png) +
+ + + +

Reports

+W&B Reports can be created from your saved runs for sharing online. Once a report is created you will receive a link you can use to publically share your results. Here is an example report created from the COCO128 tutorial trainings of all four YOLOv5 models ([link](https://wandb.ai/glenn-jocher/yolov5_tutorial/reports/YOLOv5-COCO128-Tutorial-Results--VmlldzozMDI5OTY)). + +Weights & Biases Reports + + +## Environments + +YOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including [CUDA](https://developer.nvidia.com/cuda)/[CUDNN](https://developer.nvidia.com/cudnn), [Python](https://www.python.org/) and [PyTorch](https://pytorch.org/) preinstalled): + +- **Google Colab and Kaggle** notebooks with free GPU: Open In Colab Open In Kaggle +- **Google Cloud** Deep Learning VM. See [GCP Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/GCP-Quickstart) +- **Amazon** Deep Learning AMI. See [AWS Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/AWS-Quickstart) +- **Docker Image**. See [Docker Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/Docker-Quickstart) Docker Pulls + + +## Status + +![CI CPU testing](https://github.com/ultralytics/yolov5/workflows/CI%20CPU%20testing/badge.svg) + +If this badge is green, all [YOLOv5 GitHub Actions](https://github.com/ultralytics/yolov5/actions) Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 training ([train.py](https://github.com/ultralytics/yolov5/blob/master/train.py)), validation ([val.py](https://github.com/ultralytics/yolov5/blob/master/val.py)), inference ([detect.py](https://github.com/ultralytics/yolov5/blob/master/detect.py)) and export ([export.py](https://github.com/ultralytics/yolov5/blob/master/export.py)) on MacOS, Windows, and Ubuntu every 24 hours and on every commit. diff --git a/core/vision/yolov5/utils/loggers/wandb/__init__.py b/core/vision/yolov5/utils/loggers/wandb/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/core/vision/yolov5/utils/loggers/wandb/log_dataset.py b/core/vision/yolov5/utils/loggers/wandb/log_dataset.py new file mode 100644 index 00000000..06e81fb6 --- /dev/null +++ b/core/vision/yolov5/utils/loggers/wandb/log_dataset.py @@ -0,0 +1,27 @@ +import argparse + +from wandb_utils import WandbLogger + +from utils.general import LOGGER + +WANDB_ARTIFACT_PREFIX = 'wandb-artifact://' + + +def create_dataset_artifact(opt): + logger = WandbLogger(opt, None, job_type='Dataset Creation') # TODO: return value unused + if not logger.wandb: + LOGGER.info("install wandb using `pip install wandb` to log the dataset") + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--data', type=str, default='data/coco128.yaml', help='data.yaml path') + parser.add_argument('--single-cls', action='store_true', help='train as single-class dataset') + parser.add_argument('--project', type=str, default='YOLOv5', help='name of W&B Project') + parser.add_argument('--entity', default=None, help='W&B entity') + parser.add_argument('--name', type=str, default='log dataset', help='name of W&B run') + + opt = parser.parse_args() + opt.resume = False # Explicitly disallow resume check for dataset upload job + + create_dataset_artifact(opt) diff --git a/core/vision/yolov5/utils/loggers/wandb/sweep.py b/core/vision/yolov5/utils/loggers/wandb/sweep.py new file mode 100644 index 00000000..206059bc --- /dev/null +++ b/core/vision/yolov5/utils/loggers/wandb/sweep.py @@ -0,0 +1,41 @@ +import sys +from pathlib import Path + +import wandb + +FILE = Path(__file__).resolve() +ROOT = FILE.parents[3] # YOLOv5 root directory +if str(ROOT) not in sys.path: + sys.path.append(str(ROOT)) # add ROOT to PATH + +from train import parse_opt, train +from utils.callbacks import Callbacks +from utils.general import increment_path +from utils.torch_utils import select_device + + +def sweep(): + wandb.init() + # Get hyp dict from sweep agent + hyp_dict = vars(wandb.config).get("_items") + + # Workaround: get necessary opt args + opt = parse_opt(known=True) + opt.batch_size = hyp_dict.get("batch_size") + opt.save_dir = str(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok or opt.evolve)) + opt.epochs = hyp_dict.get("epochs") + opt.nosave = True + opt.data = hyp_dict.get("data") + opt.weights = str(opt.weights) + opt.cfg = str(opt.cfg) + opt.data = str(opt.data) + opt.hyp = str(opt.hyp) + opt.project = str(opt.project) + device = select_device(opt.device, batch_size=opt.batch_size) + + # train + train(hyp_dict, opt, device, callbacks=Callbacks()) + + +if __name__ == "__main__": + sweep() diff --git a/core/vision/yolov5/utils/loggers/wandb/sweep.yaml b/core/vision/yolov5/utils/loggers/wandb/sweep.yaml new file mode 100644 index 00000000..688b1ea0 --- /dev/null +++ b/core/vision/yolov5/utils/loggers/wandb/sweep.yaml @@ -0,0 +1,143 @@ +# Hyperparameters for training +# To set range- +# Provide min and max values as: +# parameter: +# +# min: scalar +# max: scalar +# OR +# +# Set a specific list of search space- +# parameter: +# values: [scalar1, scalar2, scalar3...] +# +# You can use grid, bayesian and hyperopt search strategy +# For more info on configuring sweeps visit - https://docs.wandb.ai/guides/sweeps/configuration + +program: utils/loggers/wandb/sweep.py +method: random +metric: + name: metrics/mAP_0.5 + goal: maximize + +parameters: + # hyperparameters: set either min, max range or values list + data: + value: "data/coco128.yaml" + batch_size: + values: [64] + epochs: + values: [10] + + lr0: + distribution: uniform + min: 1e-5 + max: 1e-1 + lrf: + distribution: uniform + min: 0.01 + max: 1.0 + momentum: + distribution: uniform + min: 0.6 + max: 0.98 + weight_decay: + distribution: uniform + min: 0.0 + max: 0.001 + warmup_epochs: + distribution: uniform + min: 0.0 + max: 5.0 + warmup_momentum: + distribution: uniform + min: 0.0 + max: 0.95 + warmup_bias_lr: + distribution: uniform + min: 0.0 + max: 0.2 + box: + distribution: uniform + min: 0.02 + max: 0.2 + cls: + distribution: uniform + min: 0.2 + max: 4.0 + cls_pw: + distribution: uniform + min: 0.5 + max: 2.0 + obj: + distribution: uniform + min: 0.2 + max: 4.0 + obj_pw: + distribution: uniform + min: 0.5 + max: 2.0 + iou_t: + distribution: uniform + min: 0.1 + max: 0.7 + anchor_t: + distribution: uniform + min: 2.0 + max: 8.0 + fl_gamma: + distribution: uniform + min: 0.0 + max: 4.0 + hsv_h: + distribution: uniform + min: 0.0 + max: 0.1 + hsv_s: + distribution: uniform + min: 0.0 + max: 0.9 + hsv_v: + distribution: uniform + min: 0.0 + max: 0.9 + degrees: + distribution: uniform + min: 0.0 + max: 45.0 + translate: + distribution: uniform + min: 0.0 + max: 0.9 + scale: + distribution: uniform + min: 0.0 + max: 0.9 + shear: + distribution: uniform + min: 0.0 + max: 10.0 + perspective: + distribution: uniform + min: 0.0 + max: 0.001 + flipud: + distribution: uniform + min: 0.0 + max: 1.0 + fliplr: + distribution: uniform + min: 0.0 + max: 1.0 + mosaic: + distribution: uniform + min: 0.0 + max: 1.0 + mixup: + distribution: uniform + min: 0.0 + max: 1.0 + copy_paste: + distribution: uniform + min: 0.0 + max: 1.0 diff --git a/core/vision/yolov5/utils/loggers/wandb/wandb_utils.py b/core/vision/yolov5/utils/loggers/wandb/wandb_utils.py new file mode 100644 index 00000000..786e58a1 --- /dev/null +++ b/core/vision/yolov5/utils/loggers/wandb/wandb_utils.py @@ -0,0 +1,562 @@ +"""Utilities and tools for tracking runs with Weights & Biases.""" + +import logging +import os +import sys +from contextlib import contextmanager +from pathlib import Path +from typing import Dict + +import yaml +from tqdm import tqdm + +FILE = Path(__file__).resolve() +ROOT = FILE.parents[3] # YOLOv5 root directory +if str(ROOT) not in sys.path: + sys.path.append(str(ROOT)) # add ROOT to PATH + +from utils.datasets import LoadImagesAndLabels, img2label_paths +from utils.general import LOGGER, check_dataset, check_file + +try: + import wandb + + assert hasattr(wandb, '__version__') # verify package import not local dir +except (ImportError, AssertionError): + wandb = None + +RANK = int(os.getenv('RANK', -1)) +WANDB_ARTIFACT_PREFIX = 'wandb-artifact://' + + +def remove_prefix(from_string, prefix=WANDB_ARTIFACT_PREFIX): + return from_string[len(prefix):] + + +def check_wandb_config_file(data_config_file): + wandb_config = '_wandb.'.join(data_config_file.rsplit('.', 1)) # updated data.yaml path + if Path(wandb_config).is_file(): + return wandb_config + return data_config_file + + +def check_wandb_dataset(data_file): + is_trainset_wandb_artifact = False + is_valset_wandb_artifact = False + if check_file(data_file) and data_file.endswith('.yaml'): + with open(data_file, errors='ignore') as f: + data_dict = yaml.safe_load(f) + is_trainset_wandb_artifact = (isinstance(data_dict['train'], str) and + data_dict['train'].startswith(WANDB_ARTIFACT_PREFIX)) + is_valset_wandb_artifact = (isinstance(data_dict['val'], str) and + data_dict['val'].startswith(WANDB_ARTIFACT_PREFIX)) + if is_trainset_wandb_artifact or is_valset_wandb_artifact: + return data_dict + else: + return check_dataset(data_file) + + +def get_run_info(run_path): + run_path = Path(remove_prefix(run_path, WANDB_ARTIFACT_PREFIX)) + run_id = run_path.stem + project = run_path.parent.stem + entity = run_path.parent.parent.stem + model_artifact_name = 'run_' + run_id + '_model' + return entity, project, run_id, model_artifact_name + + +def check_wandb_resume(opt): + process_wandb_config_ddp_mode(opt) if RANK not in [-1, 0] else None + if isinstance(opt.resume, str): + if opt.resume.startswith(WANDB_ARTIFACT_PREFIX): + if RANK not in [-1, 0]: # For resuming DDP runs + entity, project, run_id, model_artifact_name = get_run_info(opt.resume) + api = wandb.Api() + artifact = api.artifact(entity + '/' + project + '/' + model_artifact_name + ':latest') + modeldir = artifact.download() + opt.weights = str(Path(modeldir) / "last.pt") + return True + return None + + +def process_wandb_config_ddp_mode(opt): + with open(check_file(opt.data), errors='ignore') as f: + data_dict = yaml.safe_load(f) # data dict + train_dir, val_dir = None, None + if isinstance(data_dict['train'], str) and data_dict['train'].startswith(WANDB_ARTIFACT_PREFIX): + api = wandb.Api() + train_artifact = api.artifact(remove_prefix(data_dict['train']) + ':' + opt.artifact_alias) + train_dir = train_artifact.download() + train_path = Path(train_dir) / 'data/images/' + data_dict['train'] = str(train_path) + + if isinstance(data_dict['val'], str) and data_dict['val'].startswith(WANDB_ARTIFACT_PREFIX): + api = wandb.Api() + val_artifact = api.artifact(remove_prefix(data_dict['val']) + ':' + opt.artifact_alias) + val_dir = val_artifact.download() + val_path = Path(val_dir) / 'data/images/' + data_dict['val'] = str(val_path) + if train_dir or val_dir: + ddp_data_path = str(Path(val_dir) / 'wandb_local_data.yaml') + with open(ddp_data_path, 'w') as f: + yaml.safe_dump(data_dict, f) + opt.data = ddp_data_path + + +class WandbLogger(): + """Log training runs, datasets, models, and predictions to Weights & Biases. + + This logger sends information to W&B at wandb.ai. By default, this information + includes hyperparameters, system configuration and metrics, model metrics, + and basic data metrics and analyses. + + By providing additional command line arguments to train.py, datasets, + models and predictions can also be logged. + + For more on how this logger is used, see the Weights & Biases documentation: + https://docs.wandb.com/guides/integrations/yolov5 + """ + + def __init__(self, opt, run_id=None, job_type='Training'): + """ + - Initialize WandbLogger instance + - Upload dataset if opt.upload_dataset is True + - Setup trainig processes if job_type is 'Training' + + arguments: + opt (namespace) -- Commandline arguments for this run + run_id (str) -- Run ID of W&B run to be resumed + job_type (str) -- To set the job_type for this run + + """ + # Pre-training routine -- + self.job_type = job_type + self.wandb, self.wandb_run = wandb, None if not wandb else wandb.run + self.val_artifact, self.train_artifact = None, None + self.train_artifact_path, self.val_artifact_path = None, None + self.result_artifact = None + self.val_table, self.result_table = None, None + self.bbox_media_panel_images = [] + self.val_table_path_map = None + self.max_imgs_to_log = 16 + self.wandb_artifact_data_dict = None + self.data_dict = None + # It's more elegant to stick to 1 wandb.init call, + # but useful config data is overwritten in the WandbLogger's wandb.init call + if isinstance(opt.resume, str): # checks resume from artifact + if opt.resume.startswith(WANDB_ARTIFACT_PREFIX): + entity, project, run_id, model_artifact_name = get_run_info(opt.resume) + model_artifact_name = WANDB_ARTIFACT_PREFIX + model_artifact_name + assert wandb, 'install wandb to resume wandb runs' + # Resume wandb-artifact:// runs here| workaround for not overwriting wandb.config + self.wandb_run = wandb.init(id=run_id, + project=project, + entity=entity, + resume='allow', + allow_val_change=True) + opt.resume = model_artifact_name + elif self.wandb: + self.wandb_run = wandb.init(config=opt, + resume="allow", + project='YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem, + entity=opt.entity, + name=opt.name if opt.name != 'exp' else None, + job_type=job_type, + id=run_id, + allow_val_change=True) if not wandb.run else wandb.run + if self.wandb_run: + if self.job_type == 'Training': + if opt.upload_dataset: + if not opt.resume: + self.wandb_artifact_data_dict = self.check_and_upload_dataset(opt) + + if opt.resume: + # resume from artifact + if isinstance(opt.resume, str) and opt.resume.startswith(WANDB_ARTIFACT_PREFIX): + self.data_dict = dict(self.wandb_run.config.data_dict) + else: # local resume + self.data_dict = check_wandb_dataset(opt.data) + else: + self.data_dict = check_wandb_dataset(opt.data) + self.wandb_artifact_data_dict = self.wandb_artifact_data_dict or self.data_dict + + # write data_dict to config. useful for resuming from artifacts. Do this only when not resuming. + self.wandb_run.config.update({'data_dict': self.wandb_artifact_data_dict}, + allow_val_change=True) + self.setup_training(opt) + + if self.job_type == 'Dataset Creation': + self.wandb_run.config.update({"upload_dataset": True}) + self.data_dict = self.check_and_upload_dataset(opt) + + def check_and_upload_dataset(self, opt): + """ + Check if the dataset format is compatible and upload it as W&B artifact + + arguments: + opt (namespace)-- Commandline arguments for current run + + returns: + Updated dataset info dictionary where local dataset paths are replaced by WAND_ARFACT_PREFIX links. + """ + assert wandb, 'Install wandb to upload dataset' + config_path = self.log_dataset_artifact(opt.data, + opt.single_cls, + 'YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem) + with open(config_path, errors='ignore') as f: + wandb_data_dict = yaml.safe_load(f) + return wandb_data_dict + + def setup_training(self, opt): + """ + Setup the necessary processes for training YOLO models: + - Attempt to download model checkpoint and dataset artifacts if opt.resume stats with WANDB_ARTIFACT_PREFIX + - Update data_dict, to contain info of previous run if resumed and the paths of dataset artifact if downloaded + - Setup log_dict, initialize bbox_interval + + arguments: + opt (namespace) -- commandline arguments for this run + + """ + self.log_dict, self.current_epoch = {}, 0 + self.bbox_interval = opt.bbox_interval + if isinstance(opt.resume, str): + modeldir, _ = self.download_model_artifact(opt) + if modeldir: + self.weights = Path(modeldir) / "last.pt" + config = self.wandb_run.config + opt.weights, opt.save_period, opt.batch_size, opt.bbox_interval, opt.epochs, opt.hyp, opt.imgsz = str( + self.weights), config.save_period, config.batch_size, config.bbox_interval, config.epochs,\ + config.hyp, config.imgsz + data_dict = self.data_dict + if self.val_artifact is None: # If --upload_dataset is set, use the existing artifact, don't download + self.train_artifact_path, self.train_artifact = self.download_dataset_artifact(data_dict.get('train'), + opt.artifact_alias) + self.val_artifact_path, self.val_artifact = self.download_dataset_artifact(data_dict.get('val'), + opt.artifact_alias) + + if self.train_artifact_path is not None: + train_path = Path(self.train_artifact_path) / 'data/images/' + data_dict['train'] = str(train_path) + if self.val_artifact_path is not None: + val_path = Path(self.val_artifact_path) / 'data/images/' + data_dict['val'] = str(val_path) + + if self.val_artifact is not None: + self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation") + columns = ["epoch", "id", "ground truth", "prediction"] + columns.extend(self.data_dict['names']) + self.result_table = wandb.Table(columns) + self.val_table = self.val_artifact.get("val") + if self.val_table_path_map is None: + self.map_val_table_path() + if opt.bbox_interval == -1: + self.bbox_interval = opt.bbox_interval = (opt.epochs // 10) if opt.epochs > 10 else 1 + if opt.evolve: + self.bbox_interval = opt.bbox_interval = opt.epochs + 1 + train_from_artifact = self.train_artifact_path is not None and self.val_artifact_path is not None + # Update the the data_dict to point to local artifacts dir + if train_from_artifact: + self.data_dict = data_dict + + def download_dataset_artifact(self, path, alias): + """ + download the model checkpoint artifact if the path starts with WANDB_ARTIFACT_PREFIX + + arguments: + path -- path of the dataset to be used for training + alias (str)-- alias of the artifact to be download/used for training + + returns: + (str, wandb.Artifact) -- path of the downladed dataset and it's corresponding artifact object if dataset + is found otherwise returns (None, None) + """ + if isinstance(path, str) and path.startswith(WANDB_ARTIFACT_PREFIX): + artifact_path = Path(remove_prefix(path, WANDB_ARTIFACT_PREFIX) + ":" + alias) + dataset_artifact = wandb.use_artifact(artifact_path.as_posix().replace("\\", "/")) + assert dataset_artifact is not None, "'Error: W&B dataset artifact doesn\'t exist'" + datadir = dataset_artifact.download() + return datadir, dataset_artifact + return None, None + + def download_model_artifact(self, opt): + """ + download the model checkpoint artifact if the resume path starts with WANDB_ARTIFACT_PREFIX + + arguments: + opt (namespace) -- Commandline arguments for this run + """ + if opt.resume.startswith(WANDB_ARTIFACT_PREFIX): + model_artifact = wandb.use_artifact(remove_prefix(opt.resume, WANDB_ARTIFACT_PREFIX) + ":latest") + assert model_artifact is not None, 'Error: W&B model artifact doesn\'t exist' + modeldir = model_artifact.download() + # epochs_trained = model_artifact.metadata.get('epochs_trained') + total_epochs = model_artifact.metadata.get('total_epochs') + is_finished = total_epochs is None + assert not is_finished, 'training is finished, can only resume incomplete runs.' + return modeldir, model_artifact + return None, None + + def log_model(self, path, opt, epoch, fitness_score, best_model=False): + """ + Log the model checkpoint as W&B artifact + + arguments: + path (Path) -- Path of directory containing the checkpoints + opt (namespace) -- Command line arguments for this run + epoch (int) -- Current epoch number + fitness_score (float) -- fitness score for current epoch + best_model (boolean) -- Boolean representing if the current checkpoint is the best yet. + """ + model_artifact = wandb.Artifact('run_' + wandb.run.id + '_model', type='model', metadata={ + 'original_url': str(path), + 'epochs_trained': epoch + 1, + 'save period': opt.save_period, + 'project': opt.project, + 'total_epochs': opt.epochs, + 'fitness_score': fitness_score + }) + model_artifact.add_file(str(path / 'last.pt'), name='last.pt') + wandb.log_artifact(model_artifact, + aliases=['latest', 'last', 'epoch ' + str(self.current_epoch), 'best' if best_model else '']) + LOGGER.info(f"Saving model artifact on epoch {epoch + 1}") + + def log_dataset_artifact(self, data_file, single_cls, project, overwrite_config=False): + """ + Log the dataset as W&B artifact and return the new data file with W&B links + + arguments: + data_file (str) -- the .yaml file with information about the dataset like - path, classes etc. + single_class (boolean) -- train multi-class data as single-class + project (str) -- project name. Used to construct the artifact path + overwrite_config (boolean) -- overwrites the data.yaml file if set to true otherwise creates a new + file with _wandb postfix. Eg -> data_wandb.yaml + + returns: + the new .yaml file with artifact links. it can be used to start training directly from artifacts + """ + upload_dataset = self.wandb_run.config.upload_dataset + log_val_only = isinstance(upload_dataset, str) and upload_dataset == 'val' + self.data_dict = check_dataset(data_file) # parse and check + data = dict(self.data_dict) + nc, names = (1, ['item']) if single_cls else (int(data['nc']), data['names']) + names = {k: v for k, v in enumerate(names)} # to index dictionary + + # log train set + if not log_val_only: + self.train_artifact = self.create_dataset_table(LoadImagesAndLabels( + data['train'], rect=True, batch_size=1), names, name='train') if data.get('train') else None + if data.get('train'): + data['train'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'train') + + self.val_artifact = self.create_dataset_table(LoadImagesAndLabels( + data['val'], rect=True, batch_size=1), names, name='val') if data.get('val') else None + if data.get('val'): + data['val'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'val') + + path = Path(data_file) + # create a _wandb.yaml file with artifacts links if both train and test set are logged + if not log_val_only: + path = (path.stem if overwrite_config else path.stem + '_wandb') + '.yaml' # updated data.yaml path + path = ROOT / 'data' / path + data.pop('download', None) + data.pop('path', None) + with open(path, 'w') as f: + yaml.safe_dump(data, f) + LOGGER.info(f"Created dataset config file {path}") + + if self.job_type == 'Training': # builds correct artifact pipeline graph + if not log_val_only: + self.wandb_run.log_artifact( + self.train_artifact) # calling use_artifact downloads the dataset. NOT NEEDED! + self.wandb_run.use_artifact(self.val_artifact) + self.val_artifact.wait() + self.val_table = self.val_artifact.get('val') + self.map_val_table_path() + else: + self.wandb_run.log_artifact(self.train_artifact) + self.wandb_run.log_artifact(self.val_artifact) + return path + + def map_val_table_path(self): + """ + Map the validation dataset Table like name of file -> it's id in the W&B Table. + Useful for - referencing artifacts for evaluation. + """ + self.val_table_path_map = {} + LOGGER.info("Mapping dataset") + for i, data in enumerate(tqdm(self.val_table.data)): + self.val_table_path_map[data[3]] = data[0] + + def create_dataset_table(self, dataset: LoadImagesAndLabels, class_to_id: Dict[int, str], name: str = 'dataset'): + """ + Create and return W&B artifact containing W&B Table of the dataset. + + arguments: + dataset -- instance of LoadImagesAndLabels class used to iterate over the data to build Table + class_to_id -- hash map that maps class ids to labels + name -- name of the artifact + + returns: + dataset artifact to be logged or used + """ + # TODO: Explore multiprocessing to slpit this loop parallely| This is essential for speeding up the the logging + artifact = wandb.Artifact(name=name, type="dataset") + img_files = tqdm([dataset.path]) if isinstance(dataset.path, str) and Path(dataset.path).is_dir() else None + img_files = tqdm(dataset.im_files) if not img_files else img_files + for img_file in img_files: + if Path(img_file).is_dir(): + artifact.add_dir(img_file, name='data/images') + labels_path = 'labels'.join(dataset.path.rsplit('images', 1)) + artifact.add_dir(labels_path, name='data/labels') + else: + artifact.add_file(img_file, name='data/images/' + Path(img_file).name) + label_file = Path(img2label_paths([img_file])[0]) + artifact.add_file(str(label_file), + name='data/labels/' + label_file.name) if label_file.exists() else None + table = wandb.Table(columns=["id", "train_image", "Classes", "name"]) + class_set = wandb.Classes([{'id': id, 'name': name} for id, name in class_to_id.items()]) + for si, (img, labels, paths, shapes) in enumerate(tqdm(dataset)): + box_data, img_classes = [], {} + for cls, *xywh in labels[:, 1:].tolist(): + cls = int(cls) + box_data.append({"position": {"middle": [xywh[0], xywh[1]], "width": xywh[2], "height": xywh[3]}, + "class_id": cls, + "box_caption": "%s" % (class_to_id[cls])}) + img_classes[cls] = class_to_id[cls] + boxes = {"ground_truth": {"box_data": box_data, "class_labels": class_to_id}} # inference-space + table.add_data(si, wandb.Image(paths, classes=class_set, boxes=boxes), list(img_classes.values()), + Path(paths).name) + artifact.add(table, name) + return artifact + + def log_training_progress(self, predn, path, names): + """ + Build evaluation Table. Uses reference from validation dataset table. + + arguments: + predn (list): list of predictions in the native space in the format - [xmin, ymin, xmax, ymax, confidence, class] + path (str): local path of the current evaluation image + names (dict(int, str)): hash map that maps class ids to labels + """ + class_set = wandb.Classes([{'id': id, 'name': name} for id, name in names.items()]) + box_data = [] + avg_conf_per_class = [0] * len(self.data_dict['names']) + pred_class_count = {} + for *xyxy, conf, cls in predn.tolist(): + if conf >= 0.25: + cls = int(cls) + box_data.append( + {"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]}, + "class_id": cls, + "box_caption": f"{names[cls]} {conf:.3f}", + "scores": {"class_score": conf}, + "domain": "pixel"}) + avg_conf_per_class[cls] += conf + + if cls in pred_class_count: + pred_class_count[cls] += 1 + else: + pred_class_count[cls] = 1 + + for pred_class in pred_class_count.keys(): + avg_conf_per_class[pred_class] = avg_conf_per_class[pred_class] / pred_class_count[pred_class] + + boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space + id = self.val_table_path_map[Path(path).name] + self.result_table.add_data(self.current_epoch, + id, + self.val_table.data[id][1], + wandb.Image(self.val_table.data[id][1], boxes=boxes, classes=class_set), + *avg_conf_per_class + ) + + def val_one_image(self, pred, predn, path, names, im): + """ + Log validation data for one image. updates the result Table if validation dataset is uploaded and log bbox media panel + + arguments: + pred (list): list of scaled predictions in the format - [xmin, ymin, xmax, ymax, confidence, class] + predn (list): list of predictions in the native space - [xmin, ymin, xmax, ymax, confidence, class] + path (str): local path of the current evaluation image + """ + if self.val_table and self.result_table: # Log Table if Val dataset is uploaded as artifact + self.log_training_progress(predn, path, names) + + if len(self.bbox_media_panel_images) < self.max_imgs_to_log and self.current_epoch > 0: + if self.current_epoch % self.bbox_interval == 0: + box_data = [{"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]}, + "class_id": int(cls), + "box_caption": f"{names[int(cls)]} {conf:.3f}", + "scores": {"class_score": conf}, + "domain": "pixel"} for *xyxy, conf, cls in pred.tolist()] + boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space + self.bbox_media_panel_images.append(wandb.Image(im, boxes=boxes, caption=path.name)) + + def log(self, log_dict): + """ + save the metrics to the logging dictionary + + arguments: + log_dict (Dict) -- metrics/media to be logged in current step + """ + if self.wandb_run: + for key, value in log_dict.items(): + self.log_dict[key] = value + + def end_epoch(self, best_result=False): + """ + commit the log_dict, model artifacts and Tables to W&B and flush the log_dict. + + arguments: + best_result (boolean): Boolean representing if the result of this evaluation is best or not + """ + if self.wandb_run: + with all_logging_disabled(): + if self.bbox_media_panel_images: + self.log_dict["BoundingBoxDebugger"] = self.bbox_media_panel_images + try: + wandb.log(self.log_dict) + except BaseException as e: + LOGGER.info( + f"An error occurred in wandb logger. The training will proceed without interruption. More info\n{e}") + self.wandb_run.finish() + self.wandb_run = None + + self.log_dict = {} + self.bbox_media_panel_images = [] + if self.result_artifact: + self.result_artifact.add(self.result_table, 'result') + wandb.log_artifact(self.result_artifact, aliases=['latest', 'last', 'epoch ' + str(self.current_epoch), + ('best' if best_result else '')]) + + wandb.log({"evaluation": self.result_table}) + columns = ["epoch", "id", "ground truth", "prediction"] + columns.extend(self.data_dict['names']) + self.result_table = wandb.Table(columns) + self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation") + + def finish_run(self): + """ + Log metrics if any and finish the current W&B run + """ + if self.wandb_run: + if self.log_dict: + with all_logging_disabled(): + wandb.log(self.log_dict) + wandb.run.finish() + + +@contextmanager +def all_logging_disabled(highest_level=logging.CRITICAL): + """ source - https://gist.github.com/simon-weber/7853144 + A context manager that will prevent any logging messages triggered during the body from being processed. + :param highest_level: the maximum logging level in use. + This would only need to be changed if a custom level greater than CRITICAL is defined. + """ + previous_level = logging.root.manager.disable + logging.disable(highest_level) + try: + yield + finally: + logging.disable(previous_level) diff --git a/core/vision/yolov5/utils/loss.py b/core/vision/yolov5/utils/loss.py new file mode 100644 index 00000000..0f013781 --- /dev/null +++ b/core/vision/yolov5/utils/loss.py @@ -0,0 +1,223 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Loss functions +""" + +import torch +import torch.nn as nn + +from utils.metrics import bbox_iou +from utils.torch_utils import de_parallel + + +def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441 + # return positive, negative label smoothing BCE targets + return 1.0 - 0.5 * eps, 0.5 * eps + + +class BCEBlurWithLogitsLoss(nn.Module): + # BCEwithLogitLoss() with reduced missing label effects. + def __init__(self, alpha=0.05): + super().__init__() + self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none') # must be nn.BCEWithLogitsLoss() + self.alpha = alpha + + def forward(self, pred, true): + loss = self.loss_fcn(pred, true) + pred = torch.sigmoid(pred) # prob from logits + dx = pred - true # reduce only missing label effects + # dx = (pred - true).abs() # reduce missing label and false label effects + alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4)) + loss *= alpha_factor + return loss.mean() + + +class FocalLoss(nn.Module): + # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5) + def __init__(self, loss_fcn, gamma=1.5, alpha=0.25): + super().__init__() + self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss() + self.gamma = gamma + self.alpha = alpha + self.reduction = loss_fcn.reduction + self.loss_fcn.reduction = 'none' # required to apply FL to each element + + def forward(self, pred, true): + loss = self.loss_fcn(pred, true) + # p_t = torch.exp(-loss) + # loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability + + # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py + pred_prob = torch.sigmoid(pred) # prob from logits + p_t = true * pred_prob + (1 - true) * (1 - pred_prob) + alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha) + modulating_factor = (1.0 - p_t) ** self.gamma + loss *= alpha_factor * modulating_factor + + if self.reduction == 'mean': + return loss.mean() + elif self.reduction == 'sum': + return loss.sum() + else: # 'none' + return loss + + +class QFocalLoss(nn.Module): + # Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5) + def __init__(self, loss_fcn, gamma=1.5, alpha=0.25): + super().__init__() + self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss() + self.gamma = gamma + self.alpha = alpha + self.reduction = loss_fcn.reduction + self.loss_fcn.reduction = 'none' # required to apply FL to each element + + def forward(self, pred, true): + loss = self.loss_fcn(pred, true) + + pred_prob = torch.sigmoid(pred) # prob from logits + alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha) + modulating_factor = torch.abs(true - pred_prob) ** self.gamma + loss *= alpha_factor * modulating_factor + + if self.reduction == 'mean': + return loss.mean() + elif self.reduction == 'sum': + return loss.sum() + else: # 'none' + return loss + + +class ComputeLoss: + sort_obj_iou = False + + # Compute losses + def __init__(self, model, autobalance=False): + device = next(model.parameters()).device # get model device + h = model.hyp # hyperparameters + + # Define criteria + BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device)) + BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device)) + + # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3 + self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets + + # Focal loss + g = h['fl_gamma'] # focal loss gamma + if g > 0: + BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g) + + det = de_parallel(model).model[-1] # Detect() module + self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.06, 0.02]) # P3-P7 + self.ssi = list(det.stride).index(16) if autobalance else 0 # stride 16 index + self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, 1.0, h, autobalance + self.device = device + for k in 'na', 'nc', 'nl', 'anchors': + setattr(self, k, getattr(det, k)) + + def __call__(self, p, targets): # predictions, targets + lcls = torch.zeros(1, device=self.device) # class loss + lbox = torch.zeros(1, device=self.device) # box loss + lobj = torch.zeros(1, device=self.device) # object loss + tcls, tbox, indices, anchors = self.build_targets(p, targets) # targets + + # Losses + for i, pi in enumerate(p): # layer index, layer predictions + b, a, gj, gi = indices[i] # image, anchor, gridy, gridx + tobj = torch.zeros(pi.shape[:4], device=self.device) # target obj + + n = b.shape[0] # number of targets + if n: + pxy, pwh, _, pcls = pi[b, a, gj, gi].tensor_split((2, 4, 5), dim=1) # target-subset of predictions + + # Regression + pxy = pxy.sigmoid() * 2 - 0.5 + pwh = (pwh.sigmoid() * 2) ** 2 * anchors[i] + pbox = torch.cat((pxy, pwh), 1) # predicted box + iou = bbox_iou(pbox.T, tbox[i], x1y1x2y2=False, CIoU=True) # iou(prediction, target) + lbox += (1.0 - iou).mean() # iou loss + + # Objectness + score_iou = iou.detach().clamp(0).type(tobj.dtype) + if self.sort_obj_iou: + sort_id = torch.argsort(score_iou) + b, a, gj, gi, score_iou = b[sort_id], a[sort_id], gj[sort_id], gi[sort_id], score_iou[sort_id] + tobj[b, a, gj, gi] = (1.0 - self.gr) + self.gr * score_iou # iou ratio + + # Classification + if self.nc > 1: # cls loss (only if multiple classes) + t = torch.full_like(pcls, self.cn, device=self.device) # targets + t[range(n), tcls[i]] = self.cp + lcls += self.BCEcls(pcls, t) # BCE + + # Append targets to text file + # with open('targets.txt', 'a') as file: + # [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)] + + obji = self.BCEobj(pi[..., 4], tobj) + lobj += obji * self.balance[i] # obj loss + if self.autobalance: + self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item() + + if self.autobalance: + self.balance = [x / self.balance[self.ssi] for x in self.balance] + lbox *= self.hyp['box'] + lobj *= self.hyp['obj'] + lcls *= self.hyp['cls'] + bs = tobj.shape[0] # batch size + + return (lbox + lobj + lcls) * bs, torch.cat((lbox, lobj, lcls)).detach() + + def build_targets(self, p, targets): + # Build targets for compute_loss(), input targets(image,class,x,y,w,h) + na, nt = self.na, targets.shape[0] # number of anchors, targets + tcls, tbox, indices, anch = [], [], [], [] + gain = torch.ones(7, device=self.device) # normalized to gridspace gain + ai = torch.arange(na, device=self.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt) + targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices + + g = 0.5 # bias + off = torch.tensor([[0, 0], + [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m + # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm + ], device=self.device).float() * g # offsets + + for i in range(self.nl): + anchors = self.anchors[i] + gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain + + # Match targets to anchors + t = targets * gain + if nt: + # Matches + r = t[:, :, 4:6] / anchors[:, None] # wh ratio + j = torch.max(r, 1 / r).max(2)[0] < self.hyp['anchor_t'] # compare + # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2)) + t = t[j] # filter + + # Offsets + gxy = t[:, 2:4] # grid xy + gxi = gain[[2, 3]] - gxy # inverse + j, k = ((gxy % 1 < g) & (gxy > 1)).T + l, m = ((gxi % 1 < g) & (gxi > 1)).T + j = torch.stack((torch.ones_like(j), j, k, l, m)) + t = t.repeat((5, 1, 1))[j] + offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j] + else: + t = targets[0] + offsets = 0 + + # Define + bc, gxy, gwh, a = t.unsafe_chunk(4, dim=1) # (image, class), grid xy, grid wh, anchors + a, (b, c) = a.long().view(-1), bc.long().T # anchors, image, class + gij = (gxy - offsets).long() + gi, gj = gij.T # grid indices + + # Append + indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices + tbox.append(torch.cat((gxy - gij, gwh), 1)) # box + anch.append(anchors[a]) # anchors + tcls.append(c) # class + + return tcls, tbox, indices, anch diff --git a/core/vision/yolov5/utils/metrics.py b/core/vision/yolov5/utils/metrics.py new file mode 100644 index 00000000..857fa5d8 --- /dev/null +++ b/core/vision/yolov5/utils/metrics.py @@ -0,0 +1,342 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Model validation metrics +""" + +import math +import warnings +from pathlib import Path + +import matplotlib.pyplot as plt +import numpy as np +import torch + + +def fitness(x): + # Model fitness as a weighted combination of metrics + w = [0.0, 0.0, 0.1, 0.9] # weights for [P, R, mAP@0.5, mAP@0.5:0.95] + return (x[:, :4] * w).sum(1) + + +def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='.', names=(), eps=1e-16): + """ Compute the average precision, given the recall and precision curves. + Source: https://github.com/rafaelpadilla/Object-Detection-Metrics. + # Arguments + tp: True positives (nparray, nx1 or nx10). + conf: Objectness value from 0-1 (nparray). + pred_cls: Predicted object classes (nparray). + target_cls: True object classes (nparray). + plot: Plot precision-recall curve at mAP@0.5 + save_dir: Plot save directory + # Returns + The average precision as computed in py-faster-rcnn. + """ + + # Sort by objectness + i = np.argsort(-conf) + tp, conf, pred_cls = tp[i], conf[i], pred_cls[i] + + # Find unique classes + unique_classes, nt = np.unique(target_cls, return_counts=True) + nc = unique_classes.shape[0] # number of classes, number of detections + + # Create Precision-Recall curve and compute AP for each class + px, py = np.linspace(0, 1, 1000), [] # for plotting + ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000)) + for ci, c in enumerate(unique_classes): + i = pred_cls == c + n_l = nt[ci] # number of labels + n_p = i.sum() # number of predictions + + if n_p == 0 or n_l == 0: + continue + else: + # Accumulate FPs and TPs + fpc = (1 - tp[i]).cumsum(0) + tpc = tp[i].cumsum(0) + + # Recall + recall = tpc / (n_l + eps) # recall curve + r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases + + # Precision + precision = tpc / (tpc + fpc) # precision curve + p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1) # p at pr_score + + # AP from recall-precision curve + for j in range(tp.shape[1]): + ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j]) + if plot and j == 0: + py.append(np.interp(px, mrec, mpre)) # precision at mAP@0.5 + + # Compute F1 (harmonic mean of precision and recall) + f1 = 2 * p * r / (p + r + eps) + names = [v for k, v in names.items() if k in unique_classes] # list: only classes that have data + names = {i: v for i, v in enumerate(names)} # to dict + if plot: + plot_pr_curve(px, py, ap, Path(save_dir) / 'PR_curve.png', names) + plot_mc_curve(px, f1, Path(save_dir) / 'F1_curve.png', names, ylabel='F1') + plot_mc_curve(px, p, Path(save_dir) / 'P_curve.png', names, ylabel='Precision') + plot_mc_curve(px, r, Path(save_dir) / 'R_curve.png', names, ylabel='Recall') + + i = f1.mean(0).argmax() # max F1 index + p, r, f1 = p[:, i], r[:, i], f1[:, i] + tp = (r * nt).round() # true positives + fp = (tp / (p + eps) - tp).round() # false positives + return tp, fp, p, r, f1, ap, unique_classes.astype('int32') + + +def compute_ap(recall, precision): + """ Compute the average precision, given the recall and precision curves + # Arguments + recall: The recall curve (list) + precision: The precision curve (list) + # Returns + Average precision, precision curve, recall curve + """ + + # Append sentinel values to beginning and end + mrec = np.concatenate(([0.0], recall, [1.0])) + mpre = np.concatenate(([1.0], precision, [0.0])) + + # Compute the precision envelope + mpre = np.flip(np.maximum.accumulate(np.flip(mpre))) + + # Integrate area under curve + method = 'interp' # methods: 'continuous', 'interp' + if method == 'interp': + x = np.linspace(0, 1, 101) # 101-point interp (COCO) + ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate + else: # 'continuous' + i = np.where(mrec[1:] != mrec[:-1])[0] # points where x axis (recall) changes + ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve + + return ap, mpre, mrec + + +class ConfusionMatrix: + # Updated version of https://github.com/kaanakan/object_detection_confusion_matrix + def __init__(self, nc, conf=0.25, iou_thres=0.45): + self.matrix = np.zeros((nc + 1, nc + 1)) + self.nc = nc # number of classes + self.conf = conf + self.iou_thres = iou_thres + + def process_batch(self, detections, labels): + """ + Return intersection-over-union (Jaccard index) of boxes. + Both sets of boxes are expected to be in (x1, y1, x2, y2) format. + Arguments: + detections (Array[N, 6]), x1, y1, x2, y2, conf, class + labels (Array[M, 5]), class, x1, y1, x2, y2 + Returns: + None, updates confusion matrix accordingly + """ + detections = detections[detections[:, 4] > self.conf] + gt_classes = labels[:, 0].int() + detection_classes = detections[:, 5].int() + iou = box_iou(labels[:, 1:], detections[:, :4]) + + x = torch.where(iou > self.iou_thres) + if x[0].shape[0]: + matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy() + if x[0].shape[0] > 1: + matches = matches[matches[:, 2].argsort()[::-1]] + matches = matches[np.unique(matches[:, 1], return_index=True)[1]] + matches = matches[matches[:, 2].argsort()[::-1]] + matches = matches[np.unique(matches[:, 0], return_index=True)[1]] + else: + matches = np.zeros((0, 3)) + + n = matches.shape[0] > 0 + m0, m1, _ = matches.transpose().astype(np.int16) + for i, gc in enumerate(gt_classes): + j = m0 == i + if n and sum(j) == 1: + self.matrix[detection_classes[m1[j]], gc] += 1 # correct + else: + self.matrix[self.nc, gc] += 1 # background FP + + if n: + for i, dc in enumerate(detection_classes): + if not any(m1 == i): + self.matrix[dc, self.nc] += 1 # background FN + + def matrix(self): + return self.matrix + + def tp_fp(self): + tp = self.matrix.diagonal() # true positives + fp = self.matrix.sum(1) - tp # false positives + # fn = self.matrix.sum(0) - tp # false negatives (missed detections) + return tp[:-1], fp[:-1] # remove background class + + def plot(self, normalize=True, save_dir='', names=()): + try: + import seaborn as sn + + array = self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1E-9) if normalize else 1) # normalize columns + array[array < 0.005] = np.nan # don't annotate (would appear as 0.00) + + fig = plt.figure(figsize=(12, 9), tight_layout=True) + nc, nn = self.nc, len(names) # number of classes, names + sn.set(font_scale=1.0 if nc < 50 else 0.8) # for label size + labels = (0 < nn < 99) and (nn == nc) # apply names to ticklabels + with warnings.catch_warnings(): + warnings.simplefilter('ignore') # suppress empty matrix RuntimeWarning: All-NaN slice encountered + sn.heatmap(array, annot=nc < 30, annot_kws={"size": 8}, cmap='Blues', fmt='.2f', square=True, vmin=0.0, + xticklabels=names + ['background FP'] if labels else "auto", + yticklabels=names + ['background FN'] if labels else "auto").set_facecolor((1, 1, 1)) + fig.axes[0].set_xlabel('True') + fig.axes[0].set_ylabel('Predicted') + fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250) + plt.close() + except Exception as e: + print(f'WARNING: ConfusionMatrix plot failure: {e}') + + def print(self): + for i in range(self.nc + 1): + print(' '.join(map(str, self.matrix[i]))) + + +def bbox_iou(box1, box2, x1y1x2y2=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-7): + # Returns the IoU of box1 to box2. box1 is 4, box2 is nx4 + box2 = box2.T + + # Get the coordinates of bounding boxes + if x1y1x2y2: # x1, y1, x2, y2 = box1 + b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3] + b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3] + else: # transform from xywh to xyxy + b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2 + b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2 + b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2 + b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2 + + # Intersection area + inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \ + (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0) + + # Union Area + w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps + w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps + union = w1 * h1 + w2 * h2 - inter + eps + + iou = inter / union + if CIoU or DIoU or GIoU: + cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex (smallest enclosing box) width + ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height + if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1 + c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared + rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center distance squared + if CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47 + v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2) + with torch.no_grad(): + alpha = v / (v - iou + (1 + eps)) + return iou - (rho2 / c2 + v * alpha) # CIoU + return iou - rho2 / c2 # DIoU + c_area = cw * ch + eps # convex area + return iou - (c_area - union) / c_area # GIoU https://arxiv.org/pdf/1902.09630.pdf + return iou # IoU + + +def box_iou(box1, box2): + # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py + """ + Return intersection-over-union (Jaccard index) of boxes. + Both sets of boxes are expected to be in (x1, y1, x2, y2) format. + Arguments: + box1 (Tensor[N, 4]) + box2 (Tensor[M, 4]) + Returns: + iou (Tensor[N, M]): the NxM matrix containing the pairwise + IoU values for every element in boxes1 and boxes2 + """ + + def box_area(box): + # box = 4xn + return (box[2] - box[0]) * (box[3] - box[1]) + + area1 = box_area(box1.T) + area2 = box_area(box2.T) + + # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2) + inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2) + return inter / (area1[:, None] + area2 - inter) # iou = inter / (area1 + area2 - inter) + + +def bbox_ioa(box1, box2, eps=1E-7): + """ Returns the intersection over box2 area given box1, box2. Boxes are x1y1x2y2 + box1: np.array of shape(4) + box2: np.array of shape(nx4) + returns: np.array of shape(n) + """ + + box2 = box2.transpose() + + # Get the coordinates of bounding boxes + b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3] + b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3] + + # Intersection area + inter_area = (np.minimum(b1_x2, b2_x2) - np.maximum(b1_x1, b2_x1)).clip(0) * \ + (np.minimum(b1_y2, b2_y2) - np.maximum(b1_y1, b2_y1)).clip(0) + + # box2 area + box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + eps + + # Intersection over box2 area + return inter_area / box2_area + + +def wh_iou(wh1, wh2): + # Returns the nxm IoU matrix. wh1 is nx2, wh2 is mx2 + wh1 = wh1[:, None] # [N,1,2] + wh2 = wh2[None] # [1,M,2] + inter = torch.min(wh1, wh2).prod(2) # [N,M] + return inter / (wh1.prod(2) + wh2.prod(2) - inter) # iou = inter / (area1 + area2 - inter) + + +# Plots ---------------------------------------------------------------------------------------------------------------- + +def plot_pr_curve(px, py, ap, save_dir='pr_curve.png', names=()): + # Precision-recall curve + fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True) + py = np.stack(py, axis=1) + + if 0 < len(names) < 21: # display per-class legend if < 21 classes + for i, y in enumerate(py.T): + ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}') # plot(recall, precision) + else: + ax.plot(px, py, linewidth=1, color='grey') # plot(recall, precision) + + ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f mAP@0.5' % ap[:, 0].mean()) + ax.set_xlabel('Recall') + ax.set_ylabel('Precision') + ax.set_xlim(0, 1) + ax.set_ylim(0, 1) + plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left") + fig.savefig(Path(save_dir), dpi=250) + plt.close() + + +def plot_mc_curve(px, py, save_dir='mc_curve.png', names=(), xlabel='Confidence', ylabel='Metric'): + # Metric-confidence curve + fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True) + + if 0 < len(names) < 21: # display per-class legend if < 21 classes + for i, y in enumerate(py): + ax.plot(px, y, linewidth=1, label=f'{names[i]}') # plot(confidence, metric) + else: + ax.plot(px, py.T, linewidth=1, color='grey') # plot(confidence, metric) + + y = py.mean(0) + ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}') + ax.set_xlabel(xlabel) + ax.set_ylabel(ylabel) + ax.set_xlim(0, 1) + ax.set_ylim(0, 1) + plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left") + fig.savefig(Path(save_dir), dpi=250) + plt.close() diff --git a/core/vision/yolov5/utils/plots.py b/core/vision/yolov5/utils/plots.py new file mode 100644 index 00000000..a30c0faf --- /dev/null +++ b/core/vision/yolov5/utils/plots.py @@ -0,0 +1,476 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Plotting utils +""" + +import math +import os +from copy import copy +from pathlib import Path +from urllib.error import URLError + +import cv2 +import matplotlib +import matplotlib.pyplot as plt +import numpy as np +import pandas as pd +import seaborn as sn +import torch +from PIL import Image, ImageDraw, ImageFont + +from utils.general import (CONFIG_DIR, FONT, LOGGER, Timeout, check_font, check_requirements, clip_coords, + increment_path, is_ascii, is_chinese, try_except, xywh2xyxy, xyxy2xywh) +from utils.metrics import fitness + +# Settings +RANK = int(os.getenv('RANK', -1)) +matplotlib.rc('font', **{'size': 11}) +matplotlib.use('Agg') # for writing to files only + + +class Colors: + # Ultralytics color palette https://ultralytics.com/ + def __init__(self): + # hex = matplotlib.colors.TABLEAU_COLORS.values() + hex = ('FF3838', 'FF9D97', 'FF701F', 'FFB21D', 'CFD231', '48F90A', '92CC17', '3DDB86', '1A9334', '00D4BB', + '2C99A8', '00C2FF', '344593', '6473FF', '0018EC', '8438FF', '520085', 'CB38FF', 'FF95C8', 'FF37C7') + self.palette = [self.hex2rgb('#' + c) for c in hex] + self.n = len(self.palette) + + def __call__(self, i, bgr=False): + c = self.palette[int(i) % self.n] + return (c[2], c[1], c[0]) if bgr else c + + @staticmethod + def hex2rgb(h): # rgb order (PIL) + return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4)) + + +colors = Colors() # create instance for 'from utils.plots import colors' + + +def check_pil_font(font=FONT, size=10): + # Return a PIL TrueType Font, downloading to CONFIG_DIR if necessary + font = Path(font) + font = font if font.exists() else (CONFIG_DIR / font.name) + try: + return ImageFont.truetype(str(font) if font.exists() else font.name, size) + except Exception: # download if missing + try: + check_font(font) + return ImageFont.truetype(str(font), size) + except TypeError: + check_requirements('Pillow>=8.4.0') # known issue https://github.com/ultralytics/yolov5/issues/5374 + except URLError: # not online + return ImageFont.load_default() + + +class Annotator: + if RANK in (-1, 0): + check_pil_font() # download TTF if necessary + + # YOLOv5 Annotator for train/val mosaics and jpgs and detect/hub inference annotations + def __init__(self, im, line_width=None, font_size=None, font='Arial.ttf', pil=False, example='abc'): + assert im.data.contiguous, 'Image not contiguous. Apply np.ascontiguousarray(im) to Annotator() input images.' + self.pil = pil or not is_ascii(example) or is_chinese(example) + if self.pil: # use PIL + self.im = im if isinstance(im, Image.Image) else Image.fromarray(im) + self.draw = ImageDraw.Draw(self.im) + self.font = check_pil_font(font='Arial.Unicode.ttf' if is_chinese(example) else font, + size=font_size or max(round(sum(self.im.size) / 2 * 0.035), 12)) + else: # use cv2 + self.im = im + self.lw = line_width or max(round(sum(im.shape) / 2 * 0.003), 2) # line width + + def box_label(self, box, label='', color=(128, 128, 128), txt_color=(255, 255, 255)): + # Add one xyxy box to image with label + if self.pil or not is_ascii(label): + self.draw.rectangle(box, width=self.lw, outline=color) # box + if label: + w, h = self.font.getsize(label) # text width, height + outside = box[1] - h >= 0 # label fits outside box + self.draw.rectangle((box[0], + box[1] - h if outside else box[1], + box[0] + w + 1, + box[1] + 1 if outside else box[1] + h + 1), fill=color) + # self.draw.text((box[0], box[1]), label, fill=txt_color, font=self.font, anchor='ls') # for PIL>8.0 + self.draw.text((box[0], box[1] - h if outside else box[1]), label, fill=txt_color, font=self.font) + else: # cv2 + p1, p2 = (int(box[0]), int(box[1])), (int(box[2]), int(box[3])) + cv2.rectangle(self.im, p1, p2, color, thickness=self.lw, lineType=cv2.LINE_AA) + if label: + tf = max(self.lw - 1, 1) # font thickness + w, h = cv2.getTextSize(label, 0, fontScale=self.lw / 3, thickness=tf)[0] # text width, height + outside = p1[1] - h - 3 >= 0 # label fits outside box + p2 = p1[0] + w, p1[1] - h - 3 if outside else p1[1] + h + 3 + cv2.rectangle(self.im, p1, p2, color, -1, cv2.LINE_AA) # filled + cv2.putText(self.im, label, (p1[0], p1[1] - 2 if outside else p1[1] + h + 2), 0, self.lw / 3, txt_color, + thickness=tf, lineType=cv2.LINE_AA) + + def rectangle(self, xy, fill=None, outline=None, width=1): + # Add rectangle to image (PIL-only) + self.draw.rectangle(xy, fill, outline, width) + + def text(self, xy, text, txt_color=(255, 255, 255)): + # Add text to image (PIL-only) + w, h = self.font.getsize(text) # text width, height + self.draw.text((xy[0], xy[1] - h + 1), text, fill=txt_color, font=self.font) + + def result(self): + # Return annotated image as array + return np.asarray(self.im) + + +def feature_visualization(x, module_type, stage, n=32, save_dir=Path('runs/detect/exp')): + """ + x: Features to be visualized + module_type: Module type + stage: Module stage within model + n: Maximum number of feature maps to plot + save_dir: Directory to save results + """ + if 'Detect' not in module_type: + batch, channels, height, width = x.shape # batch, channels, height, width + if height > 1 and width > 1: + f = save_dir / f"stage{stage}_{module_type.split('.')[-1]}_features.png" # filename + + blocks = torch.chunk(x[0].cpu(), channels, dim=0) # select batch index 0, block by channels + n = min(n, channels) # number of plots + fig, ax = plt.subplots(math.ceil(n / 8), 8, tight_layout=True) # 8 rows x n/8 cols + ax = ax.ravel() + plt.subplots_adjust(wspace=0.05, hspace=0.05) + for i in range(n): + ax[i].imshow(blocks[i].squeeze()) # cmap='gray' + ax[i].axis('off') + + LOGGER.info(f'Saving {f}... ({n}/{channels})') + plt.savefig(f, dpi=300, bbox_inches='tight') + plt.close() + np.save(str(f.with_suffix('.npy')), x[0].cpu().numpy()) # npy save + + +def hist2d(x, y, n=100): + # 2d histogram used in labels.png and evolve.png + xedges, yedges = np.linspace(x.min(), x.max(), n), np.linspace(y.min(), y.max(), n) + hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges)) + xidx = np.clip(np.digitize(x, xedges) - 1, 0, hist.shape[0] - 1) + yidx = np.clip(np.digitize(y, yedges) - 1, 0, hist.shape[1] - 1) + return np.log(hist[xidx, yidx]) + + +def butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5): + from scipy.signal import butter, filtfilt + + # https://stackoverflow.com/questions/28536191/how-to-filter-smooth-with-scipy-numpy + def butter_lowpass(cutoff, fs, order): + nyq = 0.5 * fs + normal_cutoff = cutoff / nyq + return butter(order, normal_cutoff, btype='low', analog=False) + + b, a = butter_lowpass(cutoff, fs, order=order) + return filtfilt(b, a, data) # forward-backward filter + + +def output_to_target(output): + # Convert model output to target format [batch_id, class_id, x, y, w, h, conf] + targets = [] + for i, o in enumerate(output): + for *box, conf, cls in o.cpu().numpy(): + targets.append([i, cls, *list(*xyxy2xywh(np.array(box)[None])), conf]) + return np.array(targets) + + +def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=1920, max_subplots=16): + # Plot image grid with labels + if isinstance(images, torch.Tensor): + images = images.cpu().float().numpy() + if isinstance(targets, torch.Tensor): + targets = targets.cpu().numpy() + if np.max(images[0]) <= 1: + images *= 255 # de-normalise (optional) + bs, _, h, w = images.shape # batch size, _, height, width + bs = min(bs, max_subplots) # limit plot images + ns = np.ceil(bs ** 0.5) # number of subplots (square) + + # Build Image + mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init + for i, im in enumerate(images): + if i == max_subplots: # if last batch has fewer images than we expect + break + x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin + im = im.transpose(1, 2, 0) + mosaic[y:y + h, x:x + w, :] = im + + # Resize (optional) + scale = max_size / ns / max(h, w) + if scale < 1: + h = math.ceil(scale * h) + w = math.ceil(scale * w) + mosaic = cv2.resize(mosaic, tuple(int(x * ns) for x in (w, h))) + + # Annotate + fs = int((h + w) * ns * 0.01) # font size + annotator = Annotator(mosaic, line_width=round(fs / 10), font_size=fs, pil=True, example=names) + for i in range(i + 1): + x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin + annotator.rectangle([x, y, x + w, y + h], None, (255, 255, 255), width=2) # borders + if paths: + annotator.text((x + 5, y + 5 + h), text=Path(paths[i]).name[:40], txt_color=(220, 220, 220)) # filenames + if len(targets) > 0: + ti = targets[targets[:, 0] == i] # image targets + boxes = xywh2xyxy(ti[:, 2:6]).T + classes = ti[:, 1].astype('int') + labels = ti.shape[1] == 6 # labels if no conf column + conf = None if labels else ti[:, 6] # check for confidence presence (label vs pred) + + if boxes.shape[1]: + if boxes.max() <= 1.01: # if normalized with tolerance 0.01 + boxes[[0, 2]] *= w # scale to pixels + boxes[[1, 3]] *= h + elif scale < 1: # absolute coords need scale if image scales + boxes *= scale + boxes[[0, 2]] += x + boxes[[1, 3]] += y + for j, box in enumerate(boxes.T.tolist()): + cls = classes[j] + color = colors(cls) + cls = names[cls] if names else cls + if labels or conf[j] > 0.25: # 0.25 conf thresh + label = f'{cls}' if labels else f'{cls} {conf[j]:.1f}' + annotator.box_label(box, label, color=color) + annotator.im.save(fname) # save + + +def plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=''): + # Plot LR simulating training for full epochs + optimizer, scheduler = copy(optimizer), copy(scheduler) # do not modify originals + y = [] + for _ in range(epochs): + scheduler.step() + y.append(optimizer.param_groups[0]['lr']) + plt.plot(y, '.-', label='LR') + plt.xlabel('epoch') + plt.ylabel('LR') + plt.grid() + plt.xlim(0, epochs) + plt.ylim(0) + plt.savefig(Path(save_dir) / 'LR.png', dpi=200) + plt.close() + + +def plot_val_txt(): # from utils.plots import *; plot_val() + # Plot val.txt histograms + x = np.loadtxt('val.txt', dtype=np.float32) + box = xyxy2xywh(x[:, :4]) + cx, cy = box[:, 0], box[:, 1] + + fig, ax = plt.subplots(1, 1, figsize=(6, 6), tight_layout=True) + ax.hist2d(cx, cy, bins=600, cmax=10, cmin=0) + ax.set_aspect('equal') + plt.savefig('hist2d.png', dpi=300) + + fig, ax = plt.subplots(1, 2, figsize=(12, 6), tight_layout=True) + ax[0].hist(cx, bins=600) + ax[1].hist(cy, bins=600) + plt.savefig('hist1d.png', dpi=200) + + +def plot_targets_txt(): # from utils.plots import *; plot_targets_txt() + # Plot targets.txt histograms + x = np.loadtxt('targets.txt', dtype=np.float32).T + s = ['x targets', 'y targets', 'width targets', 'height targets'] + fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True) + ax = ax.ravel() + for i in range(4): + ax[i].hist(x[i], bins=100, label=f'{x[i].mean():.3g} +/- {x[i].std():.3g}') + ax[i].legend() + ax[i].set_title(s[i]) + plt.savefig('targets.jpg', dpi=200) + + +def plot_val_study(file='', dir='', x=None): # from utils.plots import *; plot_val_study() + # Plot file=study.txt generated by val.py (or plot all study*.txt in dir) + save_dir = Path(file).parent if file else Path(dir) + plot2 = False # plot additional results + if plot2: + ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True)[1].ravel() + + fig2, ax2 = plt.subplots(1, 1, figsize=(8, 4), tight_layout=True) + # for f in [save_dir / f'study_coco_{x}.txt' for x in ['yolov5n6', 'yolov5s6', 'yolov5m6', 'yolov5l6', 'yolov5x6']]: + for f in sorted(save_dir.glob('study*.txt')): + y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T + x = np.arange(y.shape[1]) if x is None else np.array(x) + if plot2: + s = ['P', 'R', 'mAP@.5', 'mAP@.5:.95', 't_preprocess (ms/img)', 't_inference (ms/img)', 't_NMS (ms/img)'] + for i in range(7): + ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8) + ax[i].set_title(s[i]) + + j = y[3].argmax() + 1 + ax2.plot(y[5, 1:j], y[3, 1:j] * 1E2, '.-', linewidth=2, markersize=8, + label=f.stem.replace('study_coco_', '').replace('yolo', 'YOLO')) + + ax2.plot(1E3 / np.array([209, 140, 97, 58, 35, 18]), [34.6, 40.5, 43.0, 47.5, 49.7, 51.5], + 'k.-', linewidth=2, markersize=8, alpha=.25, label='EfficientDet') + + ax2.grid(alpha=0.2) + ax2.set_yticks(np.arange(20, 60, 5)) + ax2.set_xlim(0, 57) + ax2.set_ylim(25, 55) + ax2.set_xlabel('GPU Speed (ms/img)') + ax2.set_ylabel('COCO AP val') + ax2.legend(loc='lower right') + f = save_dir / 'study.png' + print(f'Saving {f}...') + plt.savefig(f, dpi=300) + + +@try_except # known issue https://github.com/ultralytics/yolov5/issues/5395 +@Timeout(30) # known issue https://github.com/ultralytics/yolov5/issues/5611 +def plot_labels(labels, names=(), save_dir=Path('')): + # plot dataset labels + LOGGER.info(f"Plotting labels to {save_dir / 'labels.jpg'}... ") + c, b = labels[:, 0], labels[:, 1:].transpose() # classes, boxes + nc = int(c.max() + 1) # number of classes + x = pd.DataFrame(b.transpose(), columns=['x', 'y', 'width', 'height']) + + # seaborn correlogram + sn.pairplot(x, corner=True, diag_kind='auto', kind='hist', diag_kws=dict(bins=50), plot_kws=dict(pmax=0.9)) + plt.savefig(save_dir / 'labels_correlogram.jpg', dpi=200) + plt.close() + + # matplotlib labels + matplotlib.use('svg') # faster + ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel() + y = ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8) + try: # color histogram bars by class + [y[2].patches[i].set_color([x / 255 for x in colors(i)]) for i in range(nc)] # known issue #3195 + except Exception: + pass + ax[0].set_ylabel('instances') + if 0 < len(names) < 30: + ax[0].set_xticks(range(len(names))) + ax[0].set_xticklabels(names, rotation=90, fontsize=10) + else: + ax[0].set_xlabel('classes') + sn.histplot(x, x='x', y='y', ax=ax[2], bins=50, pmax=0.9) + sn.histplot(x, x='width', y='height', ax=ax[3], bins=50, pmax=0.9) + + # rectangles + labels[:, 1:3] = 0.5 # center + labels[:, 1:] = xywh2xyxy(labels[:, 1:]) * 2000 + img = Image.fromarray(np.ones((2000, 2000, 3), dtype=np.uint8) * 255) + for cls, *box in labels[:1000]: + ImageDraw.Draw(img).rectangle(box, width=1, outline=colors(cls)) # plot + ax[1].imshow(img) + ax[1].axis('off') + + for a in [0, 1, 2, 3]: + for s in ['top', 'right', 'left', 'bottom']: + ax[a].spines[s].set_visible(False) + + plt.savefig(save_dir / 'labels.jpg', dpi=200) + matplotlib.use('Agg') + plt.close() + + +def plot_evolve(evolve_csv='path/to/evolve.csv'): # from utils.plots import *; plot_evolve() + # Plot evolve.csv hyp evolution results + evolve_csv = Path(evolve_csv) + data = pd.read_csv(evolve_csv) + keys = [x.strip() for x in data.columns] + x = data.values + f = fitness(x) + j = np.argmax(f) # max fitness index + plt.figure(figsize=(10, 12), tight_layout=True) + matplotlib.rc('font', **{'size': 8}) + print(f'Best results from row {j} of {evolve_csv}:') + for i, k in enumerate(keys[7:]): + v = x[:, 7 + i] + mu = v[j] # best single result + plt.subplot(6, 5, i + 1) + plt.scatter(v, f, c=hist2d(v, f, 20), cmap='viridis', alpha=.8, edgecolors='none') + plt.plot(mu, f.max(), 'k+', markersize=15) + plt.title(f'{k} = {mu:.3g}', fontdict={'size': 9}) # limit to 40 characters + if i % 5 != 0: + plt.yticks([]) + print(f'{k:>15}: {mu:.3g}') + f = evolve_csv.with_suffix('.png') # filename + plt.savefig(f, dpi=200) + plt.close() + print(f'Saved {f}') + + +def plot_results(file='path/to/results.csv', dir=''): + # Plot training results.csv. Usage: from utils.plots import *; plot_results('path/to/results.csv') + save_dir = Path(file).parent if file else Path(dir) + fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True) + ax = ax.ravel() + files = list(save_dir.glob('results*.csv')) + assert len(files), f'No results.csv files found in {save_dir.resolve()}, nothing to plot.' + for fi, f in enumerate(files): + try: + data = pd.read_csv(f) + s = [x.strip() for x in data.columns] + x = data.values[:, 0] + for i, j in enumerate([1, 2, 3, 4, 5, 8, 9, 10, 6, 7]): + y = data.values[:, j] + # y[y == 0] = np.nan # don't show zero values + ax[i].plot(x, y, marker='.', label=f.stem, linewidth=2, markersize=8) + ax[i].set_title(s[j], fontsize=12) + # if j in [8, 9, 10]: # share train and val loss y axes + # ax[i].get_shared_y_axes().join(ax[i], ax[i - 5]) + except Exception as e: + LOGGER.info(f'Warning: Plotting error for {f}: {e}') + ax[1].legend() + fig.savefig(save_dir / 'results.png', dpi=200) + plt.close() + + +def profile_idetection(start=0, stop=0, labels=(), save_dir=''): + # Plot iDetection '*.txt' per-image logs. from utils.plots import *; profile_idetection() + ax = plt.subplots(2, 4, figsize=(12, 6), tight_layout=True)[1].ravel() + s = ['Images', 'Free Storage (GB)', 'RAM Usage (GB)', 'Battery', 'dt_raw (ms)', 'dt_smooth (ms)', 'real-world FPS'] + files = list(Path(save_dir).glob('frames*.txt')) + for fi, f in enumerate(files): + try: + results = np.loadtxt(f, ndmin=2).T[:, 90:-30] # clip first and last rows + n = results.shape[1] # number of rows + x = np.arange(start, min(stop, n) if stop else n) + results = results[:, x] + t = (results[0] - results[0].min()) # set t0=0s + results[0] = x + for i, a in enumerate(ax): + if i < len(results): + label = labels[fi] if len(labels) else f.stem.replace('frames_', '') + a.plot(t, results[i], marker='.', label=label, linewidth=1, markersize=5) + a.set_title(s[i]) + a.set_xlabel('time (s)') + # if fi == len(files) - 1: + # a.set_ylim(bottom=0) + for side in ['top', 'right']: + a.spines[side].set_visible(False) + else: + a.remove() + except Exception as e: + print(f'Warning: Plotting error for {f}; {e}') + ax[1].legend() + plt.savefig(Path(save_dir) / 'idetection_profile.png', dpi=200) + + +def save_one_box(xyxy, im, file=Path('im.jpg'), gain=1.02, pad=10, square=False, BGR=False, save=True): + # Save image crop as {file} with crop size multiple {gain} and {pad} pixels. Save and/or return crop + xyxy = torch.tensor(xyxy).view(-1, 4) + b = xyxy2xywh(xyxy) # boxes + if square: + b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # attempt rectangle to square + b[:, 2:] = b[:, 2:] * gain + pad # box wh * gain + pad + xyxy = xywh2xyxy(b).long() + clip_coords(xyxy, im.shape) + crop = im[int(xyxy[0, 1]):int(xyxy[0, 3]), int(xyxy[0, 0]):int(xyxy[0, 2]), ::(1 if BGR else -1)] + if save: + file.parent.mkdir(parents=True, exist_ok=True) # make directory + f = str(increment_path(file).with_suffix('.jpg')) + # cv2.imwrite(f, crop) # https://github.com/ultralytics/yolov5/issues/7007 chroma subsampling issue + Image.fromarray(cv2.cvtColor(crop, cv2.COLOR_BGR2RGB)).save(f, quality=95, subsampling=0) + return crop diff --git a/core/vision/yolov5/utils/torch_utils.py b/core/vision/yolov5/utils/torch_utils.py new file mode 100644 index 00000000..efcacc9c --- /dev/null +++ b/core/vision/yolov5/utils/torch_utils.py @@ -0,0 +1,310 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +PyTorch utils +""" + +import math +import os +import platform +import subprocess +import time +import warnings +from contextlib import contextmanager +from copy import deepcopy + +import torch +import torch.distributed as dist +import torch.nn as nn +import torch.nn.functional as F + +from utils.general import LOGGER, file_update_date, git_describe + +try: + import thop # for FLOPs computation +except ImportError: + thop = None + +# Suppress PyTorch warnings +warnings.filterwarnings('ignore', message='User provided device_type of \'cuda\', but CUDA is not available. Disabling') + + +@contextmanager +def torch_distributed_zero_first(local_rank: int): + # Decorator to make all processes in distributed training wait for each local_master to do something + if local_rank not in [-1, 0]: + dist.barrier(device_ids=[local_rank]) + yield + if local_rank == 0: + dist.barrier(device_ids=[0]) + + +def device_count(): + # Returns number of CUDA devices available. Safe version of torch.cuda.device_count(). Only works on Linux. + assert platform.system() == 'Linux', 'device_count() function only works on Linux' + try: + cmd = 'nvidia-smi -L | wc -l' + return int(subprocess.run(cmd, shell=True, capture_output=True, check=True).stdout.decode().split()[-1]) + except Exception: + return 0 + + +def select_device(device='', batch_size=0, newline=True): + # device = 'cpu' or '0' or '0,1,2,3' + s = f'YOLOv5 🚀 {git_describe() or file_update_date()} torch {torch.__version__} ' # string + device = str(device).strip().lower().replace('cuda:', '') # to string, 'cuda:0' to '0' + cpu = device == 'cpu' + if cpu: + os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False + elif device: # non-cpu device requested + os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable - must be before assert is_available() + assert torch.cuda.is_available() and torch.cuda.device_count() >= len(device.replace(',', '')), \ + f"Invalid CUDA '--device {device}' requested, use '--device cpu' or pass valid CUDA device(s)" + + cuda = not cpu and torch.cuda.is_available() + if cuda: + devices = device.split(',') if device else '0' # range(torch.cuda.device_count()) # i.e. 0,1,6,7 + n = len(devices) # device count + if n > 1 and batch_size > 0: # check batch_size is divisible by device_count + assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}' + space = ' ' * (len(s) + 1) + for i, d in enumerate(devices): + p = torch.cuda.get_device_properties(i) + s += f"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / (1 << 20):.0f}MiB)\n" # bytes to MB + else: + s += 'CPU\n' + + if not newline: + s = s.rstrip() + LOGGER.info(s.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else s) # emoji-safe + return torch.device('cuda:0' if cuda else 'cpu') + + +def time_sync(): + # PyTorch-accurate time + if torch.cuda.is_available(): + torch.cuda.synchronize() + return time.time() + + +def profile(input, ops, n=10, device=None): + # YOLOv5 speed/memory/FLOPs profiler + # + # Usage: + # input = torch.randn(16, 3, 640, 640) + # m1 = lambda x: x * torch.sigmoid(x) + # m2 = nn.SiLU() + # profile(input, [m1, m2], n=100) # profile over 100 iterations + + results = [] + device = device or select_device() + print(f"{'Params':>12s}{'GFLOPs':>12s}{'GPU_mem (GB)':>14s}{'forward (ms)':>14s}{'backward (ms)':>14s}" + f"{'input':>24s}{'output':>24s}") + + for x in input if isinstance(input, list) else [input]: + x = x.to(device) + x.requires_grad = True + for m in ops if isinstance(ops, list) else [ops]: + m = m.to(device) if hasattr(m, 'to') else m # device + m = m.half() if hasattr(m, 'half') and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m + tf, tb, t = 0, 0, [0, 0, 0] # dt forward, backward + try: + flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # GFLOPs + except Exception: + flops = 0 + + try: + for _ in range(n): + t[0] = time_sync() + y = m(x) + t[1] = time_sync() + try: + _ = (sum(yi.sum() for yi in y) if isinstance(y, list) else y).sum().backward() + t[2] = time_sync() + except Exception: # no backward method + # print(e) # for debug + t[2] = float('nan') + tf += (t[1] - t[0]) * 1000 / n # ms per op forward + tb += (t[2] - t[1]) * 1000 / n # ms per op backward + mem = torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0 # (GB) + s_in = tuple(x.shape) if isinstance(x, torch.Tensor) else 'list' + s_out = tuple(y.shape) if isinstance(y, torch.Tensor) else 'list' + p = sum(list(x.numel() for x in m.parameters())) if isinstance(m, nn.Module) else 0 # parameters + print(f'{p:12}{flops:12.4g}{mem:>14.3f}{tf:14.4g}{tb:14.4g}{str(s_in):>24s}{str(s_out):>24s}') + results.append([p, flops, mem, tf, tb, s_in, s_out]) + except Exception as e: + print(e) + results.append(None) + torch.cuda.empty_cache() + return results + + +def is_parallel(model): + # Returns True if model is of type DP or DDP + return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel) + + +def de_parallel(model): + # De-parallelize a model: returns single-GPU model if model is of type DP or DDP + return model.module if is_parallel(model) else model + + +def initialize_weights(model): + for m in model.modules(): + t = type(m) + if t is nn.Conv2d: + pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') + elif t is nn.BatchNorm2d: + m.eps = 1e-3 + m.momentum = 0.03 + elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]: + m.inplace = True + + +def find_modules(model, mclass=nn.Conv2d): + # Finds layer indices matching module class 'mclass' + return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)] + + +def sparsity(model): + # Return global model sparsity + a, b = 0, 0 + for p in model.parameters(): + a += p.numel() + b += (p == 0).sum() + return b / a + + +def prune(model, amount=0.3): + # Prune model to requested global sparsity + import torch.nn.utils.prune as prune + print('Pruning model... ', end='') + for name, m in model.named_modules(): + if isinstance(m, nn.Conv2d): + prune.l1_unstructured(m, name='weight', amount=amount) # prune + prune.remove(m, 'weight') # make permanent + print(' %.3g global sparsity' % sparsity(model)) + + +def fuse_conv_and_bn(conv, bn): + # Fuse Conv2d() and BatchNorm2d() layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/ + fusedconv = nn.Conv2d(conv.in_channels, + conv.out_channels, + kernel_size=conv.kernel_size, + stride=conv.stride, + padding=conv.padding, + groups=conv.groups, + bias=True).requires_grad_(False).to(conv.weight.device) + + # Prepare filters + w_conv = conv.weight.clone().view(conv.out_channels, -1) + w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var))) + fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.shape)) + + # Prepare spatial bias + b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias + b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps)) + fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn) + + return fusedconv + + +def model_info(model, verbose=False, img_size=640): + # Model information. img_size may be int or list, i.e. img_size=640 or img_size=[640, 320] + n_p = sum(x.numel() for x in model.parameters()) # number parameters + n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients + if verbose: + print(f"{'layer':>5} {'name':>40} {'gradient':>9} {'parameters':>12} {'shape':>20} {'mu':>10} {'sigma':>10}") + for i, (name, p) in enumerate(model.named_parameters()): + name = name.replace('module_list.', '') + print('%5g %40s %9s %12g %20s %10.3g %10.3g' % + (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std())) + + try: # FLOPs + from thop import profile + stride = max(int(model.stride.max()), 32) if hasattr(model, 'stride') else 32 + img = torch.zeros((1, model.yaml.get('ch', 3), stride, stride), device=next(model.parameters()).device) # input + flops = profile(deepcopy(model), inputs=(img,), verbose=False)[0] / 1E9 * 2 # stride GFLOPs + img_size = img_size if isinstance(img_size, list) else [img_size, img_size] # expand if int/float + fs = ', %.1f GFLOPs' % (flops * img_size[0] / stride * img_size[1] / stride) # 640x640 GFLOPs + except (ImportError, Exception): + fs = '' + + LOGGER.info(f"Model Summary: {len(list(model.modules()))} layers, {n_p} parameters, {n_g} gradients{fs}") + + +def scale_img(img, ratio=1.0, same_shape=False, gs=32): # img(16,3,256,416) + # Scales img(bs,3,y,x) by ratio constrained to gs-multiple + if ratio == 1.0: + return img + else: + h, w = img.shape[2:] + s = (int(h * ratio), int(w * ratio)) # new size + img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize + if not same_shape: # pad/crop img + h, w = (math.ceil(x * ratio / gs) * gs for x in (h, w)) + return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean + + +def copy_attr(a, b, include=(), exclude=()): + # Copy attributes from b to a, options to only include [...] and to exclude [...] + for k, v in b.__dict__.items(): + if (len(include) and k not in include) or k.startswith('_') or k in exclude: + continue + else: + setattr(a, k, v) + + +class EarlyStopping: + # YOLOv5 simple early stopper + def __init__(self, patience=30): + self.best_fitness = 0.0 # i.e. mAP + self.best_epoch = 0 + self.patience = patience or float('inf') # epochs to wait after fitness stops improving to stop + self.possible_stop = False # possible stop may occur next epoch + + def __call__(self, epoch, fitness): + if fitness >= self.best_fitness: # >= 0 to allow for early zero-fitness stage of training + self.best_epoch = epoch + self.best_fitness = fitness + delta = epoch - self.best_epoch # epochs without improvement + self.possible_stop = delta >= (self.patience - 1) # possible stop may occur next epoch + stop = delta >= self.patience # stop training if patience exceeded + if stop: + LOGGER.info(f'Stopping training early as no improvement observed in last {self.patience} epochs. ' + f'Best results observed at epoch {self.best_epoch}, best model saved as best.pt.\n' + f'To update EarlyStopping(patience={self.patience}) pass a new patience value, ' + f'i.e. `python train.py --patience 300` or use `--patience 0` to disable EarlyStopping.') + return stop + + +class ModelEMA: + """ Updated Exponential Moving Average (EMA) from https://github.com/rwightman/pytorch-image-models + Keeps a moving average of everything in the model state_dict (parameters and buffers) + For EMA details see https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage + """ + + def __init__(self, model, decay=0.9999, tau=2000, updates=0): + # Create EMA + self.ema = deepcopy(de_parallel(model)).eval() # FP32 EMA + # if next(model.parameters()).device.type != 'cpu': + # self.ema.half() # FP16 EMA + self.updates = updates # number of EMA updates + self.decay = lambda x: decay * (1 - math.exp(-x / tau)) # decay exponential ramp (to help early epochs) + for p in self.ema.parameters(): + p.requires_grad_(False) + + def update(self, model): + # Update EMA parameters + with torch.no_grad(): + self.updates += 1 + d = self.decay(self.updates) + + msd = de_parallel(model).state_dict() # model state_dict + for k, v in self.ema.state_dict().items(): + if v.dtype.is_floating_point: + v *= d + v += (1 - d) * msd[k].detach() + + def update_attr(self, model, include=(), exclude=('process_group', 'reducer')): + # Update EMA attributes + copy_attr(self.ema, model, include, exclude) diff --git a/core/vision/yolov5/val.py b/core/vision/yolov5/val.py new file mode 100644 index 00000000..2dd2aec6 --- /dev/null +++ b/core/vision/yolov5/val.py @@ -0,0 +1,381 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Validate a trained YOLOv5 model accuracy on a custom dataset + +Usage: + $ python path/to/val.py --weights yolov5s.pt --data coco128.yaml --img 640 + +Usage - formats: + $ python path/to/val.py --weights yolov5s.pt # PyTorch + yolov5s.torchscript # TorchScript + yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn + yolov5s.xml # OpenVINO + yolov5s.engine # TensorRT + yolov5s.mlmodel # CoreML (MacOS-only) + yolov5s_saved_model # TensorFlow SavedModel + yolov5s.pb # TensorFlow GraphDef + yolov5s.tflite # TensorFlow Lite + yolov5s_edgetpu.tflite # TensorFlow Edge TPU +""" + +import argparse +import json +import os +import sys +from pathlib import Path +from threading import Thread + +import numpy as np +import torch +from tqdm import tqdm + +FILE = Path(__file__).resolve() +ROOT = FILE.parents[0] # YOLOv5 root directory +if str(ROOT) not in sys.path: + sys.path.append(str(ROOT)) # add ROOT to PATH +ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative + +from models.common import DetectMultiBackend +from utils.callbacks import Callbacks +from utils.datasets import create_dataloader +from utils.general import (LOGGER, box_iou, check_dataset, check_img_size, check_requirements, check_yaml, + coco80_to_coco91_class, colorstr, increment_path, non_max_suppression, print_args, + scale_coords, xywh2xyxy, xyxy2xywh) +from utils.metrics import ConfusionMatrix, ap_per_class +from utils.plots import output_to_target, plot_images, plot_val_study +from utils.torch_utils import select_device, time_sync + + +def save_one_txt(predn, save_conf, shape, file): + # Save one txt result + gn = torch.tensor(shape)[[1, 0, 1, 0]] # normalization gain whwh + for *xyxy, conf, cls in predn.tolist(): + xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh + line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format + with open(file, 'a') as f: + f.write(('%g ' * len(line)).rstrip() % line + '\n') + + +def save_one_json(predn, jdict, path, class_map): + # Save one JSON result {"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236} + image_id = int(path.stem) if path.stem.isnumeric() else path.stem + box = xyxy2xywh(predn[:, :4]) # xywh + box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner + for p, b in zip(predn.tolist(), box.tolist()): + jdict.append({'image_id': image_id, + 'category_id': class_map[int(p[5])], + 'bbox': [round(x, 3) for x in b], + 'score': round(p[4], 5)}) + + +def process_batch(detections, labels, iouv): + """ + Return correct predictions matrix. Both sets of boxes are in (x1, y1, x2, y2) format. + Arguments: + detections (Array[N, 6]), x1, y1, x2, y2, conf, class + labels (Array[M, 5]), class, x1, y1, x2, y2 + Returns: + correct (Array[N, 10]), for 10 IoU levels + """ + correct = torch.zeros(detections.shape[0], iouv.shape[0], dtype=torch.bool, device=iouv.device) + iou = box_iou(labels[:, 1:], detections[:, :4]) + x = torch.where((iou >= iouv[0]) & (labels[:, 0:1] == detections[:, 5])) # IoU above threshold and classes match + if x[0].shape[0]: + matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy() # [label, detection, iou] + if x[0].shape[0] > 1: + matches = matches[matches[:, 2].argsort()[::-1]] + matches = matches[np.unique(matches[:, 1], return_index=True)[1]] + # matches = matches[matches[:, 2].argsort()[::-1]] + matches = matches[np.unique(matches[:, 0], return_index=True)[1]] + matches = torch.from_numpy(matches).to(iouv.device) + correct[matches[:, 1].long()] = matches[:, 2:3] >= iouv + return correct + + +@torch.no_grad() +def run(data, + weights=None, # model.pt path(s) + batch_size=32, # batch size + imgsz=640, # inference size (pixels) + conf_thres=0.001, # confidence threshold + iou_thres=0.6, # NMS IoU threshold + task='val', # train, val, test, speed or study + device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu + workers=8, # max dataloader workers (per RANK in DDP mode) + single_cls=False, # treat as single-class dataset + augment=False, # augmented inference + verbose=False, # verbose output + save_txt=False, # save results to *.txt + save_hybrid=False, # save label+prediction hybrid results to *.txt + save_conf=False, # save confidences in --save-txt labels + save_json=False, # save a COCO-JSON results file + project=ROOT / 'runs/val', # save to project/name + name='exp', # save to project/name + exist_ok=False, # existing project/name ok, do not increment + half=True, # use FP16 half-precision inference + dnn=False, # use OpenCV DNN for ONNX inference + model=None, + dataloader=None, + save_dir=Path(''), + plots=True, + callbacks=Callbacks(), + compute_loss=None, + ): + # Initialize/load model and set device + training = model is not None + if training: # called by train.py + device, pt, jit, engine = next(model.parameters()).device, True, False, False # get model device, PyTorch model + half &= device.type != 'cpu' # half precision only supported on CUDA + model.half() if half else model.float() + else: # called directly + device = select_device(device, batch_size=batch_size) + + # Directories + save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run + (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir + + # Load model + model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half) + stride, pt, jit, engine = model.stride, model.pt, model.jit, model.engine + imgsz = check_img_size(imgsz, s=stride) # check image size + half = model.fp16 # FP16 supported on limited backends with CUDA + if engine: + batch_size = model.batch_size + else: + device = model.device + if not (pt or jit): + batch_size = 1 # export.py models default to batch-size 1 + LOGGER.info(f'Forcing --batch-size 1 square inference (1,3,{imgsz},{imgsz}) for non-PyTorch models') + + # Data + data = check_dataset(data) # check + + # Configure + model.eval() + cuda = device.type != 'cpu' + is_coco = isinstance(data.get('val'), str) and data['val'].endswith('coco/val2017.txt') # COCO dataset + nc = 1 if single_cls else int(data['nc']) # number of classes + iouv = torch.linspace(0.5, 0.95, 10, device=device) # iou vector for mAP@0.5:0.95 + niou = iouv.numel() + + # Dataloader + if not training: + model.warmup(imgsz=(1 if pt else batch_size, 3, imgsz, imgsz)) # warmup + pad = 0.0 if task in ('speed', 'benchmark') else 0.5 + rect = False if task == 'benchmark' else pt # square inference for benchmarks + task = task if task in ('train', 'val', 'test') else 'val' # path to train/val/test images + dataloader = create_dataloader(data[task], imgsz, batch_size, stride, single_cls, pad=pad, rect=rect, + workers=workers, prefix=colorstr(f'{task}: '))[0] + + seen = 0 + confusion_matrix = ConfusionMatrix(nc=nc) + names = {k: v for k, v in enumerate(model.names if hasattr(model, 'names') else model.module.names)} + class_map = coco80_to_coco91_class() if is_coco else list(range(1000)) + s = ('%20s' + '%11s' * 6) % ('Class', 'Images', 'Labels', 'P', 'R', 'mAP@.5', 'mAP@.5:.95') + dt, p, r, f1, mp, mr, map50, map = [0.0, 0.0, 0.0], 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 + loss = torch.zeros(3, device=device) + jdict, stats, ap, ap_class = [], [], [], [] + pbar = tqdm(dataloader, desc=s, bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}') # progress bar + for batch_i, (im, targets, paths, shapes) in enumerate(pbar): + t1 = time_sync() + if cuda: + im = im.to(device, non_blocking=True) + targets = targets.to(device) + im = im.half() if half else im.float() # uint8 to fp16/32 + im /= 255 # 0 - 255 to 0.0 - 1.0 + nb, _, height, width = im.shape # batch size, channels, height, width + t2 = time_sync() + dt[0] += t2 - t1 + + # Inference + out, train_out = model(im) if training else model(im, augment=augment, val=True) # inference, loss outputs + dt[1] += time_sync() - t2 + + # Loss + if compute_loss: + loss += compute_loss([x.float() for x in train_out], targets)[1] # box, obj, cls + + # NMS + targets[:, 2:] *= torch.tensor((width, height, width, height), device=device) # to pixels + lb = [targets[targets[:, 0] == i, 1:] for i in range(nb)] if save_hybrid else [] # for autolabelling + t3 = time_sync() + out = non_max_suppression(out, conf_thres, iou_thres, labels=lb, multi_label=True, agnostic=single_cls) + dt[2] += time_sync() - t3 + + # Metrics + for si, pred in enumerate(out): + labels = targets[targets[:, 0] == si, 1:] + nl = len(labels) + tcls = labels[:, 0].tolist() if nl else [] # target class + path, shape = Path(paths[si]), shapes[si][0] + seen += 1 + + if len(pred) == 0: + if nl: + stats.append((torch.zeros(0, niou, dtype=torch.bool), torch.Tensor(), torch.Tensor(), tcls)) + continue + + # Predictions + if single_cls: + pred[:, 5] = 0 + predn = pred.clone() + scale_coords(im[si].shape[1:], predn[:, :4], shape, shapes[si][1]) # native-space pred + + # Evaluate + if nl: + tbox = xywh2xyxy(labels[:, 1:5]) # target boxes + scale_coords(im[si].shape[1:], tbox, shape, shapes[si][1]) # native-space labels + labelsn = torch.cat((labels[:, 0:1], tbox), 1) # native-space labels + correct = process_batch(predn, labelsn, iouv) + if plots: + confusion_matrix.process_batch(predn, labelsn) + else: + correct = torch.zeros(pred.shape[0], niou, dtype=torch.bool) + stats.append((correct.cpu(), pred[:, 4].cpu(), pred[:, 5].cpu(), tcls)) # (correct, conf, pcls, tcls) + + # Save/log + if save_txt: + save_one_txt(predn, save_conf, shape, file=save_dir / 'labels' / (path.stem + '.txt')) + if save_json: + save_one_json(predn, jdict, path, class_map) # append to COCO-JSON dictionary + callbacks.run('on_val_image_end', pred, predn, path, names, im[si]) + + # Plot images + if plots and batch_i < 3: + f = save_dir / f'val_batch{batch_i}_labels.jpg' # labels + Thread(target=plot_images, args=(im, targets, paths, f, names), daemon=True).start() + f = save_dir / f'val_batch{batch_i}_pred.jpg' # predictions + Thread(target=plot_images, args=(im, output_to_target(out), paths, f, names), daemon=True).start() + + # Compute metrics + stats = [np.concatenate(x, 0) for x in zip(*stats)] # to numpy + if len(stats) and stats[0].any(): + tp, fp, p, r, f1, ap, ap_class = ap_per_class(*stats, plot=plots, save_dir=save_dir, names=names) + ap50, ap = ap[:, 0], ap.mean(1) # AP@0.5, AP@0.5:0.95 + mp, mr, map50, map = p.mean(), r.mean(), ap50.mean(), ap.mean() + nt = np.bincount(stats[3].astype(np.int64), minlength=nc) # number of targets per class + else: + nt = torch.zeros(1) + + # Print results + pf = '%20s' + '%11i' * 2 + '%11.3g' * 4 # print format + LOGGER.info(pf % ('all', seen, nt.sum(), mp, mr, map50, map)) + + # Print results per class + if (verbose or (nc < 50 and not training)) and nc > 1 and len(stats): + for i, c in enumerate(ap_class): + LOGGER.info(pf % (names[c], seen, nt[c], p[i], r[i], ap50[i], ap[i])) + + # Print speeds + t = tuple(x / seen * 1E3 for x in dt) # speeds per image + if not training: + shape = (batch_size, 3, imgsz, imgsz) + LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {shape}' % t) + + # Plots + if plots: + confusion_matrix.plot(save_dir=save_dir, names=list(names.values())) + callbacks.run('on_val_end') + + # Save JSON + if save_json and len(jdict): + w = Path(weights[0] if isinstance(weights, list) else weights).stem if weights is not None else '' # weights + anno_json = str(Path(data.get('path', '../coco')) / 'annotations/instances_val2017.json') # annotations json + pred_json = str(save_dir / f"{w}_predictions.json") # predictions json + LOGGER.info(f'\nEvaluating pycocotools mAP... saving {pred_json}...') + with open(pred_json, 'w') as f: + json.dump(jdict, f) + + try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb + check_requirements(['pycocotools']) + from pycocotools.coco import COCO + from pycocotools.cocoeval import COCOeval + + anno = COCO(anno_json) # init annotations api + pred = anno.loadRes(pred_json) # init predictions api + eval = COCOeval(anno, pred, 'bbox') + if is_coco: + eval.params.imgIds = [int(Path(x).stem) for x in dataloader.dataset.im_files] # image IDs to evaluate + eval.evaluate() + eval.accumulate() + eval.summarize() + map, map50 = eval.stats[:2] # update results (mAP@0.5:0.95, mAP@0.5) + except Exception as e: + LOGGER.info(f'pycocotools unable to run: {e}') + + # Return results + model.float() # for training + if not training: + s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else '' + LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}") + maps = np.zeros(nc) + map + for i, c in enumerate(ap_class): + maps[c] = ap[i] + return (mp, mr, map50, map, *(loss.cpu() / len(dataloader)).tolist()), maps, t + + +def parse_opt(): + parser = argparse.ArgumentParser() + parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path') + parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model.pt path(s)') + parser.add_argument('--batch-size', type=int, default=32, help='batch size') + parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='inference size (pixels)') + parser.add_argument('--conf-thres', type=float, default=0.001, help='confidence threshold') + parser.add_argument('--iou-thres', type=float, default=0.6, help='NMS IoU threshold') + parser.add_argument('--task', default='val', help='train, val, test, speed or study') + parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') + parser.add_argument('--workers', type=int, default=8, help='max dataloader workers (per RANK in DDP mode)') + parser.add_argument('--single-cls', action='store_true', help='treat as single-class dataset') + parser.add_argument('--augment', action='store_true', help='augmented inference') + parser.add_argument('--verbose', action='store_true', help='report mAP by class') + parser.add_argument('--save-txt', action='store_true', help='save results to *.txt') + parser.add_argument('--save-hybrid', action='store_true', help='save label+prediction hybrid results to *.txt') + parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels') + parser.add_argument('--save-json', action='store_true', help='save a COCO-JSON results file') + parser.add_argument('--project', default=ROOT / 'runs/val', help='save to project/name') + parser.add_argument('--name', default='exp', help='save to project/name') + parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment') + parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference') + parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference') + opt = parser.parse_args() + opt.data = check_yaml(opt.data) # check YAML + opt.save_json |= opt.data.endswith('coco.yaml') + opt.save_txt |= opt.save_hybrid + print_args(FILE.stem, opt) + return opt + + +def main(opt): + check_requirements(requirements=ROOT / 'requirements.txt', exclude=('tensorboard', 'thop')) + + if opt.task in ('train', 'val', 'test'): # run normally + if opt.conf_thres > 0.001: # https://github.com/ultralytics/yolov5/issues/1466 + LOGGER.info(f'WARNING: confidence threshold {opt.conf_thres} >> 0.001 will produce invalid mAP values.') + run(**vars(opt)) + + else: + weights = opt.weights if isinstance(opt.weights, list) else [opt.weights] + opt.half = True # FP16 for fastest results + if opt.task == 'speed': # speed benchmarks + # python val.py --task speed --data coco.yaml --batch 1 --weights yolov5n.pt yolov5s.pt... + opt.conf_thres, opt.iou_thres, opt.save_json = 0.25, 0.45, False + for opt.weights in weights: + run(**vars(opt), plots=False) + + elif opt.task == 'study': # speed vs mAP benchmarks + # python val.py --task study --data coco.yaml --iou 0.7 --weights yolov5n.pt yolov5s.pt... + for opt.weights in weights: + f = f'study_{Path(opt.data).stem}_{Path(opt.weights).stem}.txt' # filename to save to + x, y = list(range(256, 1536 + 128, 128)), [] # x axis (image sizes), y axis + for opt.imgsz in x: # img-size + LOGGER.info(f'\nRunning {f} --imgsz {opt.imgsz}...') + r, _, t = run(**vars(opt), plots=False) + y.append(r + t) # results and times + np.savetxt(f, y, fmt='%10.4g') # save + os.system('zip -r study.zip study_*.txt') + plot_val_study(x=x) # plot + + +if __name__ == "__main__": + opt = parse_opt() + main(opt) diff --git a/core/vision/zed_handler.py b/core/vision/zed_handler.py index 1a51b1ad..cac84686 100644 --- a/core/vision/zed_handler.py +++ b/core/vision/zed_handler.py @@ -12,6 +12,8 @@ from core.vision import Camera import threading import time +import numpy as np +from threading import Lock class ZedHandler(Camera): @@ -25,24 +27,32 @@ def __init__(self): self.feed_handler = feed_handler self.logger = logging.getLogger(__name__) + # Resolution of point cloud. + self.cloud_res = sl.Resolution() + self.cloud_res.width = 1920 + self.cloud_res.height = 1080 + # Define the camera resolutions - self.depth_res_x = 640 - self.depth_res_y = 360 - self.reg_res_x = 1280 - self.reg_res_y = 720 - self.hfov = 85 + self.point_cloud_res_x = self.cloud_res.width + self.point_cloud_res_y = self.cloud_res.height + self.depth_res_x = 1920 + self.depth_res_y = 1080 + self.reg_res_x = 1920 + self.reg_res_y = 1080 + self.hfov = 110 # Define the desired runtime FPS - self.fps = 30 + self.fps = 60 # Set configuration parameters self.input_type = sl.InputType() self.init = sl.InitParameters(input_t=self.input_type) - self.init.camera_resolution = sl.RESOLUTION.HD720 + self.init.camera_resolution = sl.RESOLUTION.HD1080 self.init.depth_mode = sl.DEPTH_MODE.ULTRA self.init.coordinate_units = sl.UNIT.MILLIMETER self.init.camera_fps = self.fps - self.init.depth_minimum_distance = 1 + self.init.depth_minimum_distance = 0.0 + self.init.depth_maximum_distance = 40000.0 # Open the camera err = self.zed.open(self.init) @@ -51,6 +61,11 @@ def __init__(self): self.zed.close() exit(1) + # Get camera params and sensors. + self.obj_runtime_param = sl.ObjectDetectionRuntimeParameters() + self.runtime_params = sl.RuntimeParameters() + self.sensors_data = sl.SensorsData() + # Add the desired feeds to be recorded (not streamed) self.feed_handler.add_feed(10, "regular", save_video=True, stream_video=False) self.feed_handler.add_feed(11, "depth", save_video=True, stream_video=False) @@ -64,6 +79,8 @@ def __init__(self): self.thread = threading.Thread(target=self.frame_grabber, args=()) + self.lock = Lock() + # Should this be a generator or a thread? Generator might help cuz I could schedule this in the ASYNC calls def frame_grabber(self): """ @@ -75,8 +92,6 @@ def frame_grabber(self): self.image_size = self.zed.get_camera_information().camera_resolution self.depth_size = self.zed.get_camera_information().camera_resolution - self.depth_size.width = self.depth_size.width / 2 - self.depth_size.height = self.depth_size.height / 2 # Declare your sl.Mat matrices image_zed = sl.Mat(self.image_size.width, self.image_size.height, sl.MAT_TYPE.U8_C4) @@ -84,13 +99,13 @@ def frame_grabber(self): self.zed.enable_positional_tracking() # Set runtime parameters after opening the camera - runtime = sl.RuntimeParameters() - runtime.sensing_mode = sl.SENSING_MODE.STANDARD - runtime.confidence_threshold = 50 - runtime.measure3D_reference_frame = sl.REFERENCE_FRAME.CAMERA + self.runtime_params = sl.RuntimeParameters() + self.runtime_params.sensing_mode = sl.SENSING_MODE.STANDARD + self.runtime_params.confidence_threshold = 50 + self.runtime_params.measure3D_reference_frame = sl.REFERENCE_FRAME.CAMERA while not self._stop.is_set(): - err = self.zed.grab(runtime) + err = self.zed.grab(self.runtime_params) if err == sl.ERROR_CODE.SUCCESS: # Grab images, and grab the data as opencv/numpy matrix self.zed.retrieve_image(image_zed, sl.VIEW.LEFT, sl.MEM.CPU, self.image_size) @@ -101,7 +116,6 @@ def frame_grabber(self): # Now let the feed_handler stream/save the frames self.feed_handler.handle_frame("regular", self.reg_img) self.feed_handler.handle_frame("depth", self.depth_img) - time.sleep(1 / self.fps) def grab_regular(self): """ @@ -125,7 +139,7 @@ def grab_point_cloud(self): Returns 3D point cloud data captured with ZED """ point_cloud = sl.Mat() - self.zed.retrieve_measure(point_cloud, sl.MEASURE.XYZ, sl.MEM.CPU, self.depth_size) + self.zed.retrieve_measure(point_cloud, sl.MEASURE.XYZRGBA, sl.MEM.CPU, self.cloud_res) return point_cloud def get_floor(self): @@ -145,12 +159,141 @@ def get_info(self): info = self.zed.get_camera_information().calibration_parameters return info - def get_pose(self, pose): + def get_general_info(self): + """ + Returns all the details of the zed camera. + """ + info = self.zed.get_camera_information() + return info + + def get_config(self): + """ + Returns the zed camera config. + """ + config = self.zed.get_camera_information().camera_configuration + return config + + def enable_pose_tracking(self, static=False): + """ + Sets up the camera for constant positional tracking. + """ + positional_tracking_parameters = sl.PositionalTrackingParameters() + # If the camera is static, this will cause it to have better performances and boxes will stick to the ground better. + positional_tracking_parameters.set_as_static = False + self.zed.enable_positional_tracking(positional_tracking_parameters) + + def enable_camera_detection_module(self, enable_tracking=True): + """ + Sets up the camera to load a custom object detection module. + """ + obj_param = sl.ObjectDetectionParameters() + obj_param.detection_model = sl.DETECTION_MODEL.CUSTOM_BOX_OBJECTS + obj_param.enable_tracking = True + self.zed.enable_object_detection(obj_param) + return obj_param + + def ingest_box_objects(self, detections): + """ + Takes sl.CustomBoxObjectData objects and feed them to the zed. + """ + self.zed.ingest_custom_box_objects(detections) + + def get_objects(self): + """ + Get the list of objects from the zed cam. + """ + objects = sl.Objects() + if self.zed.grab(self.runtime_params) == sl.ERROR_CODE.SUCCESS: + self.zed.retrieve_objects(objects, self.obj_runtime_param) + return objects + + def get_pose(self): """ Returns the estimated pose of the ZED camera """ - tracking_state = self.zed.get_position(pose) - return tracking_state + # Get pose from ZED camera. + pose = sl.Pose() + status = self.zed.get_position(pose, sl.REFERENCE_FRAME.WORLD) + + # Unpack pose values. + translation = sl.Translation() + tx = round(pose.get_translation(translation).get()[0], 3) / 1000 + ty = round(pose.get_translation(translation).get()[1], 3) / 1000 + tz = round(pose.get_translation(translation).get()[2], 3) / 1000 + # Retrieve only frame synchronized data. + zed_imu_pose = sl.Transform() + self.zed.get_sensors_data(self.sensors_data, sl.TIME_REFERENCE.IMAGE) + ox, oy, oz = np.rad2deg(self.sensors_data.get_imu_data().get_pose(zed_imu_pose).get_orientation().get_rotation_matrix().get_euler_angles()) + + # Wrap heading. + if oy < 0: + oy = 360 + oy + + return tx, ty, tz, ox, oy, oz + + def set_pose(self, x, y, z, roll, pitch, yaw): + """ + This method will set the zed translation and rotation to the given values. + You must pass in a x, y, z, roll, pitch, yaw. PAY ATTENTION TO THE ZED COORDINATE FRAME. + Z - FORWARD + Y - DOWN + X - RIGHT + + :param x: The new x position in meters to set the camera to. + :param y: The new y position in meters to set the camera to. + :param z: The new z position in meters to set the camera to. + :param roll: The new roll angle in degrees to set the camera to. + :param pitch: The new pitch angle in degrees to set the camera to. + :param yaw: The new yaw angle in degrees to set the camera to. + """ + # Create zed translation object. + translation_vector = sl.Translation() + translation_vector.init_vector(x * 1000, y * 1000, z * 1000) + # Create zed rotation object. + rotation_angles = sl.Rotation() + rotation_angles.set_euler_angles(roll, pitch, yaw, radian=False) + # Sets the Matrix3f to identity. + # rotation_angles.set_identity() + # Build transform. + new_transform = sl.Transform() + new_transform.init_rotation_translation(rotation_angles, translation_vector) + + # Reset positional tracking. + self.zed.reset_positional_tracking(new_transform) + + def reset_pose(self): + """ + This method will set the zed translation and rotation back to zero. + """ + # Create zed translation object. + translation_vector = sl.Translation() + translation_vector.init_vector(0, 0, 0) + # Create zed rotation object. + rotation_angles = sl.Rotation() + rotation_angles.set_euler_angles(0, 0, 0, radian=False) + # Sets the Matrix3f to identity. + rotation_angles.set_identity() + # Build transform. + new_transform = sl.Transform() + new_transform.init_rotation_translation(rotation_angles, translation_vector) + + # Reset positional tracking. + self.zed.reset_positional_tracking(new_transform) + + def get_compass_heading(self): + """ + Returns the estimated compass heading of the ZED camera. ZED CAMERA MUST BE CALIBRATED FOR THIS TO BE ACCURATE. + CHECK ZED DOCS ONLINE. + """ + # Retrieve only frame synchronized data. + self.zed.get_sensors_data(self.sensors_data, sl.TIME_REFERENCE.IMAGE) + # Retrieve calibrated magnetic field + heading = self.sensors_data.get_magnetometer_data().magnetic_heading + # Remap the -180-180 output to 0-360, clockwise positive. + if heading < 0: + heading = 360 + heading + + return heading def start(self): """ @@ -177,4 +320,4 @@ def close(self): # Close the feed handler as well self.feed_handler.close() - self.logger.info("Closing ZED capture") \ No newline at end of file + self.logger.info("Closing ZED capture") diff --git a/core/waypoints.py b/core/waypoints.py index 9c3b6fdd..f62b50e8 100644 --- a/core/waypoints.py +++ b/core/waypoints.py @@ -85,15 +85,15 @@ def add_position_waypoint(self, packet) -> None: self.waypoints.append(("POSITION", waypoint)) self.logger.info(f"Added Position Waypoint: lat ({latitude}), lon({longitude})") - def clear_waypoints(self, packet) -> None: + def clear_waypoints(self, packet="") -> None: """ Clears the deque of waypoints :param packet: :return: None """ - self.waypoints.clear() + self.gps_data: GPSData = None self.logger.info("Cleared all waypoints") def get_waypoint(self) -> GPSData: @@ -138,7 +138,7 @@ def is_empty(self) -> bool: :return: If waypoints is empty """ - if self.waypoints: + if len(self.waypoints) > 0: return False else: return True diff --git a/docs/state_machine_matrix.csv b/docs/state_machine_matrix.csv index 25bfeece..b0c72e52 100644 --- a/docs/state_machine_matrix.csv +++ b/docs/state_machine_matrix.csv @@ -1,5 +1,5 @@ Events,Idle,Navigating,SearchPattern,ApproachingMarker,Avoidance, ApproachingGate -START,Navigating,Navigating,SearchPattern,ApproachingMarker,Avoidance, ApproachingGate +START,Reversing,Navigating,SearchPattern,ApproachingMarker,Avoidance, ApproachingGate REACHED_GPS_COORDINATE,,SearchPattern,,,, MARKER_SEEN,,,ApproachingMarker,,, GATE_SEEN,,,ApproachingGate,,, diff --git a/example/ar_cascades.py b/example/ar_cascades.py index 030b5eee..7e93fc79 100644 --- a/example/ar_cascades.py +++ b/example/ar_cascades.py @@ -28,9 +28,6 @@ def main() -> None: core.vision.feed_handler.handle_frame("artag", reg_img) - # Sleep so we only process around when we expect a new frame - time.sleep(1 / 30) - if __name__ == "__main__": # Run main() diff --git a/example/obstacle_avoidance_example.py b/example/obstacle_avoidance_example.py index 77a1bf5a..29d9e5ee 100644 --- a/example/obstacle_avoidance_example.py +++ b/example/obstacle_avoidance_example.py @@ -9,6 +9,7 @@ import time import algorithms import core +import core.constants import logging import interfaces import algorithms.heading_hold @@ -52,7 +53,7 @@ def main() -> None: == core.ApproachState.APPROACHING ): left, right = algorithms.gps_navigate.calculate_move( - core.Coordinate(new_lat, new_lon), interfaces.nav_board.location(), previous_loc, 250 + core.Coordinate(new_lat, new_lon), interfaces.nav_board.location(), previous_loc, core.MAX_DRIVE_POWER ) logger.debug(f"Navigating: Driving at ({left}, {right})") interfaces.drive_board.send_drive(left, right) diff --git a/interfaces/drive_board.py b/interfaces/drive_board.py index 65257c7c..5e03395e 100644 --- a/interfaces/drive_board.py +++ b/interfaces/drive_board.py @@ -19,10 +19,16 @@ class DriveBoard: """ def __init__(self): + # Create class member variables. self._targetSpdLeft: int = 0 self._targetSpdRight: int = 0 self.logger: logging.Logger = logging.getLogger(__name__) + # Set rovecomm callback for setting max drive speed. + core.rovecomm_node.set_callback( + core.manifest["Autonomy"]["Commands"]["SetMaxSpeed"]["dataId"], self.set_max_speed + ) + def calculate_move(self, speed: float, angle: float) -> Tuple[int, int]: """ Calculates the drives speeds given the vector (speed, angle) @@ -57,15 +63,37 @@ def send_drive(self, target_left: int, target_right: int) -> None: # Write a drive packet (UDP) core.rovecomm_node.write( core.RoveCommPacket( - core.manifest["Drive"]["Commands"]["DriveLeftRight"]["dataId"], - "h", - (target_left, target_right), - core.manifest["Drive"]["Ip"], + core.manifest["Core"]["Commands"]["DriveLeftRight"]["dataId"], + "f", + (target_left / 1000, target_right / 1000), + core.manifest["Core"]["Ip"], core.UDP_OUTGOING_PORT, ), False, ) + def set_max_speed(self, packet) -> None: + """ + This method is called whenever a SetMaxSpeed packet is sent from basestation. + + :param packet: + :return: None + """ + # Get data out of packet. + max_speed = packet.data + + # Do some checking. + if max_speed < 0: + max_speed = 0 + elif max_speed > 1000: + max_speed = 1000 + + # Set max speed constant. + core.constants.MAX_DRIVE_POWER = max_speed + + # Print logging info. + self.logger.info(f"Autonomy set max drive power to {max_speed}") + def stop(self) -> None: """ Sends a rovecomm packet with a 0, 0 to indicate full stop @@ -74,10 +102,10 @@ def stop(self) -> None: # Write a drive packet of 0s (to stop) core.rovecomm_node.write( core.RoveCommPacket( - core.manifest["Drive"]["Commands"]["DriveLeftRight"]["dataId"], - "h", - (0, 0), - core.manifest["Drive"]["Ip"], + core.manifest["Core"]["Commands"]["DriveLeftRight"]["dataId"], + "f", + (0.0, 0.0), + core.manifest["Core"]["Ip"], core.UDP_OUTGOING_PORT, ), False, diff --git a/interfaces/multimedia_board.py b/interfaces/multimedia_board.py index ca895f54..12021c74 100644 --- a/interfaces/multimedia_board.py +++ b/interfaces/multimedia_board.py @@ -28,10 +28,10 @@ def send_lighting_state(self, state): # Write a lighting state packet (TCP) core.rovecomm_node.write( core.RoveCommPacket( - core.manifest["Multimedia"]["Commands"]["StateDisplay"]["dataId"], + core.manifest["Core"]["Commands"]["StateDisplay"]["dataId"], "B", (state,), - core.manifest["Multimedia"]["Ip"], + core.manifest["Core"]["Ip"], core.UDP_OUTGOING_PORT, ), False, @@ -46,10 +46,10 @@ def send_rgb(self, rgb): # Write a lighting rgb packet (TCP) core.rovecomm_node.write( core.RoveCommPacket( - core.manifest["Multimedia"]["Commands"]["LEDRGB"]["dataId"], + core.manifest["Core"]["Commands"]["LEDRGB"]["dataId"], "B", rgb, - core.manifest["Multimedia"]["Ip"], + core.manifest["Core"]["Ip"], core.UDP_OUTGOING_PORT, ), True, diff --git a/interfaces/nav_board.py b/interfaces/nav_board.py index b046dbf9..9b958959 100644 --- a/interfaces/nav_board.py +++ b/interfaces/nav_board.py @@ -10,6 +10,7 @@ from core.constants import Coordinate import time import logging +import utm class NavBoard: @@ -23,10 +24,16 @@ def __init__(self): self._pitch: float = 0 self._roll: float = 0 self._heading: float = 0 + self._zed_heading: float = 0 self._location: Coordinate = Coordinate(0, 0) self._distToGround: int = 0 self._lidarQuality = 0 # int 5 for brand-new data, counts down 1 every 50ms, should never go below 3. self._lastTime = time.time() + self._accur_horizontal = -1 + self._accur_vertical = -1 + self._accur_heading = -1 + self._start_UTM = None + self._heading_adjust = 0 # Set up RoveComm and Logger self.logger = logging.getLogger(__name__) @@ -36,13 +43,15 @@ def __init__(self): # set up appropriate callbacks so we can store data as we receive it from NavBoard core.rovecomm_node.set_callback(core.manifest["Nav"]["Telemetry"]["IMUData"]["dataId"], self.process_imu_data) core.rovecomm_node.set_callback(core.manifest["Nav"]["Telemetry"]["GPSLatLon"]["dataId"], self.process_gps_data) + core.rovecomm_node.set_callback( + core.manifest["Nav"]["Telemetry"]["AccuracyData"]["dataId"], self.process_accuracy_data + ) def process_imu_data(self, packet): """ Process IMU Data :param packet: pitch, heading, and roll included """ - self._pitch, self._heading, self._roll = packet.data self.logger.debug(f"Incoming IMU data: ({self._pitch}, {self._heading}, {self._roll})") @@ -51,21 +60,158 @@ def process_gps_data(self, packet) -> None: Process GPS Data :param packet: lat and lon included """ - # The GPS sends data as two int32_t's lat, lon = packet.data self.logger.debug(f"Incoming GPS data: ({lat}, {lon})") self._lastTime = time.time() self._location = Coordinate(lat, lon) + def process_accuracy_data(self, packet) -> None: + """ + Process Accuracy Data + :param packet: lat and lon included + """ + # The GPS sends data as three floats. + self._accur_horizontal, self._accur_vertical, self._accur_heading = packet.data + def pitch(self) -> float: - return self._pitch + # Check if ZED relative positioning is turned on. + if core.vision.RELATIVE_POSITIONING: + # Get heading from the zed camera. + pitch = core.vision.camera_handler.get_pose()[0] + + # Wrap heading. + if pitch < 0: + pitch = 360 + pitch + else: + # Return reported heading from nav board. + pitch = self._pitch + + return pitch def roll(self) -> float: - return self._roll + # Check if ZED relative positioning is turned on. + if core.vision.RELATIVE_POSITIONING: + # Get heading from the zed camera. + roll = core.vision.camera_handler.get_pose()[2] + + # Wrap heading. + if roll < 0: + roll = 360 + roll + else: + # Return reported heading from nav board. + roll = self._roll + + return roll + + def heading(self, force_absolute=False) -> float: + # Check if ZED relative positioning is turned on. + if core.vision.RELATIVE_POSITIONING and not force_absolute: + # Get heading from the zed camera IMU. + heading = core.vision.camera_handler.get_pose()[4] + else: + # Return reported heading from nav board. + heading = self._heading + """ + OLD + """ + # # Check if ZED relative positioning is turned on. + # if core.vision.RELATIVE_POSITIONING and not force_absolute: + # # Get heading from the zed camera. + # heading = (core.vision.camera_handler.get_pose()[4] + self._heading_adjust) % 360 + # else: + # # Return reported heading from nav board. + # heading = self._heading + + return heading + + def location(self, force_absolute=False) -> Coordinate: + # Check if ZED relative positioning is turned on. + if core.vision.RELATIVE_POSITIONING and not force_absolute: + # Check if we already set are absolute start position. + if self._start_UTM is None: + # Get current GPS. + self._start_UTM = list(utm.from_latlon(self._location[0], self._location[1])) + # Get the current roll and yaw of camera. x and z axis. These need to be retained otherwise camera positional tracking will be off. + _, _, _, roll, _, yaw = location = core.vision.camera_handler.get_pose() + # Align set pose to current gps location and heading. + core.vision.camera_handler.set_pose(0, 0, 0, roll, self._heading, yaw) + + # Get current pose of camera. + location = core.vision.camera_handler.get_pose() + # Get zed x, y location. Longitude is actually Z in zed axis because of default coordinate frame. + x, y = self._start_UTM[0] + location[2], self._start_UTM[1] + location[0] + # Convert back to GPS. Last two params are UTM zone. + gps_current = utm.to_latlon(*(x, y, self._start_UTM[2], self._start_UTM[3])) + gps_current = Coordinate(gps_current[0], gps_current[1]) + + """ + OLD + """ + # location = core.vision.camera_handler.get_pose() + + # # Get zed x, y location. Actually Z. + # x, y = location[0], location[2] + + # # Check if we already set are absolute start position. + # if self._start_UTM is None: + # # Get current GPS. + # self._start_UTM = list(utm.from_latlon(self._location[0], self._location[1])) + # # Align set pose to current gps location and heading. + + # # Add Start UTM coords to ZED position. + # x, y = x + self._start_UTM[0], y + self._start_UTM[1] + # # Convert back to GPS. Last two params are UTM zone. + # gps_current = utm.to_latlon(*(x, y, self._start_UTM[2], self._start_UTM[3])) + # gps_current = Coordinate(gps_current[0], gps_current[1]) + else: + # Get reported GPS location from nav board. + gps_current = self._location + return gps_current + + def accuracy(self) -> float: + # Return accuracy data. + return self._accur_horizontal, self._accur_vertical, self._accur_heading + + def realign(self) -> None: + """ + Realigns the relative positioning to the absolute position. + """ + # Get current GPS. + self._start_UTM = list(utm.from_latlon(self._location[0], self._location[1])) + # Get the current roll and yaw of camera. x and z axis. These need to be retained otherwise camera positional tracking will be off. + _, _, _, roll, _, yaw = location = core.vision.camera_handler.get_pose() + # Align set pose to current gps location and heading. + core.vision.camera_handler.set_pose(0, 0, 0, roll, self._heading, yaw) + + """ + OLD + """ + # if self._start_UTM is None: + # # Get current GPS. + # self._start_UTM = list(utm.from_latlon(self._location[0], self._location[1])) + # else: + # # Get curremt relative in UTM. + # location = core.vision.camera_handler.get_pose() + # # Get zed x, y location. + # x, y = location[0], location[2] + + # # Get current position in UTM. + # current_UTM = utm.from_latlon(self._location[0], self._location[1]) - def heading(self) -> float: - return self._heading + # # Calculate offset. + # offset_lat, offset_long = current_UTM[0] - (self._start_UTM[0] + x), current_UTM[1] - ( + # self._start_UTM[1] + y + # ) + # # Realign zed offset. + # self._start_UTM[0] = self._start_UTM[0] + offset_lat + # self._start_UTM[1] = self._start_UTM[1] + offset_long - def location(self) -> Coordinate: - return self._location + # Realign heading. + # # Check if the ZED absolute magnotometer heading is turned on. + # if core.vision.ZED_MAGNETOMETER: + # self._zed_heading = core.vision.camera_handler.get_compass_heading() + # self._heading_adjust = self._zed_heading - core.vision.camera_handler.get_pose()[4] + # else: + # self._diffGPS_heading = self._heading + # self._heading_adjust = self._diffGPS_heading - core.vision.camera_handler.get_pose()[4] diff --git a/resources/yolo_models/2022-0304/F1_curve.png b/resources/yolo_models/2022-0304/F1_curve.png new file mode 100644 index 00000000..10ee799a Binary files /dev/null and b/resources/yolo_models/2022-0304/F1_curve.png differ diff --git a/resources/yolo_models/2022-0304/PR_curve.png b/resources/yolo_models/2022-0304/PR_curve.png new file mode 100644 index 00000000..6755d0ad Binary files /dev/null and b/resources/yolo_models/2022-0304/PR_curve.png differ diff --git a/resources/yolo_models/2022-0304/P_curve.png b/resources/yolo_models/2022-0304/P_curve.png new file mode 100644 index 00000000..840a461b Binary files /dev/null and b/resources/yolo_models/2022-0304/P_curve.png differ diff --git a/resources/yolo_models/2022-0304/R_curve.png b/resources/yolo_models/2022-0304/R_curve.png new file mode 100644 index 00000000..5f4b7608 Binary files /dev/null and b/resources/yolo_models/2022-0304/R_curve.png differ diff --git a/resources/yolo_models/2022-0304/confusion_matrix.png b/resources/yolo_models/2022-0304/confusion_matrix.png new file mode 100644 index 00000000..f3b94b0a Binary files /dev/null and b/resources/yolo_models/2022-0304/confusion_matrix.png differ diff --git a/resources/yolo_models/2022-0304/events.out.tfevents.1646424266.ccowen-GL75-Leopard-10SFK.59957.0 b/resources/yolo_models/2022-0304/events.out.tfevents.1646424266.ccowen-GL75-Leopard-10SFK.59957.0 new file mode 100644 index 00000000..e5ef224f Binary files /dev/null and b/resources/yolo_models/2022-0304/events.out.tfevents.1646424266.ccowen-GL75-Leopard-10SFK.59957.0 differ diff --git a/resources/yolo_models/2022-0304/events.out.tfevents.1646460889.ccowen-GL75-Leopard-10SFK.102310.0 b/resources/yolo_models/2022-0304/events.out.tfevents.1646460889.ccowen-GL75-Leopard-10SFK.102310.0 new file mode 100644 index 00000000..2a0e46c3 Binary files /dev/null and b/resources/yolo_models/2022-0304/events.out.tfevents.1646460889.ccowen-GL75-Leopard-10SFK.102310.0 differ diff --git a/resources/yolo_models/2022-0304/events.out.tfevents.1646464545.ccowen-GL75-Leopard-10SFK.2457.0 b/resources/yolo_models/2022-0304/events.out.tfevents.1646464545.ccowen-GL75-Leopard-10SFK.2457.0 new file mode 100644 index 00000000..2ad1f8f1 Binary files /dev/null and b/resources/yolo_models/2022-0304/events.out.tfevents.1646464545.ccowen-GL75-Leopard-10SFK.2457.0 differ diff --git a/resources/yolo_models/2022-0304/hyp.yaml b/resources/yolo_models/2022-0304/hyp.yaml new file mode 100644 index 00000000..b54281de --- /dev/null +++ b/resources/yolo_models/2022-0304/hyp.yaml @@ -0,0 +1,28 @@ +lr0: 0.01 +lrf: 0.1 +momentum: 0.937 +weight_decay: 0.0005 +warmup_epochs: 3.0 +warmup_momentum: 0.8 +warmup_bias_lr: 0.1 +box: 0.05 +cls: 0.5 +cls_pw: 1.0 +obj: 1.0 +obj_pw: 1.0 +iou_t: 0.2 +anchor_t: 4.0 +fl_gamma: 0.0 +hsv_h: 0.015 +hsv_s: 0.7 +hsv_v: 0.4 +degrees: 0.0 +translate: 0.1 +scale: 0.5 +shear: 0.0 +perspective: 0.0 +flipud: 0.0 +fliplr: 0.5 +mosaic: 1.0 +mixup: 0.0 +copy_paste: 0.0 diff --git a/resources/yolo_models/2022-0304/labels.jpg b/resources/yolo_models/2022-0304/labels.jpg new file mode 100644 index 00000000..54cfd5ca Binary files /dev/null and b/resources/yolo_models/2022-0304/labels.jpg differ diff --git a/resources/yolo_models/2022-0304/labels_correlogram.jpg b/resources/yolo_models/2022-0304/labels_correlogram.jpg new file mode 100644 index 00000000..16e652ac Binary files /dev/null and b/resources/yolo_models/2022-0304/labels_correlogram.jpg differ diff --git a/resources/yolo_models/2022-0304/opt.yaml b/resources/yolo_models/2022-0304/opt.yaml new file mode 100644 index 00000000..aa1ef9bd --- /dev/null +++ b/resources/yolo_models/2022-0304/opt.yaml @@ -0,0 +1,38 @@ +weights: runs/train/exp4/weights/last.pt +cfg: '' +data: MarsRover.yaml +hyp: data/hyps/hyp.scratch.yaml +epochs: 220 +batch_size: -1 +imgsz: 640 +rect: false +resume: true +nosave: false +noval: false +noautoanchor: false +evolve: null +bucket: '' +cache: null +image_weights: false +device: '' +multi_scale: false +single_cls: false +optimizer: SGD +sync_bn: false +workers: 8 +project: runs/train +name: exp +exist_ok: false +quad: false +linear_lr: false +label_smoothing: 0.0 +patience: 100 +freeze: +- 0 +save_period: -1 +local_rank: -1 +entity: null +upload_dataset: false +bbox_interval: -1 +artifact_alias: latest +save_dir: runs/train/exp4 diff --git a/resources/yolo_models/2022-0304/results.csv b/resources/yolo_models/2022-0304/results.csv new file mode 100644 index 00000000..0d5cc916 --- /dev/null +++ b/resources/yolo_models/2022-0304/results.csv @@ -0,0 +1,222 @@ + epoch, train/box_loss, train/obj_loss, train/cls_loss, metrics/precision, metrics/recall, metrics/mAP_0.5,metrics/mAP_0.5:0.95, val/box_loss, val/obj_loss, val/cls_loss, x/lr0, x/lr1, x/lr2 + 0, 0.079894, 0.060339, 0.041056, 0.56965, 0.31772, 0.22786, 0.074393, 0.060261, 0.03118, 0.018066, 0.0033279, 0.0033279, 0.070049 + 1, 0.06387, 0.048696, 0.016492, 0.64992, 0.36226, 0.35764, 0.15101, 0.05461, 0.027454, 0.0089099, 0.006661, 0.006661, 0.040048 + 2, 0.05975, 0.048884, 0.012282, 0.6418, 0.39314, 0.38843, 0.16611, 0.053645, 0.029828, 0.0080772, 0.0099928, 0.0099928, 0.010047 + 3, 0.056089, 0.051052, 0.011395, 0.76423, 0.47025, 0.49663, 0.23431, 0.046953, 0.028293, 0.0060013, 0.0099959, 0.0099959, 0.0099959 + 4, 0.052659, 0.050738, 0.0098786, 0.74151, 0.49081, 0.51152, 0.25681, 0.044361, 0.028756, 0.0053101, 0.0099959, 0.0099959, 0.0099959 + 5, 0.050388, 0.049965, 0.0090791, 0.7933, 0.48813, 0.54147, 0.2726, 0.041587, 0.027757, 0.0046423, 0.0099927, 0.0099927, 0.0099927 + 6, 0.048499, 0.048393, 0.0075192, 0.73445, 0.5413, 0.56182, 0.28393, 0.040536, 0.02638, 0.0037057, 0.0099885, 0.0099885, 0.0099885 + 7, 0.046703, 0.047892, 0.0066378, 0.82409, 0.5591, 0.6236, 0.3267, 0.038294, 0.025709, 0.0033212, 0.0099835, 0.0099835, 0.0099835 + 8, 0.045558, 0.04457, 0.0065807, 0.83032, 0.58639, 0.67519, 0.35128, 0.038166, 0.024658, 0.0033897, 0.0099775, 0.0099775, 0.0099775 + 9, 0.045335, 0.045651, 0.006493, 0.82996, 0.57166, 0.66138, 0.35421, 0.037464, 0.024847, 0.0031623, 0.0099707, 0.0099707, 0.0099707 + 10, 0.045027, 0.045266, 0.0061624, 0.83352, 0.59146, 0.71496, 0.38111, 0.036797, 0.023993, 0.0027364, 0.0099629, 0.0099629, 0.0099629 + 11, 0.044017, 0.044371, 0.0054669, 0.76613, 0.65478, 0.69229, 0.36624, 0.035523, 0.02355, 0.0027869, 0.0099542, 0.0099542, 0.0099542 + 12, 0.043197, 0.044111, 0.0052657, 0.82781, 0.64698, 0.74957, 0.40712, 0.034572, 0.022834, 0.0022488, 0.0099446, 0.0099446, 0.0099446 + 13, 0.041965, 0.042608, 0.0045198, 0.8491, 0.66051, 0.75146, 0.40117, 0.034241, 0.022238, 0.0022238, 0.0099341, 0.0099341, 0.0099341 + 14, 0.041784, 0.042355, 0.0043093, 0.83349, 0.69683, 0.77818, 0.41508, 0.034176, 0.022027, 0.0020021, 0.0099227, 0.0099227, 0.0099227 + 15, 0.040923, 0.040855, 0.0042692, 0.6681, 0.83149, 0.7835, 0.43468, 0.033139, 0.021398, 0.001812, 0.0099104, 0.0099104, 0.0099104 + 16, 0.040428, 0.04048, 0.0044171, 0.84145, 0.77906, 0.82791, 0.46998, 0.033076, 0.021716, 0.0019683, 0.0098972, 0.0098972, 0.0098972 + 17, 0.040205, 0.040551, 0.0041051, 0.77721, 0.80329, 0.82724, 0.46083, 0.032108, 0.021132, 0.00179, 0.0098831, 0.0098831, 0.0098831 + 18, 0.039362, 0.040745, 0.0040801, 0.82569, 0.78758, 0.83782, 0.48295, 0.031054, 0.020489, 0.0017242, 0.0098681, 0.0098681, 0.0098681 + 19, 0.039645, 0.03965, 0.0037003, 0.8336, 0.79143, 0.84691, 0.48996, 0.03156, 0.020718, 0.0016284, 0.0098522, 0.0098522, 0.0098522 + 20, 0.038705, 0.03947, 0.0033539, 0.87245, 0.78861, 0.85765, 0.50796, 0.030648, 0.020533, 0.0014717, 0.0098354, 0.0098354, 0.0098354 + 21, 0.038628, 0.039522, 0.0034104, 0.88042, 0.81387, 0.87563, 0.52811, 0.03011, 0.0197, 0.001457, 0.0098177, 0.0098177, 0.0098177 + 22, 0.038064, 0.038835, 0.0034667, 0.83532, 0.80413, 0.8483, 0.50509, 0.030887, 0.019721, 0.0013744, 0.0097992, 0.0097992, 0.0097992 + 23, 0.03773, 0.03936, 0.0034626, 0.8045, 0.82689, 0.86178, 0.5001, 0.030297, 0.019671, 0.0013401, 0.0097798, 0.0097798, 0.0097798 + 24, 0.0376, 0.038395, 0.0031488, 0.8383, 0.83801, 0.86607, 0.51155, 0.029489, 0.019372, 0.0012817, 0.0097595, 0.0097595, 0.0097595 + 25, 0.037063, 0.038138, 0.0029898, 0.85227, 0.83946, 0.87877, 0.53464, 0.029262, 0.019271, 0.0014045, 0.0097383, 0.0097383, 0.0097383 + 26, 0.036691, 0.03769, 0.0031485, 0.83094, 0.84023, 0.85393, 0.51526, 0.028285, 0.018725, 0.0012826, 0.0097163, 0.0097163, 0.0097163 + 27, 0.036181, 0.036444, 0.0030863, 0.85635, 0.81714, 0.87319, 0.52986, 0.028296, 0.018971, 0.0012067, 0.0096934, 0.0096934, 0.0096934 + 28, 0.035657, 0.037234, 0.0028966, 0.83472, 0.85471, 0.88575, 0.54461, 0.028013, 0.018625, 0.0011482, 0.0096696, 0.0096696, 0.0096696 + 29, 0.035755, 0.036681, 0.0028208, 0.88173, 0.85818, 0.90854, 0.58703, 0.027303, 0.018112, 0.0011482, 0.0096451, 0.0096451, 0.0096451 + 30, 0.035178, 0.036405, 0.0026687, 0.85694, 0.8831, 0.90086, 0.56393, 0.027361, 0.017944, 0.001084, 0.0096196, 0.0096196, 0.0096196 + 31, 0.035025, 0.035984, 0.0027541, 0.83279, 0.84739, 0.87276, 0.55961, 0.026579, 0.017872, 0.001105, 0.0095933, 0.0095933, 0.0095933 + 32, 0.034772, 0.03613, 0.0026247, 0.86262, 0.84842, 0.89294, 0.59015, 0.026508, 0.017546, 0.0011433, 0.0095662, 0.0095662, 0.0095662 + 33, 0.034374, 0.035404, 0.0027772, 0.89899, 0.87567, 0.91672, 0.58968, 0.026938, 0.017597, 0.0011687, 0.0095383, 0.0095383, 0.0095383 + 34, 0.034333, 0.035911, 0.0027484, 0.80967, 0.87216, 0.86532, 0.5454, 0.026619, 0.017604, 0.0011247, 0.0095095, 0.0095095, 0.0095095 + 35, 0.034197, 0.035629, 0.0026466, 0.87597, 0.85455, 0.90404, 0.56931, 0.026376, 0.017852, 0.0010083, 0.0094799, 0.0094799, 0.0094799 + 36, 0.034189, 0.034492, 0.0025762, 0.8303, 0.90232, 0.88651, 0.57969, 0.025695, 0.017201, 0.001021, 0.0094496, 0.0094496, 0.0094496 + 37, 0.033431, 0.034834, 0.0024898, 0.90942, 0.87567, 0.92207, 0.62365, 0.026134, 0.017022, 0.0011003, 0.0094184, 0.0094184, 0.0094184 + 38, 0.033329, 0.034737, 0.0025033, 0.88249, 0.86125, 0.90989, 0.5893, 0.025406, 0.016757, 0.0010099, 0.0093864, 0.0093864, 0.0093864 + 39, 0.033221, 0.034612, 0.0024599, 0.8819, 0.88236, 0.92041, 0.61976, 0.025305, 0.016764, 0.00096252, 0.0093536, 0.0093536, 0.0093536 + 40, 0.033095, 0.034083, 0.0023233, 0.90341, 0.88091, 0.92326, 0.6132, 0.024973, 0.016439, 0.00098897, 0.00932, 0.00932, 0.00932 + 41, 0.032628, 0.034234, 0.00221, 0.89635, 0.87294, 0.91392, 0.60513, 0.025299, 0.016452, 0.00094703, 0.0092856, 0.0092856, 0.0092856 + 42, 0.032333, 0.033498, 0.0022953, 0.92194, 0.86004, 0.92571, 0.63784, 0.024348, 0.016451, 0.0009805, 0.0092505, 0.0092505, 0.0092505 + 43, 0.032652, 0.033733, 0.0025123, 0.88746, 0.86344, 0.91018, 0.60856, 0.02484, 0.016422, 0.0010259, 0.0092146, 0.0092146, 0.0092146 + 44, 0.032153, 0.033306, 0.0023245, 0.87546, 0.85109, 0.90635, 0.61748, 0.024402, 0.016294, 0.00092752, 0.009178, 0.009178, 0.009178 + 45, 0.032093, 0.033302, 0.0022208, 0.86815, 0.89237, 0.91633, 0.62724, 0.02398, 0.015958, 0.00089983, 0.0091406, 0.0091406, 0.0091406 + 46, 0.031906, 0.033382, 0.0023432, 0.87512, 0.89701, 0.921, 0.62444, 0.023739, 0.015926, 0.00089149, 0.0091024, 0.0091024, 0.0091024 + 47, 0.031754, 0.033293, 0.0024189, 0.90526, 0.90139, 0.93713, 0.65774, 0.023366, 0.015738, 0.00086695, 0.0090636, 0.0090636, 0.0090636 + 48, 0.031609, 0.032812, 0.0022001, 0.89696, 0.90166, 0.93074, 0.65266, 0.023146, 0.015635, 0.00091244, 0.009024, 0.009024, 0.009024 + 49, 0.031174, 0.033387, 0.0020703, 0.84489, 0.89458, 0.90861, 0.62875, 0.02294, 0.015568, 0.0009151, 0.0089836, 0.0089836, 0.0089836 + 50, 0.030454, 0.031713, 0.0021156, 0.89492, 0.92196, 0.94471, 0.6743, 0.022469, 0.015298, 0.00081196, 0.0089426, 0.0089426, 0.0089426 + 51, 0.0314, 0.032952, 0.0022827, 0.90261, 0.8938, 0.93452, 0.65236, 0.023054, 0.015472, 0.00093854, 0.0089009, 0.0089009, 0.0089009 + 52, 0.030897, 0.031642, 0.0020868, 0.88734, 0.8909, 0.93125, 0.64191, 0.022936, 0.015598, 0.00090951, 0.0088584, 0.0088584, 0.0088584 + 53, 0.030445, 0.032129, 0.0019425, 0.8953, 0.85839, 0.91338, 0.64168, 0.022271, 0.015075, 0.0008513, 0.0088153, 0.0088153, 0.0088153 + 54, 0.030208, 0.031961, 0.0020131, 0.87307, 0.88983, 0.92423, 0.63853, 0.022377, 0.015061, 0.00081705, 0.0087715, 0.0087715, 0.0087715 + 55, 0.03031, 0.031603, 0.0018981, 0.9066, 0.90502, 0.94065, 0.68118, 0.022005, 0.014851, 0.00078894, 0.0087271, 0.0087271, 0.0087271 + 56, 0.030112, 0.030652, 0.0017949, 0.90547, 0.89352, 0.9312, 0.637, 0.022187, 0.014921, 0.00084618, 0.008682, 0.008682, 0.008682 + 57, 0.029674, 0.031216, 0.0018701, 0.91511, 0.90869, 0.94683, 0.67955, 0.022349, 0.014868, 0.00077252, 0.0086362, 0.0086362, 0.0086362 + 58, 0.029712, 0.0308, 0.0018174, 0.91948, 0.90994, 0.94426, 0.69242, 0.021625, 0.014673, 0.00079201, 0.0085898, 0.0085898, 0.0085898 + 59, 0.030209, 0.031684, 0.0020632, 0.9156, 0.89668, 0.94194, 0.6701, 0.021666, 0.014819, 0.0008087, 0.0085428, 0.0085428, 0.0085428 + 60, 0.029505, 0.031282, 0.0019961, 0.88589, 0.91182, 0.92716, 0.65801, 0.021825, 0.014732, 0.00077839, 0.0084951, 0.0084951, 0.0084951 + 61, 0.029373, 0.030786, 0.0018061, 0.92864, 0.89747, 0.94301, 0.6881, 0.021447, 0.014455, 0.00076467, 0.0084469, 0.0084469, 0.0084469 + 62, 0.028961, 0.030456, 0.0019168, 0.94228, 0.88863, 0.94488, 0.69922, 0.021222, 0.014418, 0.00073491, 0.008398, 0.008398, 0.008398 + 63, 0.029459, 0.030684, 0.0017373, 0.92124, 0.91671, 0.94872, 0.69937, 0.02111, 0.014328, 0.00077147, 0.0083486, 0.0083486, 0.0083486 + 64, 0.028711, 0.030291, 0.0017307, 0.889, 0.90409, 0.93799, 0.6749, 0.021003, 0.014096, 0.00084382, 0.0082985, 0.0082985, 0.0082985 + 65, 0.028288, 0.029959, 0.0016813, 0.92558, 0.91511, 0.94371, 0.70592, 0.020555, 0.014075, 0.00077638, 0.0082479, 0.0082479, 0.0082479 + 66, 0.028554, 0.030195, 0.0017373, 0.92409, 0.92869, 0.95309, 0.71244, 0.020447, 0.01397, 0.00075501, 0.0081967, 0.0081967, 0.0081967 + 67, 0.028716, 0.030539, 0.0018288, 0.93749, 0.90543, 0.95132, 0.70761, 0.02025, 0.013822, 0.00075775, 0.008145, 0.008145, 0.008145 + 68, 0.028202, 0.029772, 0.0017257, 0.93488, 0.90394, 0.9492, 0.71764, 0.019967, 0.013859, 0.00074417, 0.0080928, 0.0080928, 0.0080928 + 69, 0.028096, 0.029747, 0.0016907, 0.92584, 0.91798, 0.95294, 0.73363, 0.020003, 0.013666, 0.00069126, 0.00804, 0.00804, 0.00804 + 70, 0.027789, 0.029003, 0.0016175, 0.9271, 0.90872, 0.95048, 0.69589, 0.020149, 0.013686, 0.00070011, 0.0079867, 0.0079867, 0.0079867 + 71, 0.027914, 0.029574, 0.0017244, 0.94254, 0.92102, 0.95841, 0.72642, 0.01991, 0.013611, 0.00074269, 0.0079329, 0.0079329, 0.0079329 + 72, 0.027941, 0.029682, 0.0017182, 0.90425, 0.92073, 0.94306, 0.70841, 0.019483, 0.013454, 0.00072216, 0.0078786, 0.0078786, 0.0078786 + 73, 0.027716, 0.029119, 0.0016103, 0.94893, 0.92014, 0.95591, 0.73885, 0.019576, 0.013464, 0.00069628, 0.0078238, 0.0078238, 0.0078238 + 73, 0.027773, 0.030428, 0.002163, 0.9348, 0.8996, 0.95032, 0.70009, 0.019217, 0.014004, 0.00068415, 0.0078238, 0.0078238, 0.0078238 + 74, 0.02751, 0.030139, 0.0018922, 0.91299, 0.90701, 0.94646, 0.66321, 0.019352, 0.014106, 0.00070804, 0.0077685, 0.0077685, 0.0077685 + 75, 0.027817, 0.030677, 0.0021019, 0.94252, 0.90844, 0.95426, 0.70471, 0.019477, 0.014096, 0.00068432, 0.0077128, 0.0077128, 0.0077128 + 76, 0.028153, 0.030896, 0.0020326, 0.93494, 0.91131, 0.95241, 0.70359, 0.019492, 0.01396, 0.00068276, 0.0076566, 0.0076566, 0.0076566 + 77, 0.027409, 0.030581, 0.0019533, 0.92279, 0.91762, 0.94586, 0.70566, 0.019168, 0.013955, 0.00067439, 0.0076, 0.0076, 0.0076 + 78, 0.027697, 0.030135, 0.0021816, 0.93155, 0.9048, 0.94702, 0.68502, 0.019745, 0.014112, 0.00069453, 0.007543, 0.007543, 0.007543 + 79, 0.027583, 0.030402, 0.0020263, 0.90927, 0.92539, 0.95086, 0.71072, 0.019019, 0.013863, 0.00070198, 0.0074855, 0.0074855, 0.0074855 + 80, 0.027412, 0.029852, 0.0020233, 0.93686, 0.91002, 0.95299, 0.72436, 0.018962, 0.01379, 0.00071095, 0.0074276, 0.0074276, 0.0074276 + 81, 0.027241, 0.029478, 0.0016483, 0.95393, 0.90088, 0.95653, 0.71746, 0.019013, 0.013647, 0.0006804, 0.0073694, 0.0073694, 0.0073694 + 82, 0.025504, 0.027138, 0.0014191, 0.94753, 0.90935, 0.95533, 0.7275, 0.018288, 0.013331, 0.00065449, 0.0073107, 0.0073107, 0.0073107 + 83, 0.025136, 0.026222, 0.0012592, 0.89501, 0.92996, 0.94787, 0.70106, 0.018532, 0.01343, 0.00062863, 0.0072517, 0.0072517, 0.0072517 + 84, 0.024733, 0.026385, 0.0012311, 0.93563, 0.91941, 0.95837, 0.72326, 0.018455, 0.013257, 0.00065079, 0.0071923, 0.0071923, 0.0071923 + 85, 0.025397, 0.026615, 0.0011894, 0.96004, 0.89796, 0.95468, 0.71985, 0.018342, 0.013208, 0.00067283, 0.0071326, 0.0071326, 0.0071326 + 86, 0.02453, 0.026143, 0.0012115, 0.94498, 0.91429, 0.95629, 0.72331, 0.018464, 0.01343, 0.00063575, 0.0070726, 0.0070726, 0.0070726 + 87, 0.024429, 0.025295, 0.0012351, 0.93189, 0.92426, 0.95561, 0.71252, 0.018449, 0.013337, 0.00067166, 0.0070122, 0.0070122, 0.0070122 + 88, 0.024264, 0.02557, 0.0011692, 0.94643, 0.91643, 0.95907, 0.73795, 0.018099, 0.013008, 0.0006458, 0.0069515, 0.0069515, 0.0069515 + 89, 0.024347, 0.025517, 0.00127, 0.95198, 0.92188, 0.96199, 0.74439, 0.017951, 0.013053, 0.00065416, 0.0068906, 0.0068906, 0.0068906 + 90, 0.024607, 0.025406, 0.0010486, 0.9361, 0.91757, 0.95495, 0.73725, 0.017858, 0.013014, 0.00064104, 0.0068293, 0.0068293, 0.0068293 + 91, 0.026379, 0.028482, 0.0016282, 0.93663, 0.91391, 0.95291, 0.72391, 0.017976, 0.013233, 0.00065716, 0.0067678, 0.0067678, 0.0067678 + 92, 0.026249, 0.028983, 0.0017349, 0.94711, 0.90855, 0.95785, 0.73833, 0.018013, 0.013201, 0.00062827, 0.006706, 0.006706, 0.006706 + 93, 0.025941, 0.028495, 0.0016918, 0.93699, 0.91348, 0.95639, 0.73763, 0.017847, 0.01322, 0.00063553, 0.006644, 0.006644, 0.006644 + 94, 0.025844, 0.028751, 0.0015764, 0.95792, 0.8992, 0.95687, 0.7402, 0.017763, 0.01322, 0.000598, 0.0065817, 0.0065817, 0.0065817 + 95, 0.025903, 0.02873, 0.0016728, 0.93204, 0.89947, 0.95643, 0.71792, 0.017647, 0.012906, 0.00058875, 0.0065192, 0.0065192, 0.0065192 + 96, 0.025972, 0.028733, 0.0016727, 0.92793, 0.90938, 0.95379, 0.73946, 0.017568, 0.01291, 0.00058351, 0.0064565, 0.0064565, 0.0064565 + 97, 0.025554, 0.028256, 0.0018169, 0.93326, 0.91672, 0.95955, 0.75007, 0.017573, 0.012896, 0.00057117, 0.0063937, 0.0063937, 0.0063937 + 98, 0.025412, 0.028038, 0.001596, 0.94413, 0.9076, 0.95856, 0.73835, 0.017438, 0.012875, 0.00055426, 0.0063306, 0.0063306, 0.0063306 + 99, 0.025291, 0.028037, 0.0015039, 0.94708, 0.91329, 0.95908, 0.75023, 0.017162, 0.012673, 0.00056683, 0.0062673, 0.0062673, 0.0062673 + 100, 0.025249, 0.028108, 0.0015746, 0.9339, 0.92455, 0.95043, 0.73534, 0.017386, 0.012721, 0.00058526, 0.006204, 0.006204, 0.006204 + 101, 0.024975, 0.027142, 0.0015123, 0.95172, 0.9088, 0.96074, 0.73766, 0.017252, 0.012591, 0.0005671, 0.0061404, 0.0061404, 0.0061404 + 102, 0.024918, 0.027595, 0.0014986, 0.95419, 0.91854, 0.96351, 0.75786, 0.017004, 0.012465, 0.00059016, 0.0060767, 0.0060767, 0.0060767 + 103, 0.024814, 0.026606, 0.0014044, 0.9375, 0.93394, 0.9601, 0.76148, 0.016772, 0.012469, 0.00058013, 0.006013, 0.006013, 0.006013 + 104, 0.025037, 0.027676, 0.0016835, 0.94269, 0.92805, 0.96196, 0.7568, 0.017041, 0.012617, 0.00056938, 0.0059491, 0.0059491, 0.0059491 + 105, 0.024754, 0.026803, 0.001291, 0.95083, 0.92672, 0.96229, 0.75517, 0.016634, 0.012256, 0.0005319, 0.0058851, 0.0058851, 0.0058851 + 106, 0.024395, 0.026762, 0.0013648, 0.94784, 0.9192, 0.9588, 0.76137, 0.016632, 0.012283, 0.00056678, 0.005821, 0.005821, 0.005821 + 107, 0.02422, 0.027205, 0.0014192, 0.93754, 0.93813, 0.96681, 0.76543, 0.016312, 0.012091, 0.00056368, 0.0057569, 0.0057569, 0.0057569 + 108, 0.024241, 0.026427, 0.0013877, 0.95207, 0.90687, 0.96066, 0.75791, 0.016372, 0.012172, 0.00056832, 0.0056927, 0.0056927, 0.0056927 + 109, 0.024141, 0.026637, 0.0013451, 0.93695, 0.92816, 0.96429, 0.75968, 0.016488, 0.012118, 0.0005675, 0.0056285, 0.0056285, 0.0056285 + 110, 0.023827, 0.026457, 0.0012618, 0.94981, 0.92868, 0.9674, 0.77046, 0.016295, 0.012001, 0.00054914, 0.0055643, 0.0055643, 0.0055643 + 111, 0.023839, 0.026572, 0.0012198, 0.96447, 0.9188, 0.96335, 0.77562, 0.016032, 0.011859, 0.0005271, 0.0055, 0.0055, 0.0055 + 112, 0.024567, 0.026409, 0.0014998, 0.93852, 0.93291, 0.96484, 0.76308, 0.016238, 0.012136, 0.00055147, 0.0054357, 0.0054357, 0.0054357 + 113, 0.024013, 0.026302, 0.0014398, 0.94344, 0.93402, 0.96643, 0.77665, 0.01625, 0.012113, 0.00052585, 0.0053715, 0.0053715, 0.0053715 + 114, 0.023854, 0.026506, 0.0013654, 0.97162, 0.91911, 0.96766, 0.76868, 0.016136, 0.011927, 0.00051682, 0.0053073, 0.0053073, 0.0053073 + 115, 0.023785, 0.025935, 0.0011352, 0.96441, 0.92129, 0.96782, 0.78067, 0.015903, 0.011773, 0.00053715, 0.0052431, 0.0052431, 0.0052431 + 116, 0.023392, 0.025486, 0.0012062, 0.95849, 0.92765, 0.96786, 0.78062, 0.015787, 0.011654, 0.00051923, 0.005179, 0.005179, 0.005179 + 117, 0.023283, 0.025528, 0.0012881, 0.96821, 0.92519, 0.96978, 0.78445, 0.015809, 0.011695, 0.00052952, 0.0051149, 0.0051149, 0.0051149 + 118, 0.023375, 0.025493, 0.0011949, 0.94585, 0.9315, 0.96565, 0.76942, 0.015502, 0.011486, 0.00053704, 0.0050509, 0.0050509, 0.0050509 + 119, 0.02277, 0.025116, 0.0010788, 0.94995, 0.93839, 0.96784, 0.78007, 0.015498, 0.011431, 0.00052695, 0.004987, 0.004987, 0.004987 + 120, 0.022887, 0.025326, 0.0011407, 0.95918, 0.92987, 0.9703, 0.78654, 0.015451, 0.011441, 0.00052019, 0.0049233, 0.0049233, 0.0049233 + 121, 0.022482, 0.024691, 0.0011333, 0.96273, 0.93059, 0.96976, 0.78528, 0.015369, 0.011334, 0.00050358, 0.0048596, 0.0048596, 0.0048596 + 122, 0.022591, 0.025137, 0.0012468, 0.96024, 0.93265, 0.97111, 0.79667, 0.015209, 0.011238, 0.00048674, 0.004796, 0.004796, 0.004796 + 123, 0.022398, 0.0244, 0.0012136, 0.95897, 0.93248, 0.96984, 0.79819, 0.015244, 0.011176, 0.00048564, 0.0047327, 0.0047327, 0.0047327 + 124, 0.022585, 0.024863, 0.0011666, 0.96125, 0.92688, 0.97104, 0.79311, 0.015285, 0.011186, 0.00047211, 0.0046694, 0.0046694, 0.0046694 + 125, 0.022342, 0.024783, 0.0011371, 0.96769, 0.93329, 0.97126, 0.79455, 0.01496, 0.010961, 0.00049649, 0.0046063, 0.0046063, 0.0046063 + 126, 0.022791, 0.024764, 0.0012662, 0.95865, 0.93414, 0.96973, 0.78682, 0.014889, 0.010955, 0.00048392, 0.0045435, 0.0045435, 0.0045435 + 127, 0.02276, 0.024867, 0.0012215, 0.96673, 0.93868, 0.96995, 0.80032, 0.014998, 0.011032, 0.00047415, 0.0044808, 0.0044808, 0.0044808 + 128, 0.022411, 0.024827, 0.0011549, 0.96866, 0.93497, 0.97323, 0.80881, 0.014919, 0.010967, 0.00046295, 0.0044183, 0.0044183, 0.0044183 + 129, 0.022382, 0.025215, 0.0011, 0.95788, 0.94559, 0.97129, 0.80845, 0.014804, 0.01095, 0.00044214, 0.004356, 0.004356, 0.004356 + 130, 0.022393, 0.024326, 0.00131, 0.94869, 0.94542, 0.97134, 0.80292, 0.014786, 0.010946, 0.00047113, 0.004294, 0.004294, 0.004294 + 131, 0.022446, 0.025151, 0.0011669, 0.95007, 0.94774, 0.97095, 0.79833, 0.014661, 0.010873, 0.00045396, 0.0042322, 0.0042322, 0.0042322 + 132, 0.022349, 0.024268, 0.0011168, 0.9555, 0.94719, 0.97272, 0.80522, 0.01455, 0.010796, 0.0004566, 0.0041707, 0.0041707, 0.0041707 + 133, 0.022034, 0.024572, 0.0013099, 0.967, 0.9369, 0.97392, 0.80636, 0.01444, 0.010658, 0.00046175, 0.0041094, 0.0041094, 0.0041094 + 134, 0.021988, 0.024283, 0.0010971, 0.96912, 0.93011, 0.97357, 0.81157, 0.014465, 0.010606, 0.00045532, 0.0040485, 0.0040485, 0.0040485 + 135, 0.021571, 0.024592, 0.0010088, 0.95889, 0.94342, 0.97423, 0.80334, 0.014529, 0.010691, 0.00045006, 0.0039878, 0.0039878, 0.0039878 + 136, 0.02172, 0.024334, 0.00109, 0.96588, 0.93182, 0.97291, 0.80902, 0.014518, 0.010683, 0.00046618, 0.0039274, 0.0039274, 0.0039274 + 137, 0.021746, 0.024113, 0.001075, 0.95852, 0.93797, 0.97276, 0.81552, 0.014314, 0.010612, 0.00044826, 0.0038674, 0.0038674, 0.0038674 + 138, 0.021409, 0.023965, 0.0011448, 0.953, 0.94421, 0.9725, 0.81482, 0.014192, 0.010558, 0.00043496, 0.0038077, 0.0038077, 0.0038077 + 139, 0.021245, 0.023938, 0.0010227, 0.95821, 0.94485, 0.97463, 0.8182, 0.01415, 0.010459, 0.00043057, 0.0037483, 0.0037483, 0.0037483 + 140, 0.021387, 0.023672, 0.0010074, 0.96684, 0.92793, 0.97367, 0.81511, 0.014191, 0.010439, 0.00041349, 0.0036893, 0.0036893, 0.0036893 + 141, 0.021139, 0.023421, 0.0010921, 0.96971, 0.92859, 0.97222, 0.81308, 0.014089, 0.010343, 0.00040111, 0.0036306, 0.0036306, 0.0036306 + 142, 0.021083, 0.02375, 0.0010689, 0.97292, 0.93467, 0.97293, 0.81472, 0.014021, 0.010265, 0.00038803, 0.0035724, 0.0035724, 0.0035724 + 143, 0.021123, 0.023713, 0.0011218, 0.98181, 0.93242, 0.97429, 0.82123, 0.014058, 0.01029, 0.0004052, 0.0035145, 0.0035145, 0.0035145 + 144, 0.020782, 0.023661, 0.00088243, 0.97105, 0.939, 0.97363, 0.82166, 0.014, 0.010222, 0.00038809, 0.003457, 0.003457, 0.003457 + 145, 0.020594, 0.023386, 0.00096776, 0.96893, 0.939, 0.97444, 0.82515, 0.013871, 0.010155, 0.00039551, 0.0034, 0.0034, 0.0034 + 146, 0.020839, 0.023985, 0.0010826, 0.9718, 0.93893, 0.97378, 0.82283, 0.013627, 0.010026, 0.00038575, 0.0033434, 0.0033434, 0.0033434 + 147, 0.020844, 0.023071, 0.0010092, 0.97371, 0.9274, 0.97166, 0.82828, 0.01348, 0.0099431, 0.00038387, 0.0032872, 0.0032872, 0.0032872 + 148, 0.020311, 0.02286, 0.00093501, 0.96668, 0.93507, 0.96826, 0.82587, 0.013435, 0.0098925, 0.00038851, 0.0032315, 0.0032315, 0.0032315 + 149, 0.020428, 0.023068, 0.00097853, 0.97209, 0.94561, 0.9751, 0.82759, 0.01339, 0.009858, 0.00038484, 0.0031762, 0.0031762, 0.0031762 + 150, 0.020214, 0.022708, 0.00089433, 0.97633, 0.94375, 0.97624, 0.83367, 0.013403, 0.0098564, 0.00036922, 0.0031214, 0.0031214, 0.0031214 + 151, 0.020394, 0.02259, 0.00099944, 0.96909, 0.94766, 0.97549, 0.82838, 0.013434, 0.0097893, 0.00037254, 0.0030671, 0.0030671, 0.0030671 + 152, 0.020255, 0.022704, 0.00096026, 0.95763, 0.95649, 0.97698, 0.83, 0.013344, 0.0097335, 0.00036172, 0.0030133, 0.0030133, 0.0030133 + 153, 0.020088, 0.021935, 0.00090003, 0.97259, 0.94648, 0.97706, 0.83436, 0.013232, 0.0096998, 0.00036945, 0.00296, 0.00296, 0.00296 + 154, 0.020026, 0.022731, 0.0010331, 0.97779, 0.94971, 0.97885, 0.83479, 0.013129, 0.0096725, 0.00038421, 0.0029072, 0.0029072, 0.0029072 + 155, 0.020168, 0.022159, 0.00087659, 0.97596, 0.94988, 0.97791, 0.83378, 0.013108, 0.0096227, 0.00039724, 0.002855, 0.002855, 0.002855 + 156, 0.020057, 0.022795, 0.0011302, 0.96544, 0.95926, 0.9794, 0.83758, 0.013034, 0.0095943, 0.0003645, 0.0028033, 0.0028033, 0.0028033 + 157, 0.019712, 0.022111, 0.00087797, 0.96474, 0.95908, 0.9797, 0.83972, 0.013031, 0.0096213, 0.00035002, 0.0027521, 0.0027521, 0.0027521 + 158, 0.020064, 0.022046, 0.0010188, 0.97533, 0.94677, 0.97929, 0.84333, 0.013001, 0.0095732, 0.00034306, 0.0027015, 0.0027015, 0.0027015 + 159, 0.0195, 0.021697, 0.00088013, 0.98023, 0.94474, 0.97995, 0.84305, 0.012965, 0.0094801, 0.00034187, 0.0026514, 0.0026514, 0.0026514 + 160, 0.019456, 0.02222, 0.0009213, 0.9728, 0.95394, 0.9796, 0.8407, 0.012935, 0.0094388, 0.00033657, 0.002602, 0.002602, 0.002602 + 161, 0.019385, 0.022058, 0.00084218, 0.97753, 0.94755, 0.97747, 0.84251, 0.012822, 0.0093823, 0.00034358, 0.0025531, 0.0025531, 0.0025531 + 162, 0.019238, 0.021775, 0.00080639, 0.97932, 0.9451, 0.97824, 0.84049, 0.012788, 0.0093431, 0.00033181, 0.0025049, 0.0025049, 0.0025049 + 163, 0.019394, 0.021762, 0.00084356, 0.97677, 0.95073, 0.97784, 0.84104, 0.012809, 0.0093129, 0.00032841, 0.0024572, 0.0024572, 0.0024572 + 164, 0.019225, 0.021179, 0.00076261, 0.97537, 0.95362, 0.97801, 0.8423, 0.012737, 0.0092708, 0.00031915, 0.0024102, 0.0024102, 0.0024102 + 165, 0.019333, 0.021578, 0.00084734, 0.98196, 0.94703, 0.97916, 0.84743, 0.012658, 0.0092006, 0.00032226, 0.0023638, 0.0023638, 0.0023638 + 166, 0.019142, 0.021528, 0.0007854, 0.97642, 0.95508, 0.97921, 0.84988, 0.012648, 0.0091825, 0.00031625, 0.002318, 0.002318, 0.002318 + 167, 0.018755, 0.021108, 0.00080697, 0.97319, 0.95587, 0.97835, 0.84846, 0.012589, 0.0091344, 0.000309, 0.0022729, 0.0022729, 0.0022729 + 168, 0.018996, 0.021392, 0.00081032, 0.98004, 0.95268, 0.9792, 0.84736, 0.012529, 0.0090767, 0.00030381, 0.0022285, 0.0022285, 0.0022285 + 169, 0.018742, 0.020983, 0.0007202, 0.98272, 0.95267, 0.98112, 0.85118, 0.012486, 0.0090335, 0.00030068, 0.0021847, 0.0021847, 0.0021847 + 170, 0.018639, 0.021243, 0.0008334, 0.97882, 0.95345, 0.98049, 0.85304, 0.01244, 0.009008, 0.00029761, 0.0021416, 0.0021416, 0.0021416 + 171, 0.018541, 0.020737, 0.00093516, 0.97935, 0.9513, 0.98113, 0.85351, 0.012484, 0.0089918, 0.00029929, 0.0020991, 0.0020991, 0.0020991 + 172, 0.018612, 0.020864, 0.0007228, 0.97715, 0.95244, 0.98008, 0.8562, 0.012407, 0.0089466, 0.00029073, 0.0020574, 0.0020574, 0.0020574 + 173, 0.018843, 0.021193, 0.00087355, 0.97959, 0.95006, 0.98168, 0.85669, 0.01237, 0.0089142, 0.00029049, 0.0020164, 0.0020164, 0.0020164 + 174, 0.018287, 0.020266, 0.00074541, 0.97291, 0.95681, 0.98226, 0.8581, 0.012243, 0.0088638, 0.0002893, 0.001976, 0.001976, 0.001976 + 175, 0.018574, 0.020989, 0.00080447, 0.98816, 0.94254, 0.98145, 0.86101, 0.01213, 0.0088143, 0.00029636, 0.0019364, 0.0019364, 0.0019364 + 176, 0.018321, 0.020753, 0.00072352, 0.9796, 0.95341, 0.98145, 0.86306, 0.01211, 0.0087789, 0.00029472, 0.0018976, 0.0018976, 0.0018976 + 177, 0.018131, 0.020874, 0.0007083, 0.97912, 0.95529, 0.98316, 0.86028, 0.012085, 0.0087474, 0.00029923, 0.0018594, 0.0018594, 0.0018594 + 178, 0.01816, 0.020584, 0.00069216, 0.98172, 0.95413, 0.98281, 0.86254, 0.012066, 0.0087147, 0.00029778, 0.001822, 0.001822, 0.001822 + 179, 0.01823, 0.020384, 0.00065976, 0.98141, 0.95868, 0.98229, 0.86121, 0.012005, 0.0086731, 0.0002904, 0.0017854, 0.0017854, 0.0017854 + 180, 0.017805, 0.020457, 0.00069948, 0.97833, 0.96081, 0.9825, 0.86046, 0.011951, 0.0086255, 0.00028056, 0.0017495, 0.0017495, 0.0017495 + 181, 0.018177, 0.020018, 0.00078947, 0.97978, 0.95991, 0.98098, 0.86069, 0.011842, 0.0085703, 0.00027443, 0.0017144, 0.0017144, 0.0017144 + 182, 0.017898, 0.020337, 0.00075235, 0.97679, 0.95993, 0.98269, 0.86247, 0.011804, 0.0085325, 0.00026497, 0.00168, 0.00168, 0.00168 + 183, 0.017804, 0.019788, 0.00067605, 0.97386, 0.96098, 0.98279, 0.86449, 0.01175, 0.0085001, 0.00026445, 0.0016464, 0.0016464, 0.0016464 + 184, 0.017839, 0.020173, 0.00067716, 0.98989, 0.9445, 0.98299, 0.8676, 0.01171, 0.0084701, 0.00026368, 0.0016136, 0.0016136, 0.0016136 + 185, 0.01805, 0.020307, 0.00066716, 0.9874, 0.94873, 0.98275, 0.8683, 0.01169, 0.0084449, 0.00026252, 0.0015816, 0.0015816, 0.0015816 + 186, 0.0178, 0.02026, 0.00070101, 0.97713, 0.95889, 0.98351, 0.871, 0.011667, 0.0084129, 0.00025778, 0.0015504, 0.0015504, 0.0015504 + 187, 0.017521, 0.019327, 0.0007857, 0.98122, 0.95814, 0.98356, 0.87126, 0.011647, 0.0084064, 0.0002558, 0.0015201, 0.0015201, 0.0015201 + 188, 0.017741, 0.019893, 0.0006617, 0.97977, 0.96185, 0.98255, 0.87084, 0.01162, 0.0083923, 0.00025137, 0.0014905, 0.0014905, 0.0014905 + 189, 0.017455, 0.019277, 0.00082862, 0.97599, 0.96368, 0.98195, 0.8713, 0.011553, 0.0083565, 0.00024952, 0.0014617, 0.0014617, 0.0014617 + 190, 0.017383, 0.019795, 0.00069752, 0.97459, 0.96387, 0.98261, 0.87281, 0.011517, 0.008318, 0.00024474, 0.0014338, 0.0014338, 0.0014338 + 191, 0.017544, 0.019752, 0.00062571, 0.97264, 0.96665, 0.98248, 0.87275, 0.011478, 0.0082939, 0.00024226, 0.0014067, 0.0014067, 0.0014067 + 192, 0.017417, 0.019517, 0.00066932, 0.97543, 0.96462, 0.983, 0.87396, 0.011443, 0.0082617, 0.00024069, 0.0013804, 0.0013804, 0.0013804 + 193, 0.01757, 0.019643, 0.00065937, 0.97898, 0.96515, 0.9844, 0.87246, 0.01147, 0.0082688, 0.00024046, 0.0013549, 0.0013549, 0.0013549 + 194, 0.017305, 0.01945, 0.0006785, 0.97856, 0.96566, 0.98449, 0.87237, 0.011442, 0.0082419, 0.00023743, 0.0013304, 0.0013304, 0.0013304 + 195, 0.01713, 0.019219, 0.00069626, 0.98963, 0.95639, 0.98459, 0.87193, 0.011401, 0.0082087, 0.00023499, 0.0013066, 0.0013066, 0.0013066 + 196, 0.017074, 0.019362, 0.00056472, 0.99117, 0.95426, 0.98173, 0.87315, 0.011374, 0.0081736, 0.0002339, 0.0012837, 0.0012837, 0.0012837 + 197, 0.017072, 0.018748, 0.00063828, 0.98854, 0.95781, 0.98269, 0.8739, 0.011332, 0.008151, 0.00023335, 0.0012617, 0.0012617, 0.0012617 + 198, 0.017153, 0.019071, 0.00063565, 0.98507, 0.96409, 0.98317, 0.87494, 0.011286, 0.0081132, 0.00023157, 0.0012405, 0.0012405, 0.0012405 + 199, 0.017021, 0.018916, 0.00066308, 0.98268, 0.9667, 0.98499, 0.87574, 0.011251, 0.0080915, 0.00023222, 0.0012202, 0.0012202, 0.0012202 + 200, 0.017024, 0.019091, 0.00059165, 0.98159, 0.96878, 0.98417, 0.87565, 0.011214, 0.0080652, 0.00023062, 0.0012008, 0.0012008, 0.0012008 + 201, 0.017056, 0.018932, 0.00063002, 0.98255, 0.96921, 0.984, 0.8778, 0.011191, 0.0080309, 0.00022918, 0.0011823, 0.0011823, 0.0011823 + 202, 0.016882, 0.019063, 0.00066132, 0.98981, 0.96101, 0.98389, 0.87692, 0.011195, 0.0080267, 0.00022692, 0.0011646, 0.0011646, 0.0011646 + 203, 0.016872, 0.018726, 0.00076429, 0.98966, 0.96335, 0.98276, 0.87626, 0.011167, 0.0080001, 0.00022479, 0.0011478, 0.0011478, 0.0011478 + 204, 0.016651, 0.018769, 0.0006092, 0.99009, 0.9626, 0.98283, 0.8763, 0.011131, 0.0079802, 0.00022267, 0.0011319, 0.0011319, 0.0011319 + 205, 0.01662, 0.01884, 0.00059341, 0.98718, 0.96778, 0.98364, 0.87703, 0.01112, 0.0079666, 0.00021899, 0.0011169, 0.0011169, 0.0011169 + 206, 0.016774, 0.01897, 0.00063537, 0.99047, 0.96458, 0.98392, 0.8775, 0.011107, 0.0079398, 0.00021608, 0.0011028, 0.0011028, 0.0011028 + 207, 0.016793, 0.01869, 0.00064625, 0.98986, 0.96497, 0.98289, 0.87841, 0.011113, 0.0079292, 0.00021523, 0.0010896, 0.0010896, 0.0010896 + 208, 0.016658, 0.018585, 0.0006337, 0.98636, 0.96793, 0.98465, 0.87902, 0.011121, 0.0079266, 0.00021574, 0.0010773, 0.0010773, 0.0010773 + 209, 0.016901, 0.01854, 0.00063244, 0.98804, 0.96727, 0.98377, 0.87982, 0.01113, 0.0079317, 0.00021467, 0.0010659, 0.0010659, 0.0010659 + 210, 0.016524, 0.018967, 0.0005779, 0.9866, 0.96824, 0.9839, 0.87978, 0.011111, 0.0079161, 0.00021485, 0.0010554, 0.0010554, 0.0010554 + 211, 0.01659, 0.018561, 0.00055759, 0.98618, 0.96911, 0.98356, 0.87939, 0.011139, 0.0079216, 0.00021563, 0.0010458, 0.0010458, 0.0010458 + 212, 0.016639, 0.018768, 0.00059742, 0.98578, 0.96935, 0.98361, 0.88051, 0.011106, 0.0079018, 0.00021405, 0.0010371, 0.0010371, 0.0010371 + 213, 0.01675, 0.018693, 0.00056804, 0.98711, 0.96737, 0.98355, 0.8817, 0.011061, 0.0078661, 0.00021191, 0.0010293, 0.0010293, 0.0010293 + 214, 0.016292, 0.018032, 0.00055218, 0.9845, 0.96988, 0.98439, 0.88214, 0.01102, 0.0078358, 0.00021179, 0.0010225, 0.0010225, 0.0010225 + 215, 0.016503, 0.018604, 0.00058705, 0.98807, 0.9656, 0.9845, 0.88345, 0.010996, 0.0078223, 0.00020822, 0.0010165, 0.0010165, 0.0010165 + 216, 0.016233, 0.018145, 0.00057561, 0.9841, 0.96917, 0.98461, 0.88276, 0.010951, 0.0077978, 0.00020601, 0.0010115, 0.0010115, 0.0010115 + 217, 0.016624, 0.018502, 0.00057278, 0.99103, 0.96403, 0.98476, 0.88369, 0.010948, 0.007784, 0.00020389, 0.0010073, 0.0010073, 0.0010073 + 218, 0.01628, 0.018383, 0.00068041, 0.99197, 0.96331, 0.98484, 0.88328, 0.010915, 0.007759, 0.00020341, 0.0010041, 0.0010041, 0.0010041 + 219, 0.016333, 0.018647, 0.00075483, 0.99437, 0.96134, 0.98499, 0.88563, 0.010889, 0.00774, 0.0002034, 0.0010018, 0.0010018, 0.0010018 diff --git a/resources/yolo_models/2022-0304/results.png b/resources/yolo_models/2022-0304/results.png new file mode 100644 index 00000000..b65a1c62 Binary files /dev/null and b/resources/yolo_models/2022-0304/results.png differ diff --git a/resources/yolo_models/2022-0304/train_batch0.jpg b/resources/yolo_models/2022-0304/train_batch0.jpg new file mode 100644 index 00000000..fa2f82ec Binary files /dev/null and b/resources/yolo_models/2022-0304/train_batch0.jpg differ diff --git a/resources/yolo_models/2022-0304/train_batch1.jpg b/resources/yolo_models/2022-0304/train_batch1.jpg new file mode 100644 index 00000000..97df70dc Binary files /dev/null and b/resources/yolo_models/2022-0304/train_batch1.jpg differ diff --git a/resources/yolo_models/2022-0304/train_batch2.jpg b/resources/yolo_models/2022-0304/train_batch2.jpg new file mode 100644 index 00000000..7b96e94f Binary files /dev/null and b/resources/yolo_models/2022-0304/train_batch2.jpg differ diff --git a/resources/yolo_models/2022-0304/val_batch0_labels.jpg b/resources/yolo_models/2022-0304/val_batch0_labels.jpg new file mode 100644 index 00000000..920238d2 Binary files /dev/null and b/resources/yolo_models/2022-0304/val_batch0_labels.jpg differ diff --git a/resources/yolo_models/2022-0304/val_batch0_pred.jpg b/resources/yolo_models/2022-0304/val_batch0_pred.jpg new file mode 100644 index 00000000..85b7e693 Binary files /dev/null and b/resources/yolo_models/2022-0304/val_batch0_pred.jpg differ diff --git a/resources/yolo_models/2022-0304/val_batch1_labels.jpg b/resources/yolo_models/2022-0304/val_batch1_labels.jpg new file mode 100644 index 00000000..2747a1ba Binary files /dev/null and b/resources/yolo_models/2022-0304/val_batch1_labels.jpg differ diff --git a/resources/yolo_models/2022-0304/val_batch1_pred.jpg b/resources/yolo_models/2022-0304/val_batch1_pred.jpg new file mode 100644 index 00000000..80c0e589 Binary files /dev/null and b/resources/yolo_models/2022-0304/val_batch1_pred.jpg differ diff --git a/resources/yolo_models/2022-0304/val_batch2_labels.jpg b/resources/yolo_models/2022-0304/val_batch2_labels.jpg new file mode 100644 index 00000000..61c555e4 Binary files /dev/null and b/resources/yolo_models/2022-0304/val_batch2_labels.jpg differ diff --git a/resources/yolo_models/2022-0304/val_batch2_pred.jpg b/resources/yolo_models/2022-0304/val_batch2_pred.jpg new file mode 100644 index 00000000..506def45 Binary files /dev/null and b/resources/yolo_models/2022-0304/val_batch2_pred.jpg differ diff --git a/resources/yolo_models/2022-0304/weights/best.pt b/resources/yolo_models/2022-0304/weights/best.pt new file mode 100644 index 00000000..b73651c8 --- /dev/null +++ b/resources/yolo_models/2022-0304/weights/best.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2938fd4decdc4ae52c31710e6492d6359c0829f920821f26d5cdbd794991681e +size 173252189 diff --git a/resources/yolo_models/2022-0304/weights/last.pt b/resources/yolo_models/2022-0304/weights/last.pt new file mode 100644 index 00000000..b73651c8 --- /dev/null +++ b/resources/yolo_models/2022-0304/weights/last.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2938fd4decdc4ae52c31710e6492d6359c0829f920821f26d5cdbd794991681e +size 173252189 diff --git a/resources/yolo_models/2022-0511/F1_curve.png b/resources/yolo_models/2022-0511/F1_curve.png new file mode 100644 index 00000000..5eba0f49 Binary files /dev/null and b/resources/yolo_models/2022-0511/F1_curve.png differ diff --git a/resources/yolo_models/2022-0511/PR_curve.png b/resources/yolo_models/2022-0511/PR_curve.png new file mode 100644 index 00000000..e3a98589 Binary files /dev/null and b/resources/yolo_models/2022-0511/PR_curve.png differ diff --git a/resources/yolo_models/2022-0511/P_curve.png b/resources/yolo_models/2022-0511/P_curve.png new file mode 100644 index 00000000..b881b4ca Binary files /dev/null and b/resources/yolo_models/2022-0511/P_curve.png differ diff --git a/resources/yolo_models/2022-0511/R_curve.png b/resources/yolo_models/2022-0511/R_curve.png new file mode 100644 index 00000000..bb495402 Binary files /dev/null and b/resources/yolo_models/2022-0511/R_curve.png differ diff --git a/resources/yolo_models/2022-0511/confusion_matrix.png b/resources/yolo_models/2022-0511/confusion_matrix.png new file mode 100644 index 00000000..a505d861 Binary files /dev/null and b/resources/yolo_models/2022-0511/confusion_matrix.png differ diff --git a/resources/yolo_models/2022-0511/events.out.tfevents.1651812712.DESKTOP-T6806JH.15864.0 b/resources/yolo_models/2022-0511/events.out.tfevents.1651812712.DESKTOP-T6806JH.15864.0 new file mode 100644 index 00000000..2951a7e4 Binary files /dev/null and b/resources/yolo_models/2022-0511/events.out.tfevents.1651812712.DESKTOP-T6806JH.15864.0 differ diff --git a/resources/yolo_models/2022-0511/events.out.tfevents.1651852595.DESKTOP-T6806JH.18364.0 b/resources/yolo_models/2022-0511/events.out.tfevents.1651852595.DESKTOP-T6806JH.18364.0 new file mode 100644 index 00000000..62640a94 Binary files /dev/null and b/resources/yolo_models/2022-0511/events.out.tfevents.1651852595.DESKTOP-T6806JH.18364.0 differ diff --git a/resources/yolo_models/2022-0511/events.out.tfevents.1651882946.DESKTOP-T6806JH.14872.0 b/resources/yolo_models/2022-0511/events.out.tfevents.1651882946.DESKTOP-T6806JH.14872.0 new file mode 100644 index 00000000..0a98ddb8 Binary files /dev/null and b/resources/yolo_models/2022-0511/events.out.tfevents.1651882946.DESKTOP-T6806JH.14872.0 differ diff --git a/resources/yolo_models/2022-0511/events.out.tfevents.1651971357.DESKTOP-T6806JH.16356.0 b/resources/yolo_models/2022-0511/events.out.tfevents.1651971357.DESKTOP-T6806JH.16356.0 new file mode 100644 index 00000000..18cd22c4 Binary files /dev/null and b/resources/yolo_models/2022-0511/events.out.tfevents.1651971357.DESKTOP-T6806JH.16356.0 differ diff --git a/resources/yolo_models/2022-0511/hyp.yaml b/resources/yolo_models/2022-0511/hyp.yaml new file mode 100644 index 00000000..fa80eb95 --- /dev/null +++ b/resources/yolo_models/2022-0511/hyp.yaml @@ -0,0 +1,28 @@ +lr0: 0.01 +lrf: 0.01 +momentum: 0.937 +weight_decay: 0.0005 +warmup_epochs: 3.0 +warmup_momentum: 0.8 +warmup_bias_lr: 0.1 +box: 0.05 +cls: 0.5 +cls_pw: 1.0 +obj: 1.0 +obj_pw: 1.0 +iou_t: 0.2 +anchor_t: 4.0 +fl_gamma: 0.0 +hsv_h: 0.015 +hsv_s: 0.7 +hsv_v: 0.4 +degrees: 0.0 +translate: 0.1 +scale: 0.5 +shear: 0.0 +perspective: 0.0 +flipud: 0.0 +fliplr: 0.5 +mosaic: 1.0 +mixup: 0.0 +copy_paste: 0.0 diff --git a/resources/yolo_models/2022-0511/labels.jpg b/resources/yolo_models/2022-0511/labels.jpg new file mode 100644 index 00000000..bc69bf7f Binary files /dev/null and b/resources/yolo_models/2022-0511/labels.jpg differ diff --git a/resources/yolo_models/2022-0511/labels_correlogram.jpg b/resources/yolo_models/2022-0511/labels_correlogram.jpg new file mode 100644 index 00000000..2de070ea Binary files /dev/null and b/resources/yolo_models/2022-0511/labels_correlogram.jpg differ diff --git a/resources/yolo_models/2022-0511/opt.yaml b/resources/yolo_models/2022-0511/opt.yaml new file mode 100644 index 00000000..01fd54cb --- /dev/null +++ b/resources/yolo_models/2022-0511/opt.yaml @@ -0,0 +1,39 @@ +weights: .\runs\train\exp2\weights\last.pt +cfg: '' +data: 2022-0505data.yaml +hyp: data\hyps\hyp.scratch-low.yaml +epochs: 300 +batch_size: -1 +imgsz: 640 +rect: false +resume: true +nosave: false +noval: false +noautoanchor: false +noplots: false +evolve: null +bucket: '' +cache: null +image_weights: false +device: '' +multi_scale: false +single_cls: false +optimizer: SGD +sync_bn: false +workers: 8 +project: runs\train +name: exp +exist_ok: false +quad: false +cos_lr: false +label_smoothing: 0.0 +patience: 100 +freeze: +- 0 +save_period: -1 +local_rank: -1 +entity: null +upload_dataset: false +bbox_interval: -1 +artifact_alias: latest +save_dir: runs\train\exp2 diff --git a/resources/yolo_models/2022-0511/results.csv b/resources/yolo_models/2022-0511/results.csv new file mode 100644 index 00000000..26a33382 --- /dev/null +++ b/resources/yolo_models/2022-0511/results.csv @@ -0,0 +1,301 @@ + epoch, train/box_loss, train/obj_loss, train/cls_loss, metrics/precision, metrics/recall, metrics/mAP_0.5,metrics/mAP_0.5:0.95, val/box_loss, val/obj_loss, val/cls_loss, x/lr0, x/lr1, x/lr2 + 0, 0.075289, 0.055563, 0.038897, 0.48876, 0.49363, 0.37628, 0.15543, 0.055572, 0.027026, 0.01471, 0.0033266, 0.0033266, 0.07006 + 1, 0.057528, 0.045849, 0.013675, 0.61501, 0.52593, 0.49909, 0.22006, 0.048295, 0.02597, 0.0083195, 0.006638, 0.006638, 0.040038 + 2, 0.053913, 0.046407, 0.011522, 0.63831, 0.51246, 0.50974, 0.23721, 0.04576, 0.02862, 0.0076773, 0.0099274, 0.0099274, 0.0099943 + 3, 0.051698, 0.048201, 0.01149, 0.69576, 0.52959, 0.5563, 0.27214, 0.043252, 0.027577, 0.0064213, 0.009901, 0.009901, 0.009901 + 4, 0.049264, 0.048057, 0.009629, 0.73593, 0.58955, 0.64373, 0.32757, 0.041196, 0.025888, 0.0049208, 0.009901, 0.009901, 0.009901 + 5, 0.046713, 0.045939, 0.0078638, 0.67984, 0.70082, 0.70717, 0.37637, 0.038617, 0.024289, 0.0034447, 0.009868, 0.009868, 0.009868 + 6, 0.04499, 0.043502, 0.0066654, 0.7222, 0.70363, 0.73125, 0.38174, 0.037917, 0.023545, 0.0030777, 0.009835, 0.009835, 0.009835 + 7, 0.042946, 0.042344, 0.0057318, 0.75138, 0.71086, 0.75608, 0.40228, 0.036945, 0.022924, 0.0026239, 0.009802, 0.009802, 0.009802 + 8, 0.041652, 0.040727, 0.0050568, 0.7809, 0.74828, 0.79467, 0.41607, 0.036545, 0.022349, 0.0023353, 0.009769, 0.009769, 0.009769 + 9, 0.040813, 0.040741, 0.0045773, 0.79856, 0.78834, 0.83029, 0.4734, 0.033379, 0.021213, 0.0020541, 0.009736, 0.009736, 0.009736 + 10, 0.041083, 0.041058, 0.0052604, 0.7962, 0.75922, 0.81739, 0.4607, 0.034266, 0.021664, 0.002096, 0.009703, 0.009703, 0.009703 + 11, 0.040768, 0.041085, 0.0049124, 0.78141, 0.82247, 0.84758, 0.48808, 0.032769, 0.021033, 0.0017519, 0.00967, 0.00967, 0.00967 + 12, 0.039498, 0.039321, 0.0044201, 0.80186, 0.79868, 0.84223, 0.48662, 0.032828, 0.020619, 0.0018691, 0.009637, 0.009637, 0.009637 + 13, 0.03922, 0.039341, 0.0043987, 0.83579, 0.81413, 0.86387, 0.50455, 0.031397, 0.019654, 0.0015775, 0.009604, 0.009604, 0.009604 + 14, 0.03844, 0.039157, 0.0041344, 0.8251, 0.83762, 0.87896, 0.533, 0.030778, 0.019307, 0.0016935, 0.009571, 0.009571, 0.009571 + 15, 0.037953, 0.038184, 0.0040302, 0.86521, 0.84437, 0.89588, 0.54149, 0.030581, 0.018972, 0.0013933, 0.009538, 0.009538, 0.009538 + 16, 0.0374, 0.037255, 0.0037599, 0.8602, 0.83971, 0.89342, 0.54845, 0.029695, 0.01891, 0.0013952, 0.009505, 0.009505, 0.009505 + 17, 0.03725, 0.037259, 0.003742, 0.85091, 0.85331, 0.89709, 0.55192, 0.02963, 0.018456, 0.0013606, 0.009472, 0.009472, 0.009472 + 18, 0.0369, 0.036506, 0.0036274, 0.83897, 0.86638, 0.90644, 0.56167, 0.029292, 0.018183, 0.0012737, 0.009439, 0.009439, 0.009439 + 19, 0.036575, 0.036217, 0.0036832, 0.88948, 0.85224, 0.90809, 0.57857, 0.02848, 0.017978, 0.0011434, 0.009406, 0.009406, 0.009406 + 20, 0.035466, 0.036221, 0.0032358, 0.86946, 0.86761, 0.91385, 0.57442, 0.027925, 0.017371, 0.0010957, 0.009373, 0.009373, 0.009373 + 21, 0.034481, 0.034404, 0.0029141, 0.88226, 0.88346, 0.9258, 0.59619, 0.028257, 0.017267, 0.0010747, 0.00934, 0.00934, 0.00934 + 22, 0.034084, 0.033822, 0.0027446, 0.87302, 0.88881, 0.92168, 0.60202, 0.02701, 0.016799, 0.0011182, 0.009307, 0.009307, 0.009307 + 23, 0.033292, 0.0332, 0.0026102, 0.89931, 0.88569, 0.93121, 0.61184, 0.027021, 0.01636, 0.0011162, 0.009274, 0.009274, 0.009274 + 24, 0.033044, 0.033282, 0.0024352, 0.89268, 0.88853, 0.93095, 0.62439, 0.025994, 0.016199, 0.00096382, 0.009241, 0.009241, 0.009241 + 25, 0.033045, 0.032952, 0.0025773, 0.9007, 0.9085, 0.94239, 0.6365, 0.025478, 0.015965, 0.0010392, 0.009208, 0.009208, 0.009208 + 26, 0.032762, 0.033161, 0.0025749, 0.91456, 0.89611, 0.94054, 0.62406, 0.025547, 0.015907, 0.00093029, 0.009175, 0.009175, 0.009175 + 27, 0.032301, 0.032197, 0.0023711, 0.8952, 0.91187, 0.94405, 0.65218, 0.024962, 0.015601, 0.00094709, 0.009142, 0.009142, 0.009142 + 28, 0.031897, 0.032099, 0.0024198, 0.89098, 0.90659, 0.93851, 0.64182, 0.024882, 0.015715, 0.00099415, 0.009109, 0.009109, 0.009109 + 29, 0.031612, 0.032126, 0.002368, 0.90249, 0.91021, 0.94441, 0.65882, 0.024454, 0.015254, 0.0010035, 0.009076, 0.009076, 0.009076 + 30, 0.031325, 0.031518, 0.0022345, 0.93143, 0.89837, 0.95291, 0.66471, 0.024068, 0.015184, 0.00091862, 0.009043, 0.009043, 0.009043 + 31, 0.031196, 0.031018, 0.0021695, 0.90191, 0.92308, 0.95259, 0.66597, 0.023934, 0.015055, 0.00090138, 0.00901, 0.00901, 0.00901 + 32, 0.031101, 0.030856, 0.0022075, 0.9064, 0.91927, 0.95342, 0.67109, 0.02394, 0.014839, 0.00088151, 0.008977, 0.008977, 0.008977 + 33, 0.030991, 0.030915, 0.0022547, 0.92455, 0.90931, 0.951, 0.67155, 0.02362, 0.014705, 0.00083384, 0.008944, 0.008944, 0.008944 + 34, 0.03069, 0.030299, 0.0021701, 0.91322, 0.9194, 0.95432, 0.68446, 0.023146, 0.014758, 0.00087608, 0.008911, 0.008911, 0.008911 + 35, 0.031472, 0.03208, 0.0026285, 0.92256, 0.90595, 0.9542, 0.67713, 0.023277, 0.014772, 0.00083798, 0.008878, 0.008878, 0.008878 + 36, 0.031341, 0.031568, 0.0026042, 0.90628, 0.90565, 0.94183, 0.67116, 0.023183, 0.014647, 0.00086794, 0.008845, 0.008845, 0.008845 + 37, 0.031172, 0.031466, 0.0027305, 0.91707, 0.91591, 0.95597, 0.68141, 0.023231, 0.014664, 0.0008813, 0.008812, 0.008812, 0.008812 + 38, 0.031006, 0.031565, 0.0024893, 0.92122, 0.92003, 0.9581, 0.68917, 0.023241, 0.014471, 0.00083446, 0.008779, 0.008779, 0.008779 + 39, 0.030651, 0.03136, 0.0024461, 0.92723, 0.90745, 0.95571, 0.68828, 0.022802, 0.014334, 0.00078887, 0.008746, 0.008746, 0.008746 + 40, 0.030718, 0.031026, 0.0024097, 0.92776, 0.91734, 0.95772, 0.69675, 0.022672, 0.014249, 0.00084133, 0.008713, 0.008713, 0.008713 + 41, 0.03045, 0.031346, 0.002292, 0.92457, 0.93378, 0.9638, 0.70423, 0.022142, 0.013906, 0.00080433, 0.00868, 0.00868, 0.00868 + 42, 0.03019, 0.030744, 0.0022393, 0.92849, 0.92605, 0.95945, 0.70674, 0.021859, 0.013808, 0.00080769, 0.008647, 0.008647, 0.008647 + 43, 0.029585, 0.030251, 0.0023529, 0.92056, 0.92346, 0.95952, 0.7144, 0.021535, 0.013672, 0.00079072, 0.008614, 0.008614, 0.008614 + 44, 0.029832, 0.030515, 0.0023497, 0.94133, 0.9223, 0.96211, 0.70843, 0.021611, 0.013643, 0.0008194, 0.008581, 0.008581, 0.008581 + 45, 0.029479, 0.030447, 0.0022771, 0.93235, 0.92923, 0.96375, 0.71777, 0.021254, 0.013569, 0.00079741, 0.008548, 0.008548, 0.008548 + 46, 0.029259, 0.030306, 0.0022378, 0.94114, 0.92071, 0.96368, 0.715, 0.021364, 0.013553, 0.00072963, 0.008515, 0.008515, 0.008515 + 47, 0.02914, 0.029875, 0.0021663, 0.94788, 0.92289, 0.96832, 0.72923, 0.020702, 0.013108, 0.00071485, 0.008482, 0.008482, 0.008482 + 48, 0.028839, 0.029733, 0.0021264, 0.93745, 0.91978, 0.96609, 0.7282, 0.020683, 0.013335, 0.00072117, 0.008449, 0.008449, 0.008449 + 49, 0.028794, 0.029626, 0.0019662, 0.93737, 0.92976, 0.967, 0.73571, 0.020251, 0.012965, 0.00070631, 0.008416, 0.008416, 0.008416 + 50, 0.02883, 0.029193, 0.0020481, 0.94991, 0.92798, 0.97028, 0.73197, 0.020337, 0.012854, 0.00073176, 0.008383, 0.008383, 0.008383 + 51, 0.028502, 0.028937, 0.0020172, 0.9304, 0.94529, 0.96763, 0.74168, 0.01993, 0.012834, 0.0006967, 0.00835, 0.00835, 0.00835 + 52, 0.028634, 0.028949, 0.002208, 0.93606, 0.93735, 0.97081, 0.74552, 0.019929, 0.012751, 0.00070728, 0.008317, 0.008317, 0.008317 + 53, 0.02845, 0.028692, 0.0019738, 0.93008, 0.94611, 0.97249, 0.74747, 0.019668, 0.012694, 0.00069503, 0.008284, 0.008284, 0.008284 + 54, 0.027999, 0.028448, 0.0019722, 0.93412, 0.94271, 0.97081, 0.74481, 0.019655, 0.01266, 0.00072018, 0.008251, 0.008251, 0.008251 + 55, 0.028231, 0.028972, 0.002119, 0.9538, 0.93214, 0.97282, 0.75254, 0.01944, 0.012449, 0.00069856, 0.008218, 0.008218, 0.008218 + 56, 0.02801, 0.028676, 0.002039, 0.94615, 0.9352, 0.97358, 0.75077, 0.019346, 0.012484, 0.00065669, 0.008185, 0.008185, 0.008185 + 57, 0.02791, 0.028551, 0.0018839, 0.94028, 0.93997, 0.97201, 0.75747, 0.019044, 0.012347, 0.00067728, 0.008152, 0.008152, 0.008152 + 58, 0.027718, 0.028522, 0.0020063, 0.93848, 0.94443, 0.97384, 0.75875, 0.019013, 0.012189, 0.00069735, 0.008119, 0.008119, 0.008119 + 59, 0.027618, 0.028005, 0.0019782, 0.94555, 0.9441, 0.97545, 0.76351, 0.018683, 0.012098, 0.00066009, 0.008086, 0.008086, 0.008086 + 60, 0.027477, 0.027748, 0.0019781, 0.95693, 0.93663, 0.97587, 0.76648, 0.018832, 0.012113, 0.00066221, 0.008053, 0.008053, 0.008053 + 61, 0.027272, 0.028127, 0.0018422, 0.93565, 0.95236, 0.97516, 0.76227, 0.018958, 0.012099, 0.00064292, 0.00802, 0.00802, 0.00802 + 62, 0.026854, 0.027103, 0.0017837, 0.95446, 0.94178, 0.97656, 0.76849, 0.01863, 0.012037, 0.00065746, 0.007987, 0.007987, 0.007987 + 63, 0.026795, 0.027309, 0.0018056, 0.94677, 0.94775, 0.97773, 0.76904, 0.018473, 0.011934, 0.00063528, 0.007954, 0.007954, 0.007954 + 64, 0.026676, 0.02733, 0.001886, 0.94242, 0.94791, 0.97658, 0.77652, 0.018157, 0.011829, 0.00062398, 0.007921, 0.007921, 0.007921 + 65, 0.026669, 0.027071, 0.0017599, 0.94378, 0.95306, 0.97775, 0.78133, 0.017959, 0.011741, 0.00061136, 0.007888, 0.007888, 0.007888 + 66, 0.026752, 0.027459, 0.0018991, 0.95839, 0.93498, 0.97745, 0.77998, 0.018083, 0.011733, 0.00060298, 0.007855, 0.007855, 0.007855 + 67, 0.026452, 0.027202, 0.0018665, 0.93991, 0.9541, 0.97827, 0.78273, 0.017794, 0.011567, 0.00063729, 0.007822, 0.007822, 0.007822 + 68, 0.026445, 0.026947, 0.0017429, 0.94518, 0.94986, 0.97652, 0.78365, 0.017531, 0.01149, 0.00062337, 0.007789, 0.007789, 0.007789 + 69, 0.026183, 0.026758, 0.0018381, 0.95426, 0.94968, 0.97792, 0.78596, 0.017626, 0.011535, 0.00061719, 0.007756, 0.007756, 0.007756 + 70, 0.026296, 0.02695, 0.0017451, 0.95838, 0.94702, 0.97897, 0.78719, 0.017612, 0.011453, 0.00058959, 0.007723, 0.007723, 0.007723 + 71, 0.026139, 0.027159, 0.0018074, 0.95866, 0.94284, 0.97833, 0.78869, 0.017404, 0.011485, 0.00061503, 0.00769, 0.00769, 0.00769 + 72, 0.025948, 0.026602, 0.0017427, 0.95661, 0.94899, 0.97977, 0.7942, 0.017248, 0.011307, 0.00062087, 0.007657, 0.007657, 0.007657 + 73, 0.026131, 0.026338, 0.001787, 0.95123, 0.95247, 0.98024, 0.79505, 0.016961, 0.011197, 0.00060756, 0.007624, 0.007624, 0.007624 + 74, 0.025946, 0.026378, 0.0016395, 0.95223, 0.95627, 0.98214, 0.79723, 0.016928, 0.011079, 0.0006078, 0.007591, 0.007591, 0.007591 + 75, 0.025771, 0.026055, 0.0015899, 0.95351, 0.95148, 0.98235, 0.80044, 0.016855, 0.011088, 0.00060061, 0.007558, 0.007558, 0.007558 + 76, 0.025522, 0.026277, 0.0016458, 0.95718, 0.95173, 0.98142, 0.80252, 0.01677, 0.011051, 0.00058844, 0.007525, 0.007525, 0.007525 + 77, 0.025328, 0.026226, 0.0015823, 0.94742, 0.95781, 0.98121, 0.8051, 0.016591, 0.010919, 0.00058592, 0.007492, 0.007492, 0.007492 + 78, 0.025156, 0.026273, 0.0016501, 0.95841, 0.95238, 0.98208, 0.80895, 0.01643, 0.010791, 0.0005594, 0.007459, 0.007459, 0.007459 + 79, 0.025241, 0.026112, 0.0016233, 0.96189, 0.9502, 0.98257, 0.80873, 0.016384, 0.010795, 0.00055782, 0.007426, 0.007426, 0.007426 + 80, 0.025364, 0.026219, 0.0015652, 0.96341, 0.94958, 0.98218, 0.80966, 0.016301, 0.010772, 0.00055717, 0.007393, 0.007393, 0.007393 + 81, 0.025102, 0.025741, 0.0015624, 0.96512, 0.94662, 0.98256, 0.81184, 0.016121, 0.010663, 0.00057043, 0.00736, 0.00736, 0.00736 + 82, 0.025066, 0.025939, 0.0016756, 0.95965, 0.95294, 0.98258, 0.80811, 0.016232, 0.010678, 0.00055059, 0.007327, 0.007327, 0.007327 + 83, 0.025098, 0.026079, 0.0016374, 0.94953, 0.96494, 0.98206, 0.81185, 0.016182, 0.010626, 0.00054979, 0.007294, 0.007294, 0.007294 + 84, 0.025307, 0.02555, 0.0015858, 0.95945, 0.95056, 0.98245, 0.81487, 0.016062, 0.010608, 0.00054389, 0.007261, 0.007261, 0.007261 + 85, 0.024963, 0.025658, 0.0015594, 0.96508, 0.94624, 0.98204, 0.81521, 0.015942, 0.010544, 0.00054245, 0.007228, 0.007228, 0.007228 + 86, 0.024738, 0.025578, 0.0015631, 0.96585, 0.94787, 0.98312, 0.81706, 0.015847, 0.010422, 0.00054366, 0.007195, 0.007195, 0.007195 + 87, 0.024777, 0.025469, 0.0016502, 0.96079, 0.9509, 0.98245, 0.82035, 0.015711, 0.010448, 0.00056842, 0.007162, 0.007162, 0.007162 + 88, 0.024534, 0.025577, 0.001509, 0.96495, 0.95044, 0.98313, 0.82101, 0.015547, 0.010367, 0.00054738, 0.007129, 0.007129, 0.007129 + 89, 0.02462, 0.025217, 0.0015192, 0.95922, 0.95935, 0.98391, 0.82316, 0.015611, 0.010324, 0.00054754, 0.007096, 0.007096, 0.007096 + 90, 0.024263, 0.02476, 0.0015961, 0.96315, 0.95659, 0.98371, 0.8257, 0.015374, 0.010229, 0.00052993, 0.007063, 0.007063, 0.007063 + 91, 0.024313, 0.025067, 0.0016208, 0.959, 0.962, 0.98372, 0.82494, 0.015343, 0.010147, 0.0005155, 0.00703, 0.00703, 0.00703 + 92, 0.024287, 0.024888, 0.0014992, 0.96714, 0.9555, 0.98431, 0.82816, 0.015311, 0.010142, 0.00051631, 0.006997, 0.006997, 0.006997 + 93, 0.024313, 0.024822, 0.00157, 0.9723, 0.9512, 0.9839, 0.82599, 0.015371, 0.010153, 0.00051677, 0.006964, 0.006964, 0.006964 + 94, 0.024204, 0.025103, 0.0015163, 0.96466, 0.95492, 0.9838, 0.82784, 0.01518, 0.010037, 0.00050873, 0.006931, 0.006931, 0.006931 + 95, 0.023964, 0.02517, 0.0014256, 0.96215, 0.95864, 0.98517, 0.83108, 0.015043, 0.0099739, 0.0005147, 0.006898, 0.006898, 0.006898 + 96, 0.024035, 0.024429, 0.0015627, 0.9536, 0.96587, 0.98478, 0.83409, 0.014887, 0.0099596, 0.00052578, 0.006865, 0.006865, 0.006865 + 97, 0.023831, 0.024195, 0.0015414, 0.96663, 0.9572, 0.98546, 0.83671, 0.014811, 0.0098804, 0.00052458, 0.006832, 0.006832, 0.006832 + 98, 0.024008, 0.024514, 0.0015326, 0.96056, 0.96615, 0.98617, 0.83513, 0.01472, 0.0098712, 0.00050521, 0.006799, 0.006799, 0.006799 + 99, 0.023706, 0.024756, 0.0014909, 0.97094, 0.95608, 0.98621, 0.83753, 0.014687, 0.0098626, 0.00049588, 0.006766, 0.006766, 0.006766 + 100, 0.023907, 0.024382, 0.0015065, 0.96321, 0.96567, 0.98629, 0.84091, 0.014541, 0.0097417, 0.00049724, 0.006733, 0.006733, 0.006733 + 101, 0.023641, 0.024268, 0.0014112, 0.96255, 0.96617, 0.98608, 0.84128, 0.014561, 0.009714, 0.00048432, 0.0067, 0.0067, 0.0067 + 102, 0.023665, 0.024303, 0.0013884, 0.96687, 0.95798, 0.98651, 0.84166, 0.014446, 0.0096477, 0.00049861, 0.006667, 0.006667, 0.006667 + 103, 0.02363, 0.024402, 0.001433, 0.9655, 0.96116, 0.9864, 0.84066, 0.014366, 0.0096386, 0.00049894, 0.006634, 0.006634, 0.006634 + 104, 0.023239, 0.023596, 0.0014313, 0.9695, 0.9539, 0.98613, 0.84119, 0.014359, 0.0096064, 0.00050387, 0.006601, 0.006601, 0.006601 + 105, 0.023251, 0.023953, 0.0014089, 0.96497, 0.95889, 0.98639, 0.84321, 0.014316, 0.0095654, 0.00049736, 0.006568, 0.006568, 0.006568 + 106, 0.023232, 0.024043, 0.0015065, 0.96898, 0.9584, 0.98665, 0.84439, 0.014218, 0.0094997, 0.00048965, 0.006535, 0.006535, 0.006535 + 107, 0.023279, 0.024047, 0.0014473, 0.9715, 0.95723, 0.98705, 0.8457, 0.014164, 0.0094639, 0.00047924, 0.006502, 0.006502, 0.006502 + 108, 0.022985, 0.024089, 0.0013886, 0.96856, 0.9642, 0.98729, 0.84684, 0.014103, 0.0094269, 0.00048047, 0.006469, 0.006469, 0.006469 + 109, 0.023345, 0.023897, 0.0014193, 0.96919, 0.96274, 0.98751, 0.84827, 0.013989, 0.0093805, 0.00048587, 0.006436, 0.006436, 0.006436 + 110, 0.023078, 0.023864, 0.0013398, 0.96783, 0.96408, 0.98761, 0.84959, 0.013848, 0.0093386, 0.00048614, 0.006403, 0.006403, 0.006403 + 111, 0.022953, 0.023852, 0.0013963, 0.96938, 0.96371, 0.98758, 0.85011, 0.01381, 0.00931, 0.00048284, 0.00637, 0.00637, 0.00637 + 112, 0.02259, 0.023385, 0.0012704, 0.96821, 0.96436, 0.98768, 0.85199, 0.013777, 0.0092699, 0.00048212, 0.006337, 0.006337, 0.006337 + 113, 0.022478, 0.023199, 0.0012602, 0.96935, 0.96343, 0.98766, 0.85229, 0.013747, 0.009248, 0.00047525, 0.006304, 0.006304, 0.006304 + 114, 0.022635, 0.023483, 0.0014193, 0.96507, 0.96976, 0.98783, 0.85486, 0.013654, 0.0091906, 0.00047089, 0.006271, 0.006271, 0.006271 + 115, 0.022739, 0.023493, 0.0013457, 0.96548, 0.97087, 0.98819, 0.8569, 0.013567, 0.0091283, 0.00047017, 0.006238, 0.006238, 0.006238 + 116, 0.02261, 0.023117, 0.0012806, 0.97671, 0.95999, 0.98807, 0.85746, 0.013551, 0.0091117, 0.00046827, 0.006205, 0.006205, 0.006205 + 117, 0.022566, 0.023174, 0.001329, 0.97142, 0.96507, 0.98833, 0.85756, 0.013505, 0.0090716, 0.00046304, 0.006172, 0.006172, 0.006172 + 118, 0.022221, 0.022469, 0.0012919, 0.96899, 0.96806, 0.98849, 0.85969, 0.01339, 0.009013, 0.00045994, 0.006139, 0.006139, 0.006139 + 119, 0.022586, 0.023113, 0.0013339, 0.96736, 0.97059, 0.98861, 0.86088, 0.013304, 0.0090077, 0.00045846, 0.006106, 0.006106, 0.006106 + 120, 0.022394, 0.02285, 0.0013081, 0.9697, 0.96826, 0.98768, 0.86146, 0.013217, 0.0089704, 0.0004609, 0.006073, 0.006073, 0.006073 + 121, 0.022118, 0.022962, 0.0013344, 0.97259, 0.96549, 0.98773, 0.86404, 0.013171, 0.0089302, 0.00046148, 0.00604, 0.00604, 0.00604 + 122, 0.022111, 0.023073, 0.0012941, 0.96896, 0.97042, 0.98845, 0.86503, 0.013139, 0.0088915, 0.00046585, 0.006007, 0.006007, 0.006007 + 123, 0.022175, 0.022785, 0.0012751, 0.97673, 0.96413, 0.98875, 0.86621, 0.013074, 0.0088533, 0.00046526, 0.005974, 0.005974, 0.005974 + 124, 0.022162, 0.022835, 0.0012577, 0.97499, 0.96655, 0.98883, 0.86769, 0.012985, 0.008829, 0.00045945, 0.005941, 0.005941, 0.005941 + 125, 0.022058, 0.022554, 0.0013371, 0.97452, 0.9674, 0.98897, 0.86794, 0.01293, 0.008779, 0.00045944, 0.005908, 0.005908, 0.005908 + 126, 0.021823, 0.022685, 0.0011872, 0.97667, 0.96753, 0.98892, 0.86936, 0.012876, 0.0087288, 0.00045692, 0.005875, 0.005875, 0.005875 + 127, 0.022131, 0.022649, 0.0012419, 0.97447, 0.96931, 0.98914, 0.86974, 0.012812, 0.0086909, 0.00045237, 0.005842, 0.005842, 0.005842 + 128, 0.021913, 0.022391, 0.0012528, 0.97706, 0.96741, 0.98923, 0.87069, 0.01275, 0.0086709, 0.00044901, 0.005809, 0.005809, 0.005809 + 129, 0.02193, 0.022548, 0.0013065, 0.97647, 0.96835, 0.98939, 0.87122, 0.012743, 0.0086359, 0.00045057, 0.005776, 0.005776, 0.005776 + 130, 0.022004, 0.023005, 0.0014073, 0.97785, 0.96697, 0.9894, 0.87268, 0.012681, 0.0086065, 0.00044695, 0.005743, 0.005743, 0.005743 + 131, 0.021684, 0.022713, 0.00127, 0.97787, 0.96832, 0.98955, 0.87375, 0.012634, 0.0085898, 0.00044463, 0.00571, 0.00571, 0.00571 + 132, 0.021507, 0.022161, 0.0012103, 0.97886, 0.96867, 0.98961, 0.8749, 0.012581, 0.0085623, 0.00043866, 0.005677, 0.005677, 0.005677 + 133, 0.021404, 0.022285, 0.0011403, 0.97614, 0.97047, 0.98962, 0.87662, 0.012546, 0.0085402, 0.00043569, 0.005644, 0.005644, 0.005644 + 134, 0.021545, 0.022522, 0.0013429, 0.97704, 0.97076, 0.98968, 0.87567, 0.012503, 0.0085173, 0.00043703, 0.005611, 0.005611, 0.005611 + 135, 0.021381, 0.021935, 0.0011697, 0.98079, 0.96676, 0.98975, 0.87629, 0.012467, 0.0085016, 0.0004329, 0.005578, 0.005578, 0.005578 + 136, 0.021289, 0.022137, 0.0011945, 0.9756, 0.97399, 0.98986, 0.87722, 0.012418, 0.0084706, 0.00043115, 0.005545, 0.005545, 0.005545 + 137, 0.021311, 0.022155, 0.0011665, 0.97837, 0.97121, 0.98986, 0.87671, 0.012343, 0.0084323, 0.00042935, 0.005512, 0.005512, 0.005512 + 138, 0.021454, 0.022303, 0.0011969, 0.982, 0.96741, 0.98994, 0.87842, 0.012292, 0.0083987, 0.00043043, 0.005479, 0.005479, 0.005479 + 139, 0.021094, 0.022176, 0.0011853, 0.97374, 0.97604, 0.98999, 0.87878, 0.012268, 0.0083704, 0.00042934, 0.005446, 0.005446, 0.005446 + 140, 0.021347, 0.021849, 0.0012133, 0.98142, 0.96875, 0.99002, 0.87978, 0.012219, 0.0083272, 0.00042642, 0.005413, 0.005413, 0.005413 + 141, 0.021043, 0.022055, 0.00117, 0.97632, 0.97321, 0.99014, 0.88034, 0.012178, 0.0082924, 0.0004268, 0.00538, 0.00538, 0.00538 + 142, 0.021031, 0.021473, 0.001137, 0.98206, 0.9679, 0.99024, 0.88124, 0.012132, 0.0082581, 0.00042656, 0.005347, 0.005347, 0.005347 + 143, 0.020867, 0.021813, 0.0012648, 0.98234, 0.9682, 0.99028, 0.88295, 0.012068, 0.0082188, 0.00042581, 0.005314, 0.005314, 0.005314 + 144, 0.020648, 0.021622, 0.0011738, 0.98022, 0.96921, 0.99035, 0.88413, 0.012012, 0.008178, 0.00042579, 0.005281, 0.005281, 0.005281 + 145, 0.020795, 0.021387, 0.0011528, 0.97571, 0.97382, 0.99045, 0.88472, 0.011959, 0.0081503, 0.000425, 0.005248, 0.005248, 0.005248 + 146, 0.020783, 0.021582, 0.0011592, 0.97573, 0.97435, 0.99049, 0.8856, 0.011908, 0.0081222, 0.00042244, 0.005215, 0.005215, 0.005215 + 147, 0.020924, 0.021382, 0.0012089, 0.97353, 0.97617, 0.99051, 0.88642, 0.011855, 0.0080972, 0.00042092, 0.005182, 0.005182, 0.005182 + 148, 0.020849, 0.021737, 0.0011871, 0.97524, 0.97578, 0.99052, 0.88767, 0.011813, 0.0080764, 0.00041955, 0.005149, 0.005149, 0.005149 + 149, 0.020944, 0.021395, 0.0011882, 0.97633, 0.97475, 0.99054, 0.88838, 0.011769, 0.0080516, 0.00041741, 0.005116, 0.005116, 0.005116 + 150, 0.020569, 0.021167, 0.0010766, 0.98212, 0.96971, 0.99067, 0.88927, 0.011714, 0.0080222, 0.00041562, 0.005083, 0.005083, 0.005083 + 151, 0.020569, 0.021415, 0.0011629, 0.98097, 0.97013, 0.99073, 0.89027, 0.011691, 0.0080033, 0.00041546, 0.00505, 0.00505, 0.00505 + 152, 0.020561, 0.021204, 0.0011685, 0.98352, 0.96794, 0.99081, 0.89059, 0.011657, 0.0079818, 0.00041406, 0.005017, 0.005017, 0.005017 + 153, 0.02041, 0.020965, 0.0011309, 0.98326, 0.96793, 0.99077, 0.89169, 0.011623, 0.0079532, 0.00041232, 0.004984, 0.004984, 0.004984 + 154, 0.020428, 0.021023, 0.0010722, 0.98514, 0.96689, 0.9909, 0.89241, 0.01158, 0.0079306, 0.00040974, 0.004951, 0.004951, 0.004951 + 155, 0.020527, 0.021216, 0.0010864, 0.98405, 0.96848, 0.99098, 0.89272, 0.011544, 0.0079075, 0.00040793, 0.004918, 0.004918, 0.004918 + 156, 0.020385, 0.021288, 0.0011546, 0.98081, 0.97171, 0.99102, 0.89385, 0.011511, 0.0078842, 0.00040697, 0.004885, 0.004885, 0.004885 + 157, 0.02033, 0.021061, 0.0010763, 0.9784, 0.97487, 0.99088, 0.89382, 0.011479, 0.0078601, 0.0004055, 0.004852, 0.004852, 0.004852 + 158, 0.020084, 0.020718, 0.0010387, 0.97753, 0.97626, 0.99094, 0.89424, 0.011452, 0.0078369, 0.00040388, 0.004819, 0.004819, 0.004819 + 159, 0.020005, 0.021096, 0.001055, 0.97809, 0.97581, 0.99098, 0.89512, 0.011417, 0.00781, 0.00040296, 0.004786, 0.004786, 0.004786 + 160, 0.020077, 0.020607, 0.0010582, 0.97774, 0.97638, 0.991, 0.89563, 0.011385, 0.0077854, 0.0004016, 0.004753, 0.004753, 0.004753 + 161, 0.019961, 0.020843, 0.001018, 0.9753, 0.97949, 0.99105, 0.89623, 0.011352, 0.0077646, 0.00039944, 0.00472, 0.00472, 0.00472 + 162, 0.019777, 0.020821, 0.00099026, 0.9754, 0.97982, 0.9911, 0.89712, 0.011319, 0.0077429, 0.0003977, 0.004687, 0.004687, 0.004687 + 163, 0.019778, 0.020919, 0.0010967, 0.97496, 0.98001, 0.99113, 0.89816, 0.011291, 0.0077235, 0.00039636, 0.004654, 0.004654, 0.004654 + 164, 0.019937, 0.020575, 0.0010588, 0.97629, 0.97957, 0.99114, 0.89859, 0.011263, 0.0077051, 0.00039467, 0.004621, 0.004621, 0.004621 + 165, 0.019622, 0.020698, 0.00098791, 0.9773, 0.98002, 0.99121, 0.89916, 0.011221, 0.0076892, 0.00039329, 0.004588, 0.004588, 0.004588 + 166, 0.019822, 0.020362, 0.0010488, 0.98032, 0.97635, 0.99122, 0.90014, 0.011199, 0.0076735, 0.00039283, 0.004555, 0.004555, 0.004555 + 167, 0.019432, 0.020426, 0.0010363, 0.97955, 0.97747, 0.99129, 0.9007, 0.011175, 0.0076521, 0.00039025, 0.004522, 0.004522, 0.004522 + 168, 0.019439, 0.020085, 0.0010052, 0.98116, 0.97656, 0.99139, 0.90137, 0.011151, 0.0076295, 0.00038849, 0.004489, 0.004489, 0.004489 + 169, 0.01952, 0.020088, 0.0010564, 0.98283, 0.97514, 0.99144, 0.90187, 0.011122, 0.0076066, 0.00038761, 0.004456, 0.004456, 0.004456 + 170, 0.019217, 0.020009, 0.0010266, 0.98153, 0.97674, 0.9915, 0.9021, 0.011093, 0.0075861, 0.0003869, 0.004423, 0.004423, 0.004423 + 171, 0.019263, 0.020343, 0.0009391, 0.98249, 0.97621, 0.99153, 0.90253, 0.011056, 0.0075626, 0.00038608, 0.00439, 0.00439, 0.00439 + 172, 0.019327, 0.019828, 0.00097095, 0.98256, 0.97575, 0.99155, 0.90318, 0.01102, 0.0075403, 0.00038554, 0.004357, 0.004357, 0.004357 + 173, 0.019121, 0.020083, 0.00097555, 0.98134, 0.97666, 0.99154, 0.90318, 0.010988, 0.0075194, 0.00038494, 0.004324, 0.004324, 0.004324 + 174, 0.019172, 0.019805, 0.00095488, 0.98244, 0.97635, 0.99158, 0.90328, 0.010953, 0.0075, 0.00038383, 0.004291, 0.004291, 0.004291 + 175, 0.018866, 0.019613, 0.0010044, 0.98305, 0.97578, 0.99158, 0.90417, 0.01092, 0.0074794, 0.00038335, 0.004258, 0.004258, 0.004258 + 176, 0.018943, 0.019886, 0.00095287, 0.98228, 0.97697, 0.99159, 0.90434, 0.010888, 0.0074599, 0.00038327, 0.004225, 0.004225, 0.004225 + 177, 0.018871, 0.019406, 0.0008985, 0.98324, 0.97615, 0.99161, 0.90479, 0.010859, 0.0074366, 0.00038284, 0.004192, 0.004192, 0.004192 + 178, 0.018956, 0.019353, 0.00090128, 0.98363, 0.97614, 0.99164, 0.90557, 0.010828, 0.007413, 0.00038215, 0.004159, 0.004159, 0.004159 + 179, 0.018806, 0.019282, 0.00094334, 0.98369, 0.97665, 0.99161, 0.90597, 0.010799, 0.0073909, 0.00038107, 0.004126, 0.004126, 0.004126 + 180, 0.018864, 0.019378, 0.0009804, 0.98353, 0.97675, 0.99186, 0.90641, 0.010772, 0.0073726, 0.00037981, 0.004093, 0.004093, 0.004093 + 181, 0.018573, 0.018915, 0.0009248, 0.98313, 0.97726, 0.99168, 0.90669, 0.010747, 0.0073552, 0.00037852, 0.00406, 0.00406, 0.00406 + 182, 0.01874, 0.019464, 0.0009175, 0.98301, 0.97736, 0.9917, 0.9073, 0.010718, 0.0073376, 0.0003768, 0.004027, 0.004027, 0.004027 + 183, 0.018659, 0.019182, 0.00090147, 0.98013, 0.98062, 0.99175, 0.90716, 0.010699, 0.0073226, 0.00037565, 0.003994, 0.003994, 0.003994 + 184, 0.018622, 0.019033, 0.00089413, 0.9834, 0.9775, 0.9919, 0.90774, 0.010674, 0.0073066, 0.00037482, 0.003961, 0.003961, 0.003961 + 185, 0.018573, 0.01912, 0.00087475, 0.97969, 0.98057, 0.9918, 0.90834, 0.010649, 0.0072896, 0.00037371, 0.003928, 0.003928, 0.003928 + 186, 0.018434, 0.019032, 0.00086863, 0.97994, 0.98059, 0.99184, 0.90875, 0.010624, 0.0072742, 0.00037258, 0.003895, 0.003895, 0.003895 + 187, 0.018453, 0.018946, 0.00088231, 0.98032, 0.98086, 0.99188, 0.909, 0.0106, 0.0072582, 0.00037157, 0.003862, 0.003862, 0.003862 + 188, 0.018477, 0.019185, 0.0008247, 0.98026, 0.98077, 0.99191, 0.90965, 0.01058, 0.0072442, 0.00037038, 0.003829, 0.003829, 0.003829 + 189, 0.018542, 0.019077, 0.00088285, 0.98976, 0.97156, 0.99192, 0.91022, 0.01056, 0.0072304, 0.00036959, 0.003796, 0.003796, 0.003796 + 190, 0.018073, 0.018818, 0.00089374, 0.98863, 0.9729, 0.99195, 0.91112, 0.010539, 0.0072138, 0.00036874, 0.003763, 0.003763, 0.003763 + 191, 0.018248, 0.018897, 0.00089964, 0.98846, 0.9734, 0.99197, 0.91106, 0.010516, 0.0071993, 0.00036783, 0.00373, 0.00373, 0.00373 + 192, 0.018033, 0.019031, 0.00099059, 0.98828, 0.97379, 0.99199, 0.91114, 0.010494, 0.0071835, 0.00036693, 0.003697, 0.003697, 0.003697 + 193, 0.018177, 0.019179, 0.00084739, 0.98859, 0.97355, 0.99202, 0.91208, 0.010474, 0.0071699, 0.00036588, 0.003664, 0.003664, 0.003664 + 194, 0.017945, 0.018748, 0.00083708, 0.98852, 0.97381, 0.99204, 0.91205, 0.010457, 0.0071555, 0.00036465, 0.003631, 0.003631, 0.003631 + 195, 0.017776, 0.018612, 0.00081924, 0.97972, 0.98208, 0.99206, 0.91234, 0.010436, 0.0071383, 0.00036353, 0.003598, 0.003598, 0.003598 + 196, 0.018056, 0.018862, 0.00084071, 0.97996, 0.98175, 0.99207, 0.91246, 0.010414, 0.0071245, 0.00036255, 0.003565, 0.003565, 0.003565 + 197, 0.017871, 0.018487, 0.00083325, 0.97998, 0.98201, 0.99209, 0.91319, 0.010395, 0.0071103, 0.00036164, 0.003532, 0.003532, 0.003532 + 198, 0.017813, 0.018506, 0.0008157, 0.97925, 0.98278, 0.9921, 0.91348, 0.010371, 0.0070965, 0.00036062, 0.003499, 0.003499, 0.003499 + 199, 0.017976, 0.018352, 0.0008876, 0.98767, 0.97462, 0.99211, 0.91368, 0.01035, 0.0070839, 0.0003597, 0.003466, 0.003466, 0.003466 + 200, 0.017752, 0.018238, 0.00080208, 0.97912, 0.98324, 0.99215, 0.91387, 0.010331, 0.0070701, 0.00035859, 0.003433, 0.003433, 0.003433 + 201, 0.017607, 0.018217, 0.00082739, 0.97914, 0.98353, 0.99216, 0.91412, 0.01031, 0.0070567, 0.00035772, 0.0034, 0.0034, 0.0034 + 202, 0.017788, 0.01839, 0.00081563, 0.98675, 0.97621, 0.99219, 0.91412, 0.010296, 0.0070453, 0.00035673, 0.003367, 0.003367, 0.003367 + 203, 0.017674, 0.01822, 0.00087336, 0.98607, 0.97715, 0.99226, 0.91438, 0.010279, 0.0070319, 0.00035575, 0.003334, 0.003334, 0.003334 + 204, 0.01752, 0.018429, 0.00080507, 0.986, 0.97744, 0.99227, 0.91451, 0.010259, 0.0070185, 0.00035468, 0.003301, 0.003301, 0.003301 + 205, 0.01749, 0.018326, 0.00088941, 0.98578, 0.97815, 0.99224, 0.91484, 0.010246, 0.007007, 0.00035383, 0.003268, 0.003268, 0.003268 + 206, 0.017381, 0.017985, 0.00079273, 0.98588, 0.97813, 0.99225, 0.9148, 0.010233, 0.0069959, 0.00035289, 0.003235, 0.003235, 0.003235 + 207, 0.017541, 0.017934, 0.00082022, 0.98385, 0.98052, 0.99228, 0.91495, 0.010216, 0.0069861, 0.00035192, 0.003202, 0.003202, 0.003202 + 208, 0.017353, 0.018095, 0.00076554, 0.98396, 0.98061, 0.9923, 0.91498, 0.010203, 0.006975, 0.00035087, 0.003169, 0.003169, 0.003169 + 209, 0.017159, 0.017519, 0.00075523, 0.98478, 0.98028, 0.99233, 0.9153, 0.010188, 0.0069654, 0.00034991, 0.003136, 0.003136, 0.003136 + 210, 0.017046, 0.017682, 0.00075417, 0.98488, 0.98038, 0.99235, 0.91571, 0.010173, 0.0069567, 0.00034891, 0.003103, 0.003103, 0.003103 + 211, 0.016827, 0.017389, 0.00077417, 0.98471, 0.98115, 0.99237, 0.9156, 0.010161, 0.0069472, 0.00034796, 0.00307, 0.00307, 0.00307 + 212, 0.016958, 0.017337, 0.00075806, 0.98489, 0.98126, 0.99239, 0.91632, 0.010149, 0.0069368, 0.00034698, 0.003037, 0.003037, 0.003037 + 213, 0.017076, 0.017523, 0.00079277, 0.98477, 0.9814, 0.99239, 0.91665, 0.010135, 0.0069262, 0.00034625, 0.003004, 0.003004, 0.003004 + 214, 0.016897, 0.017568, 0.00078315, 0.98609, 0.98032, 0.9924, 0.91698, 0.010123, 0.0069163, 0.0003454, 0.002971, 0.002971, 0.002971 + 215, 0.016914, 0.01743, 0.00071245, 0.98454, 0.98206, 0.99243, 0.91762, 0.010108, 0.0069052, 0.00034458, 0.002938, 0.002938, 0.002938 + 216, 0.016759, 0.017154, 0.00072685, 0.98506, 0.9816, 0.99244, 0.9177, 0.010097, 0.0068969, 0.00034365, 0.002905, 0.002905, 0.002905 + 217, 0.016738, 0.01735, 0.00069426, 0.98511, 0.98172, 0.99247, 0.91782, 0.010085, 0.0068861, 0.00034284, 0.002872, 0.002872, 0.002872 + 218, 0.016709, 0.017322, 0.00072169, 0.98515, 0.98185, 0.99248, 0.91806, 0.010073, 0.0068747, 0.00034204, 0.002839, 0.002839, 0.002839 + 219, 0.016603, 0.017226, 0.00072254, 0.98397, 0.98324, 0.9925, 0.91829, 0.01006, 0.0068646, 0.00034121, 0.002806, 0.002806, 0.002806 + 220, 0.016699, 0.017026, 0.00077267, 0.98597, 0.98132, 0.99252, 0.9187, 0.010044, 0.0068545, 0.00034041, 0.002773, 0.002773, 0.002773 + 221, 0.016583, 0.016918, 0.0006735, 0.9859, 0.98239, 0.99254, 0.91893, 0.010031, 0.006844, 0.00033949, 0.00274, 0.00274, 0.00274 + 222, 0.016564, 0.016824, 0.0006577, 0.98624, 0.98209, 0.99256, 0.91939, 0.010019, 0.0068339, 0.0003386, 0.002707, 0.002707, 0.002707 + 223, 0.016318, 0.017033, 0.00070071, 0.98657, 0.98198, 0.99257, 0.91939, 0.010008, 0.0068238, 0.00033778, 0.002674, 0.002674, 0.002674 + 224, 0.016288, 0.016902, 0.00064337, 0.98676, 0.98182, 0.99259, 0.91947, 0.0099949, 0.0068147, 0.00033689, 0.002641, 0.002641, 0.002641 + 225, 0.016189, 0.017039, 0.00072706, 0.98764, 0.9812, 0.9926, 0.91972, 0.0099844, 0.0068047, 0.00033604, 0.002608, 0.002608, 0.002608 + 226, 0.016178, 0.016847, 0.00066318, 0.98742, 0.9815, 0.99265, 0.91984, 0.0099731, 0.0067964, 0.0003352, 0.002575, 0.002575, 0.002575 + 227, 0.016188, 0.016828, 0.00070502, 0.98763, 0.98151, 0.99267, 0.91998, 0.0099598, 0.0067873, 0.00033439, 0.002542, 0.002542, 0.002542 + 228, 0.016037, 0.016507, 0.00064068, 0.98706, 0.98223, 0.99265, 0.92012, 0.0099484, 0.0067779, 0.00033352, 0.002509, 0.002509, 0.002509 + 229, 0.016021, 0.016655, 0.00072549, 0.98716, 0.98237, 0.99266, 0.92046, 0.0099411, 0.0067688, 0.0003327, 0.002476, 0.002476, 0.002476 + 230, 0.01607, 0.016803, 0.00065071, 0.98728, 0.98231, 0.99267, 0.92048, 0.0099307, 0.0067602, 0.00033193, 0.002443, 0.002443, 0.002443 + 231, 0.016248, 0.016347, 0.00063766, 0.98734, 0.98229, 0.99267, 0.92048, 0.0099212, 0.0067527, 0.0003311, 0.00241, 0.00241, 0.00241 + 232, 0.015914, 0.016375, 0.00067446, 0.98947, 0.98034, 0.99269, 0.92069, 0.0099116, 0.0067429, 0.00033021, 0.002377, 0.002377, 0.002377 + 233, 0.01585, 0.016456, 0.00065836, 0.98941, 0.98041, 0.9927, 0.92079, 0.009903, 0.0067345, 0.00032948, 0.002344, 0.002344, 0.002344 + 234, 0.015711, 0.0161, 0.00064227, 0.98956, 0.98047, 0.99275, 0.92146, 0.0098923, 0.0067252, 0.00032867, 0.002311, 0.002311, 0.002311 + 235, 0.015737, 0.016332, 0.00062654, 0.98947, 0.98061, 0.99273, 0.92159, 0.0098809, 0.006716, 0.00032792, 0.002278, 0.002278, 0.002278 + 236, 0.015762, 0.016183, 0.00058885, 0.98965, 0.98064, 0.99277, 0.92137, 0.0098721, 0.0067068, 0.00032715, 0.002245, 0.002245, 0.002245 + 237, 0.015418, 0.015844, 0.000661, 0.98988, 0.98059, 0.99278, 0.92142, 0.0098642, 0.0066976, 0.00032642, 0.002212, 0.002212, 0.002212 + 238, 0.015615, 0.016072, 0.00067205, 0.98989, 0.9808, 0.99282, 0.92165, 0.0098556, 0.006688, 0.00032556, 0.002179, 0.002179, 0.002179 + 239, 0.015563, 0.015947, 0.00059048, 0.99002, 0.98083, 0.99291, 0.92168, 0.0098465, 0.0066784, 0.00032466, 0.002146, 0.002146, 0.002146 + 240, 0.015583, 0.0159, 0.00064594, 0.98981, 0.9811, 0.99283, 0.9216, 0.0098377, 0.006671, 0.00032388, 0.002113, 0.002113, 0.002113 + 241, 0.0154, 0.016083, 0.00065944, 0.98981, 0.98122, 0.99291, 0.92172, 0.0098298, 0.0066628, 0.00032312, 0.00208, 0.00208, 0.00208 + 242, 0.015349, 0.016156, 0.00062197, 0.98889, 0.98187, 0.99292, 0.92191, 0.0098186, 0.0066533, 0.00032229, 0.002047, 0.002047, 0.002047 + 243, 0.015271, 0.015499, 0.00059552, 0.98844, 0.98233, 0.99293, 0.92213, 0.0098108, 0.0066451, 0.00032147, 0.002014, 0.002014, 0.002014 + 244, 0.015162, 0.015483, 0.00064633, 0.98846, 0.98246, 0.99293, 0.92201, 0.0098021, 0.0066354, 0.00032069, 0.001981, 0.001981, 0.001981 + 245, 0.015225, 0.01537, 0.00058196, 0.98871, 0.98232, 0.99294, 0.92234, 0.0097915, 0.0066265, 0.00031984, 0.001948, 0.001948, 0.001948 + 246, 0.015127, 0.015671, 0.00058149, 0.98856, 0.98255, 0.99295, 0.92286, 0.0097796, 0.0066164, 0.00031905, 0.001915, 0.001915, 0.001915 + 247, 0.01523, 0.015554, 0.00057911, 0.98934, 0.98237, 0.99297, 0.92306, 0.0097704, 0.0066082, 0.00031829, 0.001882, 0.001882, 0.001882 + 248, 0.014981, 0.015378, 0.0006048, 0.98956, 0.98234, 0.99297, 0.92324, 0.0097606, 0.0065991, 0.00031748, 0.001849, 0.001849, 0.001849 + 249, 0.015056, 0.015389, 0.00056178, 0.98963, 0.98244, 0.99298, 0.92387, 0.0097525, 0.0065899, 0.00031662, 0.001816, 0.001816, 0.001816 + 250, 0.014942, 0.015452, 0.00054333, 0.98988, 0.98242, 0.993, 0.92373, 0.0097441, 0.0065816, 0.00031582, 0.001783, 0.001783, 0.001783 + 251, 0.014576, 0.01485, 0.00052215, 0.98952, 0.98261, 0.99292, 0.92386, 0.0097365, 0.0065727, 0.00031499, 0.00175, 0.00175, 0.00175 + 252, 0.014685, 0.015026, 0.0005634, 0.98986, 0.98237, 0.99302, 0.92402, 0.0097311, 0.0065648, 0.00031415, 0.001717, 0.001717, 0.001717 + 253, 0.014522, 0.015065, 0.00060657, 0.98989, 0.9825, 0.99303, 0.92398, 0.009723, 0.0065564, 0.00031326, 0.001684, 0.001684, 0.001684 + 254, 0.014795, 0.015187, 0.00052994, 0.98987, 0.98267, 0.99304, 0.92412, 0.0097158, 0.0065479, 0.00031236, 0.001651, 0.001651, 0.001651 + 255, 0.014489, 0.015141, 0.00057197, 0.99059, 0.98237, 0.99305, 0.92442, 0.009709, 0.0065407, 0.00031158, 0.001618, 0.001618, 0.001618 + 256, 0.014685, 0.01493, 0.00055322, 0.99056, 0.98262, 0.99337, 0.92464, 0.0097021, 0.0065327, 0.00031079, 0.001585, 0.001585, 0.001585 + 257, 0.014541, 0.014912, 0.00053204, 0.99054, 0.98264, 0.99341, 0.92475, 0.0096935, 0.0065252, 0.00030998, 0.001552, 0.001552, 0.001552 + 258, 0.014463, 0.014858, 0.00055833, 0.9893, 0.98287, 0.99339, 0.92474, 0.0096834, 0.0065151, 0.00030914, 0.001519, 0.001519, 0.001519 + 259, 0.014117, 0.014837, 0.00049551, 0.98925, 0.98297, 0.9934, 0.92499, 0.0096762, 0.0065071, 0.00030829, 0.001486, 0.001486, 0.001486 + 260, 0.014184, 0.014496, 0.00048431, 0.98928, 0.98291, 0.99339, 0.92513, 0.0096661, 0.0064986, 0.00030743, 0.001453, 0.001453, 0.001453 + 261, 0.014191, 0.014581, 0.00053963, 0.98801, 0.98422, 0.9934, 0.92514, 0.0096577, 0.0064911, 0.00030657, 0.00142, 0.00142, 0.00142 + 262, 0.014132, 0.014572, 0.00051369, 0.98897, 0.98324, 0.99337, 0.9253, 0.009651, 0.0064832, 0.00030571, 0.001387, 0.001387, 0.001387 + 263, 0.014029, 0.014296, 0.00047216, 0.99269, 0.97984, 0.99341, 0.92527, 0.0096425, 0.0064741, 0.00030481, 0.001354, 0.001354, 0.001354 + 264, 0.0141, 0.014291, 0.00050788, 0.9925, 0.98006, 0.99336, 0.92575, 0.0096351, 0.0064651, 0.00030389, 0.001321, 0.001321, 0.001321 + 265, 0.013777, 0.013757, 0.00047163, 0.98897, 0.9836, 0.99336, 0.92578, 0.0096265, 0.0064568, 0.00030295, 0.001288, 0.001288, 0.001288 + 266, 0.014098, 0.014257, 0.00056032, 0.99249, 0.98034, 0.99337, 0.92581, 0.0096196, 0.00645, 0.00030207, 0.001255, 0.001255, 0.001255 + 267, 0.013865, 0.01415, 0.00054343, 0.98893, 0.98389, 0.99337, 0.92583, 0.0096111, 0.0064413, 0.00030118, 0.001222, 0.001222, 0.001222 + 268, 0.013643, 0.014107, 0.00050328, 0.9926, 0.98042, 0.99339, 0.92593, 0.0096039, 0.0064323, 0.00030029, 0.001189, 0.001189, 0.001189 + 269, 0.013846, 0.014281, 0.00049422, 0.99181, 0.98116, 0.99339, 0.92609, 0.0095972, 0.0064245, 0.00029947, 0.001156, 0.001156, 0.001156 + 270, 0.013744, 0.013903, 0.0004803, 0.99243, 0.98052, 0.99312, 0.92612, 0.009592, 0.0064172, 0.00029859, 0.001123, 0.001123, 0.001123 + 271, 0.013808, 0.014053, 0.00054369, 0.99163, 0.98138, 0.99313, 0.92625, 0.0095853, 0.0064096, 0.00029769, 0.00109, 0.00109, 0.00109 + 272, 0.013572, 0.013845, 0.00051583, 0.99193, 0.98119, 0.99313, 0.92639, 0.0095796, 0.0064022, 0.00029679, 0.001057, 0.001057, 0.001057 + 273, 0.013528, 0.013955, 0.00046562, 0.99208, 0.98101, 0.99312, 0.92629, 0.0095732, 0.0063938, 0.00029581, 0.001024, 0.001024, 0.001024 + 274, 0.013718, 0.013854, 0.00047416, 0.992, 0.98122, 0.99336, 0.92675, 0.0095652, 0.0063857, 0.0002948, 0.000991, 0.000991, 0.000991 + 275, 0.013418, 0.013529, 0.00044316, 0.99197, 0.98143, 0.99337, 0.92674, 0.0095591, 0.006379, 0.00029374, 0.000958, 0.000958, 0.000958 + 276, 0.013301, 0.01357, 0.00050538, 0.99209, 0.98136, 0.99314, 0.92683, 0.0095517, 0.0063705, 0.0002928, 0.000925, 0.000925, 0.000925 + 277, 0.013462, 0.01374, 0.00051918, 0.99225, 0.98124, 0.99337, 0.92684, 0.0095453, 0.0063645, 0.00029179, 0.000892, 0.000892, 0.000892 + 278, 0.0132, 0.013644, 0.0004653, 0.99225, 0.98129, 0.99346, 0.92672, 0.0095405, 0.0063579, 0.00029076, 0.000859, 0.000859, 0.000859 + 279, 0.013057, 0.013315, 0.00046224, 0.99198, 0.98164, 0.99345, 0.92706, 0.0095318, 0.0063475, 0.00028969, 0.000826, 0.000826, 0.000826 + 280, 0.013054, 0.013392, 0.00042758, 0.99206, 0.98165, 0.99347, 0.92708, 0.0095242, 0.0063407, 0.00028853, 0.000793, 0.000793, 0.000793 + 281, 0.013121, 0.01349, 0.00049714, 0.99275, 0.98112, 0.99348, 0.9273, 0.0095174, 0.0063327, 0.00028746, 0.00076, 0.00076, 0.00076 + 282, 0.013024, 0.013095, 0.00045109, 0.99281, 0.98122, 0.99368, 0.92748, 0.0095111, 0.0063249, 0.00028641, 0.000727, 0.000727, 0.000727 + 283, 0.012912, 0.013139, 0.00042311, 0.99285, 0.98133, 0.99369, 0.92755, 0.0095049, 0.0063188, 0.0002853, 0.000694, 0.000694, 0.000694 + 284, 0.012849, 0.013123, 0.00042124, 0.99268, 0.9816, 0.99369, 0.92757, 0.0094955, 0.0063091, 0.00028414, 0.000661, 0.000661, 0.000661 + 285, 0.012904, 0.013217, 0.00044162, 0.99267, 0.98181, 0.99373, 0.9275, 0.0094889, 0.0063009, 0.00028302, 0.000628, 0.000628, 0.000628 + 286, 0.01275, 0.013114, 0.00041869, 0.99344, 0.98099, 0.99373, 0.92807, 0.0094822, 0.0062939, 0.00028186, 0.000595, 0.000595, 0.000595 + 287, 0.012869, 0.012806, 0.00043699, 0.99339, 0.98122, 0.99374, 0.92806, 0.0094769, 0.0062864, 0.00028069, 0.000562, 0.000562, 0.000562 + 288, 0.01266, 0.013075, 0.00044534, 0.99336, 0.9813, 0.99374, 0.92811, 0.0094696, 0.0062796, 0.00027952, 0.000529, 0.000529, 0.000529 + 289, 0.012648, 0.012793, 0.00042948, 0.99343, 0.98119, 0.9937, 0.92809, 0.0094645, 0.0062714, 0.00027839, 0.000496, 0.000496, 0.000496 + 290, 0.012454, 0.012871, 0.00048243, 0.99244, 0.98213, 0.99374, 0.9284, 0.0094601, 0.0062651, 0.00027726, 0.000463, 0.000463, 0.000463 + 291, 0.012464, 0.012838, 0.00047032, 0.99251, 0.98209, 0.99371, 0.92838, 0.0094565, 0.006259, 0.00027616, 0.00043, 0.00043, 0.00043 + 292, 0.012272, 0.012355, 0.00036744, 0.99399, 0.98087, 0.99375, 0.92847, 0.0094536, 0.0062513, 0.000275, 0.000397, 0.000397, 0.000397 + 293, 0.012425, 0.012732, 0.00042552, 0.99393, 0.98106, 0.99375, 0.92852, 0.00945, 0.0062447, 0.00027381, 0.000364, 0.000364, 0.000364 + 294, 0.012508, 0.012516, 0.00042678, 0.9939, 0.98119, 0.99376, 0.92867, 0.0094462, 0.0062377, 0.00027261, 0.000331, 0.000331, 0.000331 + 295, 0.012431, 0.012674, 0.00042366, 0.99392, 0.98124, 0.99376, 0.92883, 0.0094393, 0.0062311, 0.00027137, 0.000298, 0.000298, 0.000298 + 296, 0.012627, 0.012439, 0.0004267, 0.9937, 0.98159, 0.99377, 0.92897, 0.0094366, 0.0062256, 0.00027016, 0.000265, 0.000265, 0.000265 + 297, 0.012199, 0.012283, 0.00037769, 0.99335, 0.982, 0.99377, 0.92917, 0.0094335, 0.0062191, 0.00026894, 0.000232, 0.000232, 0.000232 + 298, 0.012232, 0.012384, 0.00040567, 0.99385, 0.98155, 0.99373, 0.92925, 0.0094279, 0.0062135, 0.00026769, 0.000199, 0.000199, 0.000199 + 299, 0.012367, 0.012353, 0.00045379, 0.99392, 0.98153, 0.99374, 0.92948, 0.0094247, 0.0062069, 0.00026646, 0.000166, 0.000166, 0.000166 diff --git a/resources/yolo_models/2022-0511/results.png b/resources/yolo_models/2022-0511/results.png new file mode 100644 index 00000000..860deb85 Binary files /dev/null and b/resources/yolo_models/2022-0511/results.png differ diff --git a/resources/yolo_models/2022-0511/train_batch0.jpg b/resources/yolo_models/2022-0511/train_batch0.jpg new file mode 100644 index 00000000..7096c7e4 Binary files /dev/null and b/resources/yolo_models/2022-0511/train_batch0.jpg differ diff --git a/resources/yolo_models/2022-0511/train_batch1.jpg b/resources/yolo_models/2022-0511/train_batch1.jpg new file mode 100644 index 00000000..2d22d460 Binary files /dev/null and b/resources/yolo_models/2022-0511/train_batch1.jpg differ diff --git a/resources/yolo_models/2022-0511/train_batch2.jpg b/resources/yolo_models/2022-0511/train_batch2.jpg new file mode 100644 index 00000000..42c2e7b3 Binary files /dev/null and b/resources/yolo_models/2022-0511/train_batch2.jpg differ diff --git a/resources/yolo_models/2022-0511/val_batch0_labels.jpg b/resources/yolo_models/2022-0511/val_batch0_labels.jpg new file mode 100644 index 00000000..343a439b Binary files /dev/null and b/resources/yolo_models/2022-0511/val_batch0_labels.jpg differ diff --git a/resources/yolo_models/2022-0511/val_batch0_pred.jpg b/resources/yolo_models/2022-0511/val_batch0_pred.jpg new file mode 100644 index 00000000..614e6a9b Binary files /dev/null and b/resources/yolo_models/2022-0511/val_batch0_pred.jpg differ diff --git a/resources/yolo_models/2022-0511/val_batch1_labels.jpg b/resources/yolo_models/2022-0511/val_batch1_labels.jpg new file mode 100644 index 00000000..d4b08d9d Binary files /dev/null and b/resources/yolo_models/2022-0511/val_batch1_labels.jpg differ diff --git a/resources/yolo_models/2022-0511/val_batch1_pred.jpg b/resources/yolo_models/2022-0511/val_batch1_pred.jpg new file mode 100644 index 00000000..50418f8f Binary files /dev/null and b/resources/yolo_models/2022-0511/val_batch1_pred.jpg differ diff --git a/resources/yolo_models/2022-0511/val_batch2_labels.jpg b/resources/yolo_models/2022-0511/val_batch2_labels.jpg new file mode 100644 index 00000000..35aeba16 Binary files /dev/null and b/resources/yolo_models/2022-0511/val_batch2_labels.jpg differ diff --git a/resources/yolo_models/2022-0511/val_batch2_pred.jpg b/resources/yolo_models/2022-0511/val_batch2_pred.jpg new file mode 100644 index 00000000..054e3d20 Binary files /dev/null and b/resources/yolo_models/2022-0511/val_batch2_pred.jpg differ diff --git a/resources/yolo_models/2022-0511/weights/best.pt b/resources/yolo_models/2022-0511/weights/best.pt new file mode 100644 index 00000000..efc18a51 --- /dev/null +++ b/resources/yolo_models/2022-0511/weights/best.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a6c877c468b5f0746aea9ee1beb371d09d01050c3b6b9897d842cc2e127a0d88 +size 173238813 diff --git a/resources/yolo_models/2022-0511/weights/last.pt b/resources/yolo_models/2022-0511/weights/last.pt new file mode 100644 index 00000000..efc18a51 --- /dev/null +++ b/resources/yolo_models/2022-0511/weights/last.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a6c877c468b5f0746aea9ee1beb371d09d01050c3b6b9897d842cc2e127a0d88 +size 173238813 diff --git a/resources/yolo_models/2022-0601/F1_curve.png b/resources/yolo_models/2022-0601/F1_curve.png new file mode 100644 index 00000000..cdeb5ac4 Binary files /dev/null and b/resources/yolo_models/2022-0601/F1_curve.png differ diff --git a/resources/yolo_models/2022-0601/PR_curve.png b/resources/yolo_models/2022-0601/PR_curve.png new file mode 100644 index 00000000..3a079266 Binary files /dev/null and b/resources/yolo_models/2022-0601/PR_curve.png differ diff --git a/resources/yolo_models/2022-0601/P_curve.png b/resources/yolo_models/2022-0601/P_curve.png new file mode 100644 index 00000000..9941717c Binary files /dev/null and b/resources/yolo_models/2022-0601/P_curve.png differ diff --git a/resources/yolo_models/2022-0601/R_curve.png b/resources/yolo_models/2022-0601/R_curve.png new file mode 100644 index 00000000..8ca8af5e Binary files /dev/null and b/resources/yolo_models/2022-0601/R_curve.png differ diff --git a/resources/yolo_models/2022-0601/confusion_matrix.png b/resources/yolo_models/2022-0601/confusion_matrix.png new file mode 100644 index 00000000..ca68b219 Binary files /dev/null and b/resources/yolo_models/2022-0601/confusion_matrix.png differ diff --git a/resources/yolo_models/2022-0601/events.out.tfevents.1654101053.ccowen-GL75-Leopard-10SFK.53926.0 b/resources/yolo_models/2022-0601/events.out.tfevents.1654101053.ccowen-GL75-Leopard-10SFK.53926.0 new file mode 100644 index 00000000..77275417 Binary files /dev/null and b/resources/yolo_models/2022-0601/events.out.tfevents.1654101053.ccowen-GL75-Leopard-10SFK.53926.0 differ diff --git a/resources/yolo_models/2022-0601/hyp.yaml b/resources/yolo_models/2022-0601/hyp.yaml new file mode 100644 index 00000000..b54281de --- /dev/null +++ b/resources/yolo_models/2022-0601/hyp.yaml @@ -0,0 +1,28 @@ +lr0: 0.01 +lrf: 0.1 +momentum: 0.937 +weight_decay: 0.0005 +warmup_epochs: 3.0 +warmup_momentum: 0.8 +warmup_bias_lr: 0.1 +box: 0.05 +cls: 0.5 +cls_pw: 1.0 +obj: 1.0 +obj_pw: 1.0 +iou_t: 0.2 +anchor_t: 4.0 +fl_gamma: 0.0 +hsv_h: 0.015 +hsv_s: 0.7 +hsv_v: 0.4 +degrees: 0.0 +translate: 0.1 +scale: 0.5 +shear: 0.0 +perspective: 0.0 +flipud: 0.0 +fliplr: 0.5 +mosaic: 1.0 +mixup: 0.0 +copy_paste: 0.0 diff --git a/resources/yolo_models/2022-0601/labels.jpg b/resources/yolo_models/2022-0601/labels.jpg new file mode 100644 index 00000000..626f7ec8 Binary files /dev/null and b/resources/yolo_models/2022-0601/labels.jpg differ diff --git a/resources/yolo_models/2022-0601/labels_correlogram.jpg b/resources/yolo_models/2022-0601/labels_correlogram.jpg new file mode 100644 index 00000000..596f9289 Binary files /dev/null and b/resources/yolo_models/2022-0601/labels_correlogram.jpg differ diff --git a/resources/yolo_models/2022-0601/opt.yaml b/resources/yolo_models/2022-0601/opt.yaml new file mode 100644 index 00000000..d82194b8 --- /dev/null +++ b/resources/yolo_models/2022-0601/opt.yaml @@ -0,0 +1,38 @@ +weights: yolov5s.pt +cfg: '' +data: MarsRover.yaml +hyp: data/hyps/hyp.scratch.yaml +epochs: 275 +batch_size: -1 +imgsz: 640 +rect: false +resume: false +nosave: false +noval: false +noautoanchor: false +evolve: null +bucket: '' +cache: null +image_weights: false +device: '' +multi_scale: false +single_cls: false +optimizer: SGD +sync_bn: false +workers: 8 +project: runs/train +name: exp +exist_ok: false +quad: false +linear_lr: false +label_smoothing: 0.0 +patience: 100 +freeze: +- 0 +save_period: -1 +local_rank: -1 +entity: null +upload_dataset: false +bbox_interval: -1 +artifact_alias: latest +save_dir: runs/train/exp2 diff --git a/resources/yolo_models/2022-0601/results.csv b/resources/yolo_models/2022-0601/results.csv new file mode 100644 index 00000000..0f37178a --- /dev/null +++ b/resources/yolo_models/2022-0601/results.csv @@ -0,0 +1,276 @@ + epoch, train/box_loss, train/obj_loss, train/cls_loss, metrics/precision, metrics/recall, metrics/mAP_0.5,metrics/mAP_0.5:0.95, val/box_loss, val/obj_loss, val/cls_loss, x/lr0, x/lr1, x/lr2 + 0, 0.087307, 0.053185, 0.049984, 0.50296, 0.27437, 0.20509, 0.070415, 0.061261, 0.032344, 0.033255, 0.0018, 0.0018, 0.0838 + 1, 0.063095, 0.048508, 0.024197, 0.55192, 0.46337, 0.39738, 0.16056, 0.053247, 0.028189, 0.013452, 0.0036099, 0.0036099, 0.06751 + 2, 0.058759, 0.046169, 0.013793, 0.48806, 0.43661, 0.36365, 0.15177, 0.055433, 0.026798, 0.0088319, 0.0054194, 0.0054194, 0.051219 + 3, 0.059177, 0.045361, 0.011717, 0.64512, 0.50307, 0.4965, 0.23024, 0.049271, 0.027527, 0.0084164, 0.0072281, 0.0072281, 0.034928 + 4, 0.054687, 0.045869, 0.010218, 0.62406, 0.46304, 0.45893, 0.20919, 0.049408, 0.030827, 0.0099986, 0.0090358, 0.0090358, 0.018636 + 5, 0.052871, 0.047399, 0.010259, 0.67623, 0.41377, 0.44024, 0.20792, 0.051072, 0.031555, 0.015491, 0.0099927, 0.0099927, 0.0099927 + 6, 0.051682, 0.046936, 0.0092459, 0.62553, 0.56703, 0.56904, 0.27273, 0.045187, 0.027224, 0.0051888, 0.0099927, 0.0099927, 0.0099927 + 7, 0.049881, 0.046251, 0.0079726, 0.638, 0.56899, 0.59023, 0.26457, 0.046525, 0.026867, 0.0049314, 0.0099894, 0.0099894, 0.0099894 + 8, 0.048953, 0.04591, 0.0074475, 0.70897, 0.60188, 0.65159, 0.3277, 0.042807, 0.025173, 0.0038868, 0.0099856, 0.0099856, 0.0099856 + 9, 0.047514, 0.044318, 0.0064489, 0.70289, 0.63986, 0.67026, 0.33863, 0.04172, 0.025009, 0.0036191, 0.0099812, 0.0099812, 0.0099812 + 10, 0.046668, 0.043207, 0.0060938, 0.68801, 0.67399, 0.69859, 0.35889, 0.041257, 0.024995, 0.0030046, 0.0099762, 0.0099762, 0.0099762 + 11, 0.04605, 0.042975, 0.0056231, 0.7053, 0.67726, 0.70526, 0.36124, 0.040652, 0.024299, 0.0027248, 0.0099707, 0.0099707, 0.0099707 + 12, 0.045536, 0.042814, 0.0053064, 0.72078, 0.68345, 0.72475, 0.37566, 0.040279, 0.023519, 0.0023253, 0.0099645, 0.0099645, 0.0099645 + 13, 0.044805, 0.04198, 0.0051726, 0.76512, 0.69615, 0.74663, 0.39666, 0.039298, 0.023128, 0.0020712, 0.0099578, 0.0099578, 0.0099578 + 14, 0.044456, 0.041444, 0.0051574, 0.73581, 0.65806, 0.72052, 0.36901, 0.040388, 0.024171, 0.0023943, 0.0099505, 0.0099505, 0.0099505 + 15, 0.043867, 0.041634, 0.0046887, 0.74831, 0.72834, 0.7662, 0.40618, 0.038631, 0.022728, 0.0021883, 0.0099426, 0.0099426, 0.0099426 + 16, 0.043586, 0.041235, 0.0047928, 0.75239, 0.71399, 0.75904, 0.40666, 0.038944, 0.022758, 0.001851, 0.0099341, 0.0099341, 0.0099341 + 17, 0.043106, 0.041153, 0.0044366, 0.76775, 0.73964, 0.7877, 0.42682, 0.037617, 0.022194, 0.0016807, 0.009925, 0.009925, 0.009925 + 18, 0.043194, 0.040402, 0.0043482, 0.76484, 0.7317, 0.77821, 0.41514, 0.037547, 0.022015, 0.0020193, 0.0099154, 0.0099154, 0.0099154 + 19, 0.042276, 0.040061, 0.0041756, 0.78188, 0.76424, 0.80939, 0.45026, 0.037508, 0.021421, 0.0016971, 0.0099052, 0.0099052, 0.0099052 + 20, 0.042035, 0.039444, 0.0039833, 0.78135, 0.76754, 0.81238, 0.44711, 0.036635, 0.021367, 0.0016257, 0.0098944, 0.0098944, 0.0098944 + 21, 0.041657, 0.039898, 0.003753, 0.79085, 0.77296, 0.823, 0.45924, 0.035941, 0.021041, 0.001348, 0.0098831, 0.0098831, 0.0098831 + 22, 0.041532, 0.038732, 0.0038532, 0.78381, 0.76696, 0.80865, 0.44741, 0.035927, 0.021215, 0.0015369, 0.0098711, 0.0098711, 0.0098711 + 23, 0.041237, 0.038922, 0.0037724, 0.80571, 0.77822, 0.83577, 0.47234, 0.035118, 0.020677, 0.0014693, 0.0098586, 0.0098586, 0.0098586 + 24, 0.040919, 0.038926, 0.0037047, 0.82869, 0.76226, 0.83331, 0.47283, 0.034837, 0.020831, 0.0012695, 0.0098456, 0.0098456, 0.0098456 + 25, 0.040432, 0.038193, 0.0036885, 0.82788, 0.79352, 0.84915, 0.487, 0.034194, 0.020138, 0.001317, 0.0098319, 0.0098319, 0.0098319 + 26, 0.04016, 0.038436, 0.0033427, 0.82474, 0.78154, 0.84998, 0.47849, 0.035516, 0.02056, 0.0012097, 0.0098177, 0.0098177, 0.0098177 + 27, 0.040236, 0.037746, 0.0035712, 0.83718, 0.79527, 0.85648, 0.49799, 0.034898, 0.019933, 0.001188, 0.009803, 0.009803, 0.009803 + 28, 0.039975, 0.03742, 0.0035264, 0.83752, 0.78658, 0.85766, 0.49671, 0.03448, 0.019953, 0.0011585, 0.0097876, 0.0097876, 0.0097876 + 29, 0.039532, 0.037462, 0.0032122, 0.81522, 0.81924, 0.86584, 0.51076, 0.033004, 0.019565, 0.0011376, 0.0097717, 0.0097717, 0.0097717 + 30, 0.039322, 0.037329, 0.0031417, 0.83532, 0.81764, 0.87171, 0.51943, 0.033217, 0.01951, 0.0010936, 0.0097553, 0.0097553, 0.0097553 + 31, 0.039366, 0.037018, 0.0031429, 0.833, 0.82304, 0.87261, 0.52707, 0.032656, 0.019419, 0.0010565, 0.0097383, 0.0097383, 0.0097383 + 32, 0.039125, 0.036793, 0.0032561, 0.82499, 0.80539, 0.86056, 0.5106, 0.033441, 0.020032, 0.00115, 0.0097207, 0.0097207, 0.0097207 + 33, 0.038785, 0.037182, 0.003153, 0.84901, 0.82885, 0.88252, 0.5359, 0.032323, 0.018923, 0.0009794, 0.0097026, 0.0097026, 0.0097026 + 34, 0.038625, 0.036407, 0.0031609, 0.81731, 0.82261, 0.86491, 0.52483, 0.032812, 0.019398, 0.0011867, 0.009684, 0.009684, 0.009684 + 35, 0.038682, 0.036959, 0.0030427, 0.85661, 0.8355, 0.89187, 0.5438, 0.032022, 0.018554, 0.00094364, 0.0096648, 0.0096648, 0.0096648 + 36, 0.038545, 0.03664, 0.0029526, 0.85878, 0.83324, 0.89028, 0.5458, 0.031712, 0.018378, 0.00094783, 0.0096451, 0.0096451, 0.0096451 + 37, 0.03813, 0.036348, 0.002895, 0.85071, 0.84509, 0.89286, 0.54923, 0.03091, 0.018291, 0.00095891, 0.0096248, 0.0096248, 0.0096248 + 38, 0.037992, 0.036683, 0.0029458, 0.89104, 0.82483, 0.8981, 0.55463, 0.031033, 0.017996, 0.00089507, 0.009604, 0.009604, 0.009604 + 39, 0.037818, 0.035541, 0.0029157, 0.86651, 0.85133, 0.90213, 0.56615, 0.030692, 0.018063, 0.00091095, 0.0095826, 0.0095826, 0.0095826 + 40, 0.037716, 0.035756, 0.0029863, 0.87682, 0.85502, 0.90552, 0.57, 0.030521, 0.017696, 0.00094853, 0.0095607, 0.0095607, 0.0095607 + 41, 0.037517, 0.03541, 0.0029119, 0.87787, 0.83907, 0.90349, 0.5671, 0.031272, 0.017993, 0.00086635, 0.0095383, 0.0095383, 0.0095383 + 42, 0.037149, 0.035575, 0.0027369, 0.88074, 0.84855, 0.90579, 0.56293, 0.030627, 0.017907, 0.00084396, 0.0095153, 0.0095153, 0.0095153 + 43, 0.037152, 0.034711, 0.0027593, 0.86966, 0.86676, 0.90905, 0.57766, 0.029978, 0.017623, 0.00088532, 0.0094919, 0.0094919, 0.0094919 + 44, 0.036988, 0.034944, 0.0026704, 0.88001, 0.84999, 0.90979, 0.57733, 0.030068, 0.017549, 0.00083261, 0.0094679, 0.0094679, 0.0094679 + 45, 0.036484, 0.035088, 0.0027191, 0.87753, 0.87439, 0.92017, 0.59089, 0.029266, 0.017299, 0.00084065, 0.0094434, 0.0094434, 0.0094434 + 46, 0.036813, 0.035076, 0.0027994, 0.84657, 0.87653, 0.90904, 0.568, 0.030826, 0.017902, 0.00083057, 0.0094184, 0.0094184, 0.0094184 + 47, 0.036673, 0.034931, 0.0026354, 0.88723, 0.86702, 0.92011, 0.59586, 0.029147, 0.016987, 0.00081235, 0.0093928, 0.0093928, 0.0093928 + 48, 0.036601, 0.034839, 0.0026682, 0.88553, 0.86788, 0.91762, 0.59542, 0.029047, 0.016945, 0.00086736, 0.0093668, 0.0093668, 0.0093668 + 49, 0.036516, 0.034387, 0.0026897, 0.89223, 0.86711, 0.92194, 0.59109, 0.029333, 0.017184, 0.00080264, 0.0093402, 0.0093402, 0.0093402 + 50, 0.036188, 0.034588, 0.0026674, 0.88661, 0.87051, 0.91956, 0.5847, 0.029305, 0.016954, 0.00075473, 0.0093132, 0.0093132, 0.0093132 + 51, 0.036396, 0.034671, 0.0027102, 0.89115, 0.87097, 0.92278, 0.59609, 0.02894, 0.016722, 0.00076069, 0.0092856, 0.0092856, 0.0092856 + 52, 0.036044, 0.034231, 0.0025926, 0.88796, 0.87455, 0.92363, 0.60939, 0.028233, 0.016487, 0.00075457, 0.0092576, 0.0092576, 0.0092576 + 53, 0.0357, 0.033751, 0.0024973, 0.89193, 0.88175, 0.92575, 0.61412, 0.028105, 0.016462, 0.00076641, 0.0092291, 0.0092291, 0.0092291 + 54, 0.035505, 0.033428, 0.002403, 0.88704, 0.88269, 0.929, 0.61543, 0.028616, 0.016195, 0.00074912, 0.0092001, 0.0092001, 0.0092001 + 55, 0.035424, 0.034041, 0.0024231, 0.89916, 0.88216, 0.93007, 0.6217, 0.027886, 0.01628, 0.00076024, 0.0091706, 0.0091706, 0.0091706 + 56, 0.035661, 0.033755, 0.0025582, 0.88823, 0.90169, 0.93301, 0.61391, 0.02826, 0.016196, 0.00072573, 0.0091406, 0.0091406, 0.0091406 + 57, 0.035165, 0.033633, 0.0023726, 0.90096, 0.8848, 0.93189, 0.62149, 0.027781, 0.016093, 0.00069081, 0.0091101, 0.0091101, 0.0091101 + 58, 0.035587, 0.033436, 0.0023828, 0.90002, 0.89032, 0.93596, 0.62986, 0.027551, 0.016189, 0.00071755, 0.0090792, 0.0090792, 0.0090792 + 59, 0.035193, 0.03362, 0.0023805, 0.90318, 0.8929, 0.93878, 0.6373, 0.027086, 0.015997, 0.00070702, 0.0090478, 0.0090478, 0.0090478 + 60, 0.035043, 0.033539, 0.0023457, 0.90675, 0.87029, 0.92984, 0.62114, 0.027534, 0.016007, 0.00068451, 0.009016, 0.009016, 0.009016 + 61, 0.035326, 0.033674, 0.002424, 0.91001, 0.88571, 0.93867, 0.63396, 0.027286, 0.015802, 0.00069269, 0.0089836, 0.0089836, 0.0089836 + 62, 0.034995, 0.033961, 0.002364, 0.89573, 0.88879, 0.93577, 0.63529, 0.027065, 0.015732, 0.00066394, 0.0089509, 0.0089509, 0.0089509 + 63, 0.03467, 0.032759, 0.0022522, 0.90633, 0.89101, 0.9397, 0.64763, 0.026992, 0.015502, 0.00068602, 0.0089177, 0.0089177, 0.0089177 + 64, 0.034465, 0.033528, 0.0023229, 0.9022, 0.8975, 0.93936, 0.64488, 0.026568, 0.015436, 0.00070993, 0.008884, 0.008884, 0.008884 + 65, 0.034729, 0.033127, 0.0022829, 0.90381, 0.89477, 0.93784, 0.64648, 0.026463, 0.01547, 0.00068125, 0.0088499, 0.0088499, 0.0088499 + 66, 0.034434, 0.032837, 0.0023832, 0.90872, 0.89713, 0.94066, 0.65164, 0.025993, 0.015259, 0.00073444, 0.0088153, 0.0088153, 0.0088153 + 67, 0.034417, 0.032622, 0.0023708, 0.90351, 0.89755, 0.9434, 0.64332, 0.026739, 0.015394, 0.00067286, 0.0087804, 0.0087804, 0.0087804 + 68, 0.034439, 0.03333, 0.0023823, 0.90441, 0.90223, 0.94161, 0.65581, 0.026039, 0.015295, 0.00070461, 0.008745, 0.008745, 0.008745 + 69, 0.034439, 0.033253, 0.0024406, 0.91277, 0.89037, 0.93921, 0.64779, 0.02633, 0.015333, 0.00068476, 0.0087091, 0.0087091, 0.0087091 + 70, 0.034227, 0.032605, 0.0022979, 0.90847, 0.90908, 0.94585, 0.6561, 0.026133, 0.01513, 0.00065621, 0.0086729, 0.0086729, 0.0086729 + 71, 0.034233, 0.0322, 0.0022144, 0.90394, 0.91253, 0.94742, 0.66574, 0.025818, 0.015083, 0.00066345, 0.0086362, 0.0086362, 0.0086362 + 72, 0.033871, 0.032272, 0.0022359, 0.91392, 0.90036, 0.94721, 0.66173, 0.026056, 0.015081, 0.00062109, 0.0085991, 0.0085991, 0.0085991 + 73, 0.033959, 0.032559, 0.0020474, 0.90814, 0.90424, 0.94639, 0.66853, 0.025236, 0.014787, 0.00065397, 0.0085617, 0.0085617, 0.0085617 + 74, 0.033533, 0.032034, 0.0021597, 0.92448, 0.89575, 0.94756, 0.66387, 0.025414, 0.014747, 0.00064003, 0.0085238, 0.0085238, 0.0085238 + 75, 0.033757, 0.032583, 0.0022547, 0.90767, 0.91425, 0.94763, 0.67199, 0.025046, 0.014762, 0.00064498, 0.0084855, 0.0084855, 0.0084855 + 76, 0.033589, 0.032582, 0.0022479, 0.9164, 0.90776, 0.94815, 0.66985, 0.025348, 0.014716, 0.00059303, 0.0084469, 0.0084469, 0.0084469 + 77, 0.0336, 0.032249, 0.0021328, 0.92424, 0.89437, 0.94691, 0.66735, 0.025091, 0.014735, 0.00058975, 0.0084078, 0.0084078, 0.0084078 + 78, 0.03363, 0.031984, 0.0021989, 0.92021, 0.90822, 0.94953, 0.67659, 0.024626, 0.014472, 0.00059787, 0.0083684, 0.0083684, 0.0083684 + 79, 0.033542, 0.031695, 0.0021674, 0.91516, 0.91776, 0.95016, 0.68025, 0.024724, 0.014452, 0.00060108, 0.0083286, 0.0083286, 0.0083286 + 80, 0.033247, 0.032119, 0.0021482, 0.92449, 0.90513, 0.94934, 0.67787, 0.024746, 0.014516, 0.00059493, 0.0082884, 0.0082884, 0.0082884 + 81, 0.033604, 0.032451, 0.0021004, 0.91142, 0.91393, 0.94946, 0.67105, 0.025088, 0.014649, 0.00058934, 0.0082479, 0.0082479, 0.0082479 + 82, 0.033075, 0.031532, 0.0021129, 0.92195, 0.91021, 0.95072, 0.67703, 0.024538, 0.014425, 0.00060989, 0.008207, 0.008207, 0.008207 + 83, 0.032902, 0.031697, 0.0021383, 0.92117, 0.91545, 0.95323, 0.68624, 0.024248, 0.014248, 0.00061173, 0.0081658, 0.0081658, 0.0081658 + 84, 0.032923, 0.031617, 0.0020052, 0.92803, 0.91015, 0.95221, 0.68667, 0.024215, 0.014134, 0.00058345, 0.0081242, 0.0081242, 0.0081242 + 85, 0.032897, 0.031862, 0.0020354, 0.91465, 0.92037, 0.95495, 0.68606, 0.024166, 0.014176, 0.00057869, 0.0080823, 0.0080823, 0.0080823 + 86, 0.032597, 0.031566, 0.0020423, 0.93022, 0.91148, 0.95407, 0.69034, 0.023817, 0.014113, 0.0005816, 0.00804, 0.00804, 0.00804 + 87, 0.032805, 0.031688, 0.0020453, 0.92691, 0.92188, 0.95481, 0.69666, 0.023704, 0.013954, 0.0005642, 0.0079974, 0.0079974, 0.0079974 + 88, 0.032582, 0.03146, 0.0018986, 0.93488, 0.90492, 0.95348, 0.69262, 0.023741, 0.013948, 0.0005772, 0.0079545, 0.0079545, 0.0079545 + 89, 0.032432, 0.031174, 0.0020064, 0.92926, 0.91253, 0.95589, 0.69808, 0.023603, 0.01391, 0.0005697, 0.0079112, 0.0079112, 0.0079112 + 90, 0.032373, 0.031174, 0.0019708, 0.92527, 0.91371, 0.95386, 0.70164, 0.023451, 0.013849, 0.00055529, 0.0078677, 0.0078677, 0.0078677 + 91, 0.032249, 0.031322, 0.0019279, 0.92683, 0.91072, 0.95317, 0.69653, 0.023528, 0.013894, 0.0005642, 0.0078238, 0.0078238, 0.0078238 + 92, 0.032188, 0.031184, 0.0019135, 0.92694, 0.91458, 0.95465, 0.69821, 0.023617, 0.013843, 0.00056284, 0.0077796, 0.0077796, 0.0077796 + 93, 0.032148, 0.03125, 0.0019446, 0.91604, 0.92624, 0.95682, 0.69924, 0.023638, 0.013821, 0.0005747, 0.0077351, 0.0077351, 0.0077351 + 94, 0.032143, 0.031041, 0.001835, 0.91965, 0.9287, 0.95698, 0.70042, 0.023387, 0.013766, 0.00055803, 0.0076904, 0.0076904, 0.0076904 + 95, 0.031977, 0.030482, 0.0019157, 0.93086, 0.91638, 0.95855, 0.70487, 0.023166, 0.01363, 0.00055095, 0.0076453, 0.0076453, 0.0076453 + 96, 0.032187, 0.03109, 0.0017565, 0.92259, 0.92444, 0.95905, 0.70611, 0.023088, 0.013612, 0.00054028, 0.0076, 0.0076, 0.0076 + 97, 0.031925, 0.031018, 0.001989, 0.92491, 0.92617, 0.9596, 0.71, 0.022818, 0.013515, 0.00053826, 0.0075544, 0.0075544, 0.0075544 + 98, 0.032034, 0.030897, 0.0019627, 0.92931, 0.92627, 0.95987, 0.71374, 0.022692, 0.013421, 0.00054928, 0.0075085, 0.0075085, 0.0075085 + 99, 0.031725, 0.030934, 0.0018566, 0.93027, 0.92301, 0.96053, 0.71402, 0.022761, 0.013394, 0.00053593, 0.0074624, 0.0074624, 0.0074624 + 100, 0.031674, 0.030482, 0.001924, 0.93416, 0.91933, 0.96113, 0.71529, 0.022636, 0.013359, 0.00053115, 0.007416, 0.007416, 0.007416 + 101, 0.03163, 0.030217, 0.0018722, 0.93881, 0.91598, 0.96133, 0.71577, 0.022488, 0.013348, 0.00053153, 0.0073694, 0.0073694, 0.0073694 + 102, 0.03144, 0.030434, 0.0018798, 0.93725, 0.91733, 0.96165, 0.71957, 0.022423, 0.013343, 0.00053883, 0.0073225, 0.0073225, 0.0073225 + 103, 0.031627, 0.030565, 0.0019597, 0.92968, 0.92722, 0.9627, 0.72016, 0.022284, 0.01327, 0.00054098, 0.0072754, 0.0072754, 0.0072754 + 104, 0.031507, 0.030353, 0.0017396, 0.93536, 0.92132, 0.96224, 0.71867, 0.022423, 0.013235, 0.00053099, 0.007228, 0.007228, 0.007228 + 105, 0.031253, 0.030393, 0.001796, 0.93123, 0.92585, 0.96318, 0.72302, 0.022277, 0.013122, 0.00052389, 0.0071804, 0.0071804, 0.0071804 + 106, 0.031145, 0.030198, 0.0017467, 0.92565, 0.93341, 0.96286, 0.72482, 0.022131, 0.013077, 0.00051062, 0.0071326, 0.0071326, 0.0071326 + 107, 0.031341, 0.030154, 0.0018748, 0.9246, 0.93208, 0.96244, 0.72565, 0.022143, 0.013081, 0.00051662, 0.0070846, 0.0070846, 0.0070846 + 108, 0.031358, 0.030044, 0.0018818, 0.92712, 0.93255, 0.96344, 0.72709, 0.022078, 0.013053, 0.00051244, 0.0070364, 0.0070364, 0.0070364 + 109, 0.031128, 0.029978, 0.0018278, 0.9279, 0.93273, 0.96365, 0.72638, 0.022065, 0.013033, 0.00051039, 0.006988, 0.006988, 0.006988 + 110, 0.031084, 0.029999, 0.0018289, 0.94672, 0.91822, 0.96447, 0.72685, 0.022053, 0.013022, 0.00050551, 0.0069394, 0.0069394, 0.0069394 + 111, 0.031086, 0.0301, 0.0017875, 0.93636, 0.92842, 0.96379, 0.72631, 0.02199, 0.013007, 0.00050105, 0.0068906, 0.0068906, 0.0068906 + 112, 0.030871, 0.030279, 0.0017857, 0.93296, 0.92934, 0.96445, 0.72781, 0.021824, 0.012947, 0.00049982, 0.0068416, 0.0068416, 0.0068416 + 113, 0.030924, 0.029967, 0.0017463, 0.93015, 0.93281, 0.96447, 0.72904, 0.02176, 0.012909, 0.00049344, 0.0067924, 0.0067924, 0.0067924 + 114, 0.030597, 0.029761, 0.0017389, 0.92814, 0.93383, 0.96415, 0.73001, 0.021668, 0.012842, 0.00049687, 0.0067431, 0.0067431, 0.0067431 + 115, 0.030879, 0.02925, 0.0016944, 0.93326, 0.93056, 0.96561, 0.73217, 0.021525, 0.012789, 0.00048768, 0.0066936, 0.0066936, 0.0066936 + 116, 0.030776, 0.029445, 0.0017794, 0.9294, 0.9359, 0.96519, 0.73201, 0.021556, 0.012802, 0.00049123, 0.006644, 0.006644, 0.006644 + 117, 0.030403, 0.029521, 0.0016875, 0.94076, 0.92621, 0.96564, 0.73311, 0.021476, 0.01273, 0.00048605, 0.0065942, 0.0065942, 0.0065942 + 118, 0.030561, 0.029263, 0.0016796, 0.92739, 0.9399, 0.96626, 0.73595, 0.021325, 0.012672, 0.0004827, 0.0065443, 0.0065443, 0.0065443 + 119, 0.030427, 0.029022, 0.0017948, 0.9419, 0.92679, 0.96626, 0.73585, 0.021322, 0.012654, 0.00048269, 0.0064942, 0.0064942, 0.0064942 + 120, 0.03029, 0.02978, 0.0017355, 0.94494, 0.92387, 0.9667, 0.736, 0.02126, 0.01264, 0.0004827, 0.006444, 0.006444, 0.006444 + 121, 0.030404, 0.029412, 0.0016721, 0.93933, 0.92775, 0.96651, 0.73646, 0.021249, 0.012631, 0.00048223, 0.0063937, 0.0063937, 0.0063937 + 122, 0.029909, 0.029093, 0.0015333, 0.93927, 0.92869, 0.96686, 0.73685, 0.021209, 0.012598, 0.00047939, 0.0063432, 0.0063432, 0.0063432 + 123, 0.030214, 0.029473, 0.0015698, 0.9357, 0.92976, 0.96695, 0.73591, 0.021207, 0.012582, 0.00047689, 0.0062927, 0.0062927, 0.0062927 + 124, 0.030143, 0.029175, 0.001577, 0.9333, 0.93246, 0.96671, 0.73715, 0.021147, 0.012552, 0.00047428, 0.006242, 0.006242, 0.006242 + 125, 0.030031, 0.028964, 0.0016265, 0.93103, 0.93546, 0.96714, 0.73816, 0.021123, 0.012514, 0.00046753, 0.0061913, 0.0061913, 0.0061913 + 126, 0.029933, 0.029055, 0.0016089, 0.93548, 0.93733, 0.96739, 0.74033, 0.021026, 0.012472, 0.00046302, 0.0061404, 0.0061404, 0.0061404 + 127, 0.029929, 0.02862, 0.0015989, 0.94244, 0.92912, 0.96714, 0.74303, 0.020943, 0.012443, 0.00046562, 0.0060895, 0.0060895, 0.0060895 + 128, 0.029768, 0.028898, 0.0015554, 0.93798, 0.93485, 0.96704, 0.74423, 0.020868, 0.012402, 0.00046234, 0.0060385, 0.0060385, 0.0060385 + 129, 0.030138, 0.029115, 0.0017076, 0.93982, 0.93429, 0.96778, 0.74406, 0.020822, 0.012387, 0.00046398, 0.0059874, 0.0059874, 0.0059874 + 130, 0.02988, 0.028473, 0.0015576, 0.93863, 0.93608, 0.96804, 0.74498, 0.020745, 0.012346, 0.00046404, 0.0059363, 0.0059363, 0.0059363 + 131, 0.029736, 0.029229, 0.0016671, 0.93761, 0.93852, 0.96861, 0.7462, 0.020705, 0.012324, 0.00046393, 0.0058851, 0.0058851, 0.0058851 + 132, 0.029466, 0.028718, 0.0016622, 0.93397, 0.94152, 0.96859, 0.74667, 0.020699, 0.012314, 0.00046488, 0.0058338, 0.0058338, 0.0058338 + 133, 0.02959, 0.028611, 0.0015762, 0.93891, 0.93564, 0.96872, 0.74864, 0.020613, 0.012275, 0.00046323, 0.0057826, 0.0057826, 0.0057826 + 134, 0.029668, 0.028581, 0.0014747, 0.94114, 0.93575, 0.9686, 0.7473, 0.020594, 0.012264, 0.00046112, 0.0057312, 0.0057312, 0.0057312 + 135, 0.029478, 0.027834, 0.0015836, 0.93839, 0.94067, 0.96876, 0.74933, 0.020507, 0.01223, 0.0004588, 0.0056799, 0.0056799, 0.0056799 + 136, 0.029168, 0.027586, 0.0014669, 0.94416, 0.9357, 0.96917, 0.75123, 0.020416, 0.012198, 0.00045634, 0.0056285, 0.0056285, 0.0056285 + 137, 0.029293, 0.028125, 0.0014719, 0.94227, 0.93624, 0.96854, 0.75204, 0.020353, 0.012157, 0.00045397, 0.0055771, 0.0055771, 0.0055771 + 138, 0.029351, 0.028426, 0.0014646, 0.94192, 0.93653, 0.96879, 0.75317, 0.020326, 0.012142, 0.00045086, 0.0055257, 0.0055257, 0.0055257 + 139, 0.029547, 0.028559, 0.0015633, 0.9434, 0.9369, 0.96951, 0.75492, 0.020274, 0.012115, 0.00044897, 0.0054743, 0.0054743, 0.0054743 + 140, 0.029355, 0.028439, 0.0014729, 0.94578, 0.93522, 0.9696, 0.75553, 0.02023, 0.012093, 0.00044546, 0.0054229, 0.0054229, 0.0054229 + 141, 0.029185, 0.028097, 0.0015469, 0.9489, 0.93295, 0.97014, 0.7576, 0.020156, 0.012058, 0.00044313, 0.0053715, 0.0053715, 0.0053715 + 142, 0.029199, 0.028219, 0.001514, 0.94845, 0.93463, 0.97055, 0.75896, 0.020134, 0.012029, 0.00044058, 0.0053201, 0.0053201, 0.0053201 + 143, 0.028854, 0.028018, 0.0014863, 0.94569, 0.93744, 0.97053, 0.76002, 0.020108, 0.012014, 0.00043915, 0.0052688, 0.0052688, 0.0052688 + 144, 0.029012, 0.027815, 0.0014816, 0.94586, 0.93747, 0.97078, 0.76097, 0.020055, 0.01199, 0.00043866, 0.0052174, 0.0052174, 0.0052174 + 145, 0.028718, 0.02767, 0.0015313, 0.94802, 0.93549, 0.97152, 0.7614, 0.019989, 0.011961, 0.00043612, 0.0051662, 0.0051662, 0.0051662 + 146, 0.028948, 0.027456, 0.0015117, 0.94287, 0.94011, 0.97105, 0.76167, 0.019971, 0.011942, 0.00043396, 0.0051149, 0.0051149, 0.0051149 + 147, 0.028562, 0.027644, 0.0014168, 0.93929, 0.9447, 0.97122, 0.76263, 0.019881, 0.01191, 0.00043333, 0.0050637, 0.0050637, 0.0050637 + 148, 0.028329, 0.027711, 0.0013818, 0.94206, 0.94094, 0.97125, 0.76319, 0.019827, 0.01189, 0.00043175, 0.0050126, 0.0050126, 0.0050126 + 149, 0.02862, 0.02787, 0.0014942, 0.94465, 0.93833, 0.97116, 0.76342, 0.019787, 0.011867, 0.0004303, 0.0049615, 0.0049615, 0.0049615 + 150, 0.028692, 0.027617, 0.0015059, 0.93826, 0.94457, 0.97115, 0.76405, 0.01975, 0.011845, 0.0004279, 0.0049105, 0.0049105, 0.0049105 + 151, 0.028401, 0.027639, 0.0014219, 0.93523, 0.94802, 0.97139, 0.76397, 0.019735, 0.011828, 0.00042624, 0.0048596, 0.0048596, 0.0048596 + 152, 0.028417, 0.027819, 0.0014894, 0.9404, 0.9442, 0.9718, 0.76517, 0.019664, 0.011806, 0.00042493, 0.0048087, 0.0048087, 0.0048087 + 153, 0.028434, 0.02737, 0.0015029, 0.94133, 0.94367, 0.9721, 0.76551, 0.019652, 0.011793, 0.00042326, 0.004758, 0.004758, 0.004758 + 154, 0.028227, 0.027425, 0.0014334, 0.93727, 0.94871, 0.97214, 0.76608, 0.01963, 0.011776, 0.00042256, 0.0047073, 0.0047073, 0.0047073 + 155, 0.028057, 0.027551, 0.001376, 0.93883, 0.94766, 0.97222, 0.76669, 0.019613, 0.011762, 0.00042078, 0.0046568, 0.0046568, 0.0046568 + 156, 0.028176, 0.027123, 0.0014116, 0.94181, 0.94512, 0.97225, 0.76714, 0.019557, 0.01174, 0.00041898, 0.0046063, 0.0046063, 0.0046063 + 157, 0.028217, 0.027208, 0.0013288, 0.94258, 0.94464, 0.97276, 0.76655, 0.019546, 0.01173, 0.00041678, 0.004556, 0.004556, 0.004556 + 158, 0.0282, 0.027404, 0.0013574, 0.94123, 0.9458, 0.97274, 0.76736, 0.019514, 0.011713, 0.00041562, 0.0045058, 0.0045058, 0.0045058 + 159, 0.028034, 0.027147, 0.0013687, 0.94151, 0.94588, 0.97267, 0.76809, 0.019473, 0.011693, 0.00041477, 0.0044557, 0.0044557, 0.0044557 + 160, 0.027894, 0.027094, 0.0013204, 0.94191, 0.94469, 0.97224, 0.76838, 0.019437, 0.011673, 0.00041311, 0.0044058, 0.0044058, 0.0044058 + 161, 0.027876, 0.026693, 0.0013466, 0.94606, 0.94065, 0.97238, 0.76871, 0.0194, 0.011653, 0.00041262, 0.004356, 0.004356, 0.004356 + 162, 0.027693, 0.026576, 0.0014032, 0.9449, 0.94204, 0.97301, 0.76877, 0.019372, 0.011633, 0.00041176, 0.0043064, 0.0043064, 0.0043064 + 163, 0.027606, 0.026767, 0.0013603, 0.9416, 0.94562, 0.97313, 0.76933, 0.019363, 0.011621, 0.0004104, 0.0042569, 0.0042569, 0.0042569 + 164, 0.027638, 0.026331, 0.0013296, 0.94463, 0.94382, 0.97318, 0.77025, 0.019327, 0.011603, 0.00040849, 0.0042076, 0.0042076, 0.0042076 + 165, 0.027503, 0.026563, 0.0013869, 0.94369, 0.94454, 0.97325, 0.77055, 0.019304, 0.011587, 0.00040758, 0.0041584, 0.0041584, 0.0041584 + 166, 0.02767, 0.026656, 0.0014014, 0.94458, 0.94379, 0.97341, 0.77086, 0.019271, 0.011574, 0.0004066, 0.0041094, 0.0041094, 0.0041094 + 167, 0.027508, 0.026558, 0.0012618, 0.94322, 0.94516, 0.97346, 0.77123, 0.019245, 0.01156, 0.00040509, 0.0040606, 0.0040606, 0.0040606 + 168, 0.027689, 0.026895, 0.0013021, 0.94335, 0.94522, 0.97351, 0.77206, 0.019214, 0.011546, 0.00040362, 0.004012, 0.004012, 0.004012 + 169, 0.027437, 0.026857, 0.0012682, 0.94499, 0.94372, 0.9736, 0.7728, 0.019194, 0.011533, 0.00040191, 0.0039636, 0.0039636, 0.0039636 + 170, 0.027218, 0.026449, 0.0013068, 0.94486, 0.94433, 0.9737, 0.77364, 0.019149, 0.011512, 0.00039986, 0.0039154, 0.0039154, 0.0039154 + 171, 0.027363, 0.026912, 0.0012651, 0.94415, 0.94519, 0.97381, 0.77396, 0.019116, 0.011493, 0.00039825, 0.0038674, 0.0038674, 0.0038674 + 172, 0.027275, 0.026379, 0.0012635, 0.94432, 0.94566, 0.97401, 0.77464, 0.019097, 0.011478, 0.00039698, 0.0038196, 0.0038196, 0.0038196 + 173, 0.02735, 0.026512, 0.0012591, 0.94381, 0.94641, 0.97404, 0.77555, 0.019092, 0.011468, 0.00039536, 0.003772, 0.003772, 0.003772 + 174, 0.027123, 0.026312, 0.0013414, 0.94694, 0.94369, 0.9745, 0.77621, 0.019066, 0.011454, 0.00039388, 0.0037246, 0.0037246, 0.0037246 + 175, 0.026798, 0.026238, 0.0012334, 0.9459, 0.945, 0.97455, 0.77659, 0.019029, 0.011437, 0.00039287, 0.0036775, 0.0036775, 0.0036775 + 176, 0.026838, 0.026685, 0.0011939, 0.94555, 0.94582, 0.97461, 0.77692, 0.019006, 0.011424, 0.0003916, 0.0036306, 0.0036306, 0.0036306 + 177, 0.026944, 0.025845, 0.0013133, 0.94413, 0.94651, 0.97454, 0.77696, 0.018987, 0.011412, 0.00039052, 0.003584, 0.003584, 0.003584 + 178, 0.026771, 0.026168, 0.0012332, 0.94663, 0.9446, 0.9747, 0.77721, 0.018969, 0.0114, 0.00038941, 0.0035376, 0.0035376, 0.0035376 + 179, 0.026718, 0.025954, 0.0011771, 0.9465, 0.94471, 0.9747, 0.77786, 0.018948, 0.011388, 0.0003879, 0.0034915, 0.0034915, 0.0034915 + 180, 0.026873, 0.025645, 0.0012796, 0.94629, 0.9449, 0.97472, 0.77793, 0.018932, 0.011376, 0.00038638, 0.0034456, 0.0034456, 0.0034456 + 181, 0.02655, 0.025873, 0.0011976, 0.94702, 0.94426, 0.97494, 0.77828, 0.018915, 0.011363, 0.0003848, 0.0034, 0.0034, 0.0034 + 182, 0.026512, 0.025808, 0.0011851, 0.94287, 0.94847, 0.9751, 0.77857, 0.018896, 0.01135, 0.00038337, 0.0033547, 0.0033547, 0.0033547 + 183, 0.026582, 0.02627, 0.0012561, 0.94416, 0.94789, 0.97516, 0.77885, 0.018881, 0.011339, 0.00038274, 0.0033096, 0.0033096, 0.0033096 + 184, 0.026566, 0.025758, 0.0011764, 0.94517, 0.94749, 0.97521, 0.77889, 0.018867, 0.011329, 0.00038169, 0.0032649, 0.0032649, 0.0032649 + 185, 0.026372, 0.02562, 0.0011666, 0.94455, 0.94808, 0.97535, 0.77933, 0.018845, 0.011317, 0.00038069, 0.0032204, 0.0032204, 0.0032204 + 186, 0.026309, 0.025389, 0.0011781, 0.94422, 0.94839, 0.97538, 0.77974, 0.018834, 0.011306, 0.00037979, 0.0031762, 0.0031762, 0.0031762 + 187, 0.026073, 0.025681, 0.0011798, 0.9448, 0.94782, 0.97545, 0.77998, 0.018809, 0.011291, 0.00037857, 0.0031323, 0.0031323, 0.0031323 + 188, 0.02628, 0.025683, 0.0011811, 0.94502, 0.94775, 0.97558, 0.78007, 0.018801, 0.011283, 0.00037741, 0.0030888, 0.0030888, 0.0030888 + 189, 0.026211, 0.02556, 0.0011498, 0.94563, 0.94694, 0.9756, 0.78027, 0.018793, 0.011275, 0.00037606, 0.0030455, 0.0030455, 0.0030455 + 190, 0.026203, 0.025736, 0.0011843, 0.94467, 0.94887, 0.97575, 0.78088, 0.018782, 0.011266, 0.00037511, 0.0030026, 0.0030026, 0.0030026 + 191, 0.026092, 0.025222, 0.0011084, 0.94461, 0.94925, 0.97586, 0.78097, 0.018765, 0.011255, 0.00037424, 0.00296, 0.00296, 0.00296 + 192, 0.025787, 0.025122, 0.0011256, 0.94511, 0.94867, 0.97585, 0.78106, 0.018747, 0.011244, 0.00037329, 0.0029177, 0.0029177, 0.0029177 + 193, 0.025693, 0.02537, 0.0011063, 0.94518, 0.94941, 0.97594, 0.78108, 0.018741, 0.011236, 0.00037235, 0.0028758, 0.0028758, 0.0028758 + 194, 0.025988, 0.025438, 0.001105, 0.94551, 0.94925, 0.97606, 0.78141, 0.018732, 0.011228, 0.00037134, 0.0028342, 0.0028342, 0.0028342 + 195, 0.025879, 0.025049, 0.0010788, 0.94545, 0.94942, 0.97606, 0.78146, 0.018724, 0.011219, 0.00037006, 0.002793, 0.002793, 0.002793 + 196, 0.025674, 0.025283, 0.0010989, 0.95161, 0.944, 0.97614, 0.78186, 0.018708, 0.011207, 0.00036911, 0.0027521, 0.0027521, 0.0027521 + 197, 0.025626, 0.024832, 0.0011515, 0.9512, 0.9443, 0.97617, 0.78212, 0.018695, 0.011199, 0.00036833, 0.0027116, 0.0027116, 0.0027116 + 198, 0.025844, 0.024872, 0.0010776, 0.95173, 0.94425, 0.97629, 0.78226, 0.018678, 0.011189, 0.00036704, 0.0026714, 0.0026714, 0.0026714 + 199, 0.025465, 0.025325, 0.0011225, 0.94661, 0.94917, 0.97628, 0.78303, 0.018665, 0.01118, 0.00036603, 0.0026316, 0.0026316, 0.0026316 + 200, 0.025527, 0.024989, 0.0010598, 0.94617, 0.94995, 0.97637, 0.78313, 0.018656, 0.011173, 0.00036502, 0.0025922, 0.0025922, 0.0025922 + 201, 0.025748, 0.025146, 0.0011141, 0.94613, 0.95052, 0.9764, 0.78326, 0.01864, 0.011162, 0.00036406, 0.0025531, 0.0025531, 0.0025531 + 202, 0.025409, 0.024831, 0.0011546, 0.9465, 0.95017, 0.97644, 0.78347, 0.01863, 0.011153, 0.0003634, 0.0025145, 0.0025145, 0.0025145 + 203, 0.025368, 0.024999, 0.0011253, 0.94593, 0.95091, 0.97654, 0.78358, 0.018615, 0.011144, 0.00036261, 0.0024762, 0.0024762, 0.0024762 + 204, 0.025462, 0.024781, 0.0010522, 0.94723, 0.95054, 0.97654, 0.78411, 0.018598, 0.011135, 0.00036172, 0.0024383, 0.0024383, 0.0024383 + 205, 0.025092, 0.024677, 0.001075, 0.94759, 0.95013, 0.97661, 0.78421, 0.018592, 0.011128, 0.00036081, 0.0024009, 0.0024009, 0.0024009 + 206, 0.02531, 0.024853, 0.001165, 0.94811, 0.94962, 0.97669, 0.78416, 0.018575, 0.011117, 0.00036011, 0.0023638, 0.0023638, 0.0023638 + 207, 0.025006, 0.025002, 0.0010837, 0.94798, 0.9496, 0.97664, 0.78407, 0.018564, 0.011108, 0.00035923, 0.0023271, 0.0023271, 0.0023271 + 208, 0.025096, 0.024685, 0.001042, 0.94838, 0.94932, 0.97673, 0.78436, 0.018554, 0.0111, 0.00035855, 0.0022909, 0.0022909, 0.0022909 + 209, 0.025094, 0.02437, 0.001032, 0.94821, 0.94959, 0.97672, 0.78447, 0.018543, 0.011093, 0.00035757, 0.002255, 0.002255, 0.002255 + 210, 0.024942, 0.024652, 0.0010072, 0.94897, 0.94858, 0.97671, 0.78477, 0.018531, 0.011084, 0.00035669, 0.0022196, 0.0022196, 0.0022196 + 211, 0.024847, 0.024588, 0.0010305, 0.94932, 0.94842, 0.97679, 0.78515, 0.01852, 0.011077, 0.0003558, 0.0021847, 0.0021847, 0.0021847 + 212, 0.024705, 0.024318, 0.0010271, 0.9503, 0.94779, 0.97683, 0.78519, 0.018513, 0.01107, 0.00035498, 0.0021501, 0.0021501, 0.0021501 + 213, 0.024903, 0.024453, 0.001035, 0.95034, 0.94761, 0.97679, 0.78533, 0.018503, 0.011062, 0.00035397, 0.002116, 0.002116, 0.002116 + 214, 0.02463, 0.024552, 0.0010003, 0.95126, 0.94688, 0.97685, 0.78539, 0.018496, 0.011056, 0.0003532, 0.0020823, 0.0020823, 0.0020823 + 215, 0.024861, 0.024322, 0.00099174, 0.9451, 0.95312, 0.97688, 0.78546, 0.018488, 0.01105, 0.0003522, 0.0020491, 0.0020491, 0.0020491 + 216, 0.024618, 0.024012, 0.00099665, 0.94572, 0.95288, 0.9769, 0.78554, 0.018489, 0.011046, 0.00035145, 0.0020164, 0.0020164, 0.0020164 + 217, 0.024736, 0.024252, 0.00094247, 0.94569, 0.95329, 0.97692, 0.7858, 0.018467, 0.011037, 0.00035043, 0.001984, 0.001984, 0.001984 + 218, 0.024535, 0.024343, 0.00097918, 0.94655, 0.95268, 0.97698, 0.78589, 0.018462, 0.011031, 0.00034969, 0.0019522, 0.0019522, 0.0019522 + 219, 0.024565, 0.024088, 0.00095765, 0.94644, 0.9527, 0.97697, 0.78576, 0.018462, 0.011027, 0.00034858, 0.0019208, 0.0019208, 0.0019208 + 220, 0.024552, 0.02355, 0.00093923, 0.94746, 0.95224, 0.97701, 0.78558, 0.018464, 0.011024, 0.00034775, 0.0018899, 0.0018899, 0.0018899 + 221, 0.024299, 0.023887, 0.00093367, 0.94739, 0.95225, 0.97705, 0.78565, 0.018461, 0.011018, 0.00034688, 0.0018594, 0.0018594, 0.0018594 + 222, 0.024468, 0.024061, 0.00097225, 0.94842, 0.95135, 0.97706, 0.78595, 0.01845, 0.011011, 0.00034611, 0.0018294, 0.0018294, 0.0018294 + 223, 0.024305, 0.02406, 0.0010037, 0.94759, 0.9522, 0.9772, 0.78583, 0.018452, 0.011007, 0.00034519, 0.0017999, 0.0017999, 0.0017999 + 224, 0.024215, 0.02361, 0.00094287, 0.94678, 0.95372, 0.97724, 0.78605, 0.018455, 0.011003, 0.00034428, 0.0017709, 0.0017709, 0.0017709 + 225, 0.024253, 0.024001, 0.00093387, 0.94784, 0.95264, 0.97728, 0.78583, 0.018456, 0.010997, 0.00034347, 0.0017424, 0.0017424, 0.0017424 + 226, 0.024073, 0.023978, 0.00089401, 0.948, 0.95281, 0.97732, 0.78581, 0.018454, 0.010992, 0.00034266, 0.0017144, 0.0017144, 0.0017144 + 227, 0.024053, 0.023842, 0.00087693, 0.94813, 0.95261, 0.97734, 0.78611, 0.018446, 0.010986, 0.00034178, 0.0016868, 0.0016868, 0.0016868 + 228, 0.024033, 0.023367, 0.0008828, 0.94872, 0.95227, 0.9774, 0.78618, 0.018448, 0.01098, 0.0003411, 0.0016598, 0.0016598, 0.0016598 + 229, 0.023988, 0.023182, 0.00093026, 0.94874, 0.95237, 0.97743, 0.78641, 0.018434, 0.010973, 0.00034019, 0.0016332, 0.0016332, 0.0016332 + 230, 0.024168, 0.023596, 0.00092003, 0.94839, 0.95273, 0.97748, 0.78661, 0.018424, 0.010966, 0.00033947, 0.0016072, 0.0016072, 0.0016072 + 231, 0.023871, 0.023681, 0.00093079, 0.94897, 0.95251, 0.97754, 0.787, 0.018414, 0.010959, 0.00033864, 0.0015816, 0.0015816, 0.0015816 + 232, 0.023931, 0.023383, 0.0009141, 0.94885, 0.95253, 0.97752, 0.78704, 0.018407, 0.010953, 0.00033811, 0.0015566, 0.0015566, 0.0015566 + 233, 0.023746, 0.023034, 0.00096963, 0.94911, 0.95235, 0.97758, 0.78714, 0.018399, 0.010945, 0.00033733, 0.0015321, 0.0015321, 0.0015321 + 234, 0.023794, 0.023468, 0.0009015, 0.94959, 0.95189, 0.97761, 0.78724, 0.018385, 0.010937, 0.00033666, 0.0015081, 0.0015081, 0.0015081 + 235, 0.023959, 0.023267, 0.00085276, 0.9495, 0.95196, 0.97762, 0.78714, 0.018379, 0.01093, 0.00033576, 0.0014847, 0.0014847, 0.0014847 + 236, 0.023771, 0.023133, 0.00093799, 0.94949, 0.95199, 0.97766, 0.78736, 0.018374, 0.010924, 0.00033506, 0.0014617, 0.0014617, 0.0014617 + 237, 0.023741, 0.023611, 0.00087418, 0.94949, 0.95207, 0.97771, 0.78743, 0.018367, 0.010918, 0.00033415, 0.0014393, 0.0014393, 0.0014393 + 238, 0.023811, 0.023444, 0.00086828, 0.95005, 0.95154, 0.97777, 0.78746, 0.01836, 0.010913, 0.00033344, 0.0014174, 0.0014174, 0.0014174 + 239, 0.023598, 0.023339, 0.00098254, 0.9502, 0.95147, 0.97784, 0.78738, 0.018348, 0.010907, 0.00033266, 0.001396, 0.001396, 0.001396 + 240, 0.023854, 0.023294, 0.00095112, 0.9501, 0.95169, 0.9779, 0.78735, 0.01834, 0.010901, 0.00033199, 0.0013752, 0.0013752, 0.0013752 + 241, 0.023566, 0.023418, 0.00093447, 0.95016, 0.95184, 0.97792, 0.78757, 0.018323, 0.010893, 0.00033093, 0.0013549, 0.0013549, 0.0013549 + 242, 0.023388, 0.023061, 0.00089959, 0.95102, 0.95119, 0.97789, 0.78794, 0.018306, 0.010884, 0.00033017, 0.0013352, 0.0013352, 0.0013352 + 243, 0.023478, 0.022921, 0.00093788, 0.95098, 0.9514, 0.97793, 0.7881, 0.018295, 0.010876, 0.00032922, 0.001316, 0.001316, 0.001316 + 244, 0.023377, 0.022822, 0.00087479, 0.95079, 0.95169, 0.97796, 0.78829, 0.018284, 0.010869, 0.00032845, 0.0012974, 0.0012974, 0.0012974 + 245, 0.023435, 0.023044, 0.00085692, 0.95086, 0.95196, 0.9781, 0.78878, 0.018272, 0.010862, 0.00032753, 0.0012793, 0.0012793, 0.0012793 + 246, 0.023485, 0.022825, 0.00088969, 0.95053, 0.95227, 0.97807, 0.7886, 0.018266, 0.010857, 0.0003269, 0.0012617, 0.0012617, 0.0012617 + 247, 0.023269, 0.022876, 0.0008566, 0.9509, 0.95198, 0.97815, 0.78891, 0.018249, 0.010849, 0.00032594, 0.0012447, 0.0012447, 0.0012447 + 248, 0.023261, 0.022908, 0.00089699, 0.95173, 0.95113, 0.9782, 0.78901, 0.018235, 0.01084, 0.00032535, 0.0012283, 0.0012283, 0.0012283 + 249, 0.023112, 0.022519, 0.00081582, 0.95092, 0.95176, 0.97825, 0.78937, 0.018216, 0.010831, 0.00032449, 0.0012124, 0.0012124, 0.0012124 + 250, 0.023363, 0.023201, 0.0008692, 0.95058, 0.95212, 0.9783, 0.78957, 0.018195, 0.010822, 0.00032384, 0.001197, 0.001197, 0.001197 + 251, 0.023323, 0.022968, 0.00087491, 0.95074, 0.95195, 0.97833, 0.79, 0.018187, 0.010816, 0.00032288, 0.0011823, 0.0011823, 0.0011823 + 252, 0.023054, 0.022935, 0.00084765, 0.9506, 0.95216, 0.97838, 0.79009, 0.018171, 0.010807, 0.00032223, 0.0011681, 0.0011681, 0.0011681 + 253, 0.023316, 0.022815, 0.00089777, 0.95144, 0.95146, 0.97845, 0.79043, 0.018162, 0.010801, 0.00032136, 0.0011544, 0.0011544, 0.0011544 + 254, 0.023012, 0.023171, 0.00079207, 0.95197, 0.95105, 0.97847, 0.79068, 0.018149, 0.010792, 0.00032062, 0.0011414, 0.0011414, 0.0011414 + 255, 0.023001, 0.022779, 0.00084312, 0.95199, 0.95109, 0.97849, 0.7911, 0.01814, 0.010787, 0.00031971, 0.0011289, 0.0011289, 0.0011289 + 256, 0.023055, 0.022861, 0.00085312, 0.95211, 0.95113, 0.97853, 0.79066, 0.018138, 0.010781, 0.00031911, 0.0011169, 0.0011169, 0.0011169 + 257, 0.023075, 0.022773, 0.0008302, 0.95192, 0.95129, 0.97851, 0.79087, 0.018136, 0.010776, 0.00031823, 0.0011056, 0.0011056, 0.0011056 + 258, 0.023504, 0.022396, 0.00087311, 0.94972, 0.9537, 0.97853, 0.79107, 0.018127, 0.010769, 0.00031758, 0.0010948, 0.0010948, 0.0010948 + 259, 0.022834, 0.022611, 0.00089442, 0.95007, 0.95365, 0.97857, 0.79113, 0.018124, 0.010765, 0.00031671, 0.0010846, 0.0010846, 0.0010846 + 260, 0.022897, 0.022852, 0.00086963, 0.95035, 0.95375, 0.97854, 0.79132, 0.018113, 0.010759, 0.00031601, 0.001075, 0.001075, 0.001075 + 261, 0.022852, 0.022663, 0.00086594, 0.95423, 0.95022, 0.97858, 0.79158, 0.018103, 0.010752, 0.00031511, 0.0010659, 0.0010659, 0.0010659 + 262, 0.023196, 0.022795, 0.00086592, 0.95387, 0.95043, 0.9786, 0.79147, 0.018095, 0.010745, 0.00031441, 0.0010574, 0.0010574, 0.0010574 + 263, 0.023181, 0.022647, 0.00081733, 0.95413, 0.95034, 0.97859, 0.79166, 0.018088, 0.01074, 0.00031355, 0.0010495, 0.0010495, 0.0010495 + 264, 0.022983, 0.022761, 0.00080353, 0.96183, 0.94321, 0.97861, 0.79187, 0.018076, 0.010731, 0.00031293, 0.0010422, 0.0010422, 0.0010422 + 265, 0.023054, 0.02249, 0.00079835, 0.95871, 0.94608, 0.97869, 0.792, 0.018057, 0.010721, 0.00031199, 0.0010355, 0.0010355, 0.0010355 + 266, 0.022864, 0.022324, 0.00080302, 0.96177, 0.9435, 0.97873, 0.79265, 0.018048, 0.010714, 0.00031134, 0.0010293, 0.0010293, 0.0010293 + 267, 0.02276, 0.022686, 0.00076653, 0.95231, 0.95269, 0.9788, 0.79298, 0.018038, 0.010707, 0.00031046, 0.0010238, 0.0010238, 0.0010238 + 268, 0.022786, 0.022673, 0.00079754, 0.95208, 0.95319, 0.97877, 0.79287, 0.018042, 0.010704, 0.00030985, 0.0010188, 0.0010188, 0.0010188 + 269, 0.022564, 0.02231, 0.00082056, 0.95211, 0.9533, 0.97883, 0.79309, 0.018035, 0.010699, 0.00030894, 0.0010144, 0.0010144, 0.0010144 + 270, 0.022779, 0.022719, 0.00082402, 0.95211, 0.95343, 0.97885, 0.79325, 0.018034, 0.010696, 0.00030828, 0.0010106, 0.0010106, 0.0010106 + 271, 0.022751, 0.02205, 0.00087847, 0.95255, 0.9531, 0.97889, 0.7934, 0.018016, 0.010686, 0.00030736, 0.0010073, 0.0010073, 0.0010073 + 272, 0.022804, 0.02255, 0.00082927, 0.95279, 0.95309, 0.97894, 0.79359, 0.018001, 0.010677, 0.00030664, 0.0010047, 0.0010047, 0.0010047 + 273, 0.022662, 0.022418, 0.00088235, 0.95293, 0.95312, 0.97898, 0.79377, 0.017987, 0.010669, 0.0003058, 0.0010026, 0.0010026, 0.0010026 + 274, 0.022752, 0.022371, 0.00084484, 0.9532, 0.95294, 0.97905, 0.79388, 0.017978, 0.010662, 0.00030512, 0.0010012, 0.0010012, 0.0010012 diff --git a/resources/yolo_models/2022-0601/results.png b/resources/yolo_models/2022-0601/results.png new file mode 100644 index 00000000..9d0bb686 Binary files /dev/null and b/resources/yolo_models/2022-0601/results.png differ diff --git a/resources/yolo_models/2022-0601/train_batch0.jpg b/resources/yolo_models/2022-0601/train_batch0.jpg new file mode 100644 index 00000000..3ddab8c9 Binary files /dev/null and b/resources/yolo_models/2022-0601/train_batch0.jpg differ diff --git a/resources/yolo_models/2022-0601/train_batch1.jpg b/resources/yolo_models/2022-0601/train_batch1.jpg new file mode 100644 index 00000000..04bc7dc3 Binary files /dev/null and b/resources/yolo_models/2022-0601/train_batch1.jpg differ diff --git a/resources/yolo_models/2022-0601/train_batch2.jpg b/resources/yolo_models/2022-0601/train_batch2.jpg new file mode 100644 index 00000000..a495eba1 Binary files /dev/null and b/resources/yolo_models/2022-0601/train_batch2.jpg differ diff --git a/resources/yolo_models/2022-0601/val_batch0_labels.jpg b/resources/yolo_models/2022-0601/val_batch0_labels.jpg new file mode 100644 index 00000000..4a2857ff Binary files /dev/null and b/resources/yolo_models/2022-0601/val_batch0_labels.jpg differ diff --git a/resources/yolo_models/2022-0601/val_batch0_pred.jpg b/resources/yolo_models/2022-0601/val_batch0_pred.jpg new file mode 100644 index 00000000..5c7c60c0 Binary files /dev/null and b/resources/yolo_models/2022-0601/val_batch0_pred.jpg differ diff --git a/resources/yolo_models/2022-0601/val_batch1_labels.jpg b/resources/yolo_models/2022-0601/val_batch1_labels.jpg new file mode 100644 index 00000000..01dbcc9f Binary files /dev/null and b/resources/yolo_models/2022-0601/val_batch1_labels.jpg differ diff --git a/resources/yolo_models/2022-0601/val_batch1_pred.jpg b/resources/yolo_models/2022-0601/val_batch1_pred.jpg new file mode 100644 index 00000000..81b4d2a2 Binary files /dev/null and b/resources/yolo_models/2022-0601/val_batch1_pred.jpg differ diff --git a/resources/yolo_models/2022-0601/val_batch2_labels.jpg b/resources/yolo_models/2022-0601/val_batch2_labels.jpg new file mode 100644 index 00000000..8937b370 Binary files /dev/null and b/resources/yolo_models/2022-0601/val_batch2_labels.jpg differ diff --git a/resources/yolo_models/2022-0601/val_batch2_pred.jpg b/resources/yolo_models/2022-0601/val_batch2_pred.jpg new file mode 100644 index 00000000..aae7660c Binary files /dev/null and b/resources/yolo_models/2022-0601/val_batch2_pred.jpg differ diff --git a/resources/yolo_models/2022-0601/weights/best.pt b/resources/yolo_models/2022-0601/weights/best.pt new file mode 100644 index 00000000..f77d4e10 Binary files /dev/null and b/resources/yolo_models/2022-0601/weights/best.pt differ diff --git a/run.py b/run.py index 9b317696..0a4531cf 100644 --- a/run.py +++ b/run.py @@ -13,15 +13,11 @@ import os import sys import time - import yaml import rich - import core import interfaces - from logging import config -from rich import logging def setup_logger(level) -> logging.Logger: @@ -50,47 +46,72 @@ def main() -> None: :return: None """ + # Add the examples' folder to our path, so we can run example files + sys.path.insert(0, "example/") + + # Add the unit test folder to our path, so we can run tests + sys.path.insert(0, "tests/unit/") + + # Initialize the rovecomm node + core.rovecomm_node = core.RoveComm(11000, ("127.0.0.1", 11111)) # Parse arguments for autonomy parser = argparse.ArgumentParser() # Optional: Maps the file name to a known module if found - parser.add_argument( - "--file", - help="Specify the name of the custom module to be run", - default="autonomy.py" - ) + parser.add_argument("--file", help="Specify the name of the custom module to be run", default="autonomy.py") # Optional: Sets the logging level for autonomy parser.add_argument( "--level", help="Specify the logging level to be used", choices=["DEBUG", "INFO", "WARN", "CRITICAL", "ERROR"], - default="INFO" + default="INFO", ) # Optional: Sets the vision system to be used parser.add_argument( - "--vision", - help="Specify the vision system for autonomy", - choices=["ZED", "SIM"], - default="ZED" + "--vision", help="Specify the vision system for autonomy", choices=["ZED", "SIM"], default="ZED" ) # Optional: Sets whether we are streaming or not + parser.add_argument("--stream", help="Specify if we are streaming", choices=["Y", "N"], default="N") + + # Optional: Sets the mode of operation parser.add_argument( - "--stream", - help="Specify if we are streaming", - choices=["Y", "N"], - default="N" + "--mode", help="Sets if we are running on rover or on sim", choices=["REGULAR", "SIM"], default="REGULAR" ) - # Optional: Sets the mode of operation + # Optional argument for obstacle avoidance toggle. + parser.add_argument( + "--obstacle-avoidance", + choices=["ENABLE", "DISABLE"], + default="DISABLE", + help="Enable or disable YOLO algorithm for obstacle detection.", + ) + + # Add optional argument for selecting yolo classes. + parser.add_argument( + "--yolo-classes", + nargs="+", + type=int, + help="filter by class(corresponds to order of classes in dataset .yaml file): --classes 0, or --classes 0 2 3", + ) + + # Add optional argument for zed relative distance toggle. + parser.add_argument( + "--relative-positioning", + choices=["ENABLE", "DISABLE"], + default="ENABLE", + help="Toggle between using GPS positioning from Rovecomm or relative ZED positional tracking. ZED positioning still using GPS to initially align rover UTM positionwith periodic adjustments in idle state.", + ) + + # Add optional argument for zed absolute magnetometer toggle. parser.add_argument( - "--mode", - help="Sets if we are running on rover or on sim", - choices=["REGULAR", "SIM"], - default="REGULAR" + "--zed-magnetometer", + choices=["ENABLE", "DISABLE"], + default="DISABLE", + help="Toggle between using GPS heading from Rovecomm or ZED built-in magnetometer for absolute compass heading. ZED MUST BE CALIBRATED TO ENVIRONMENT OR VALUES WILL BE BAD!", ) args = parser.parse_args() @@ -98,27 +119,38 @@ def main() -> None: parser.print_help() exit(1) + # Enable the logger, also pass-in optional logging level for console output + logger = setup_logger(level) + # SIM mode defaults vision subsystem to also originate from simulator if args.mode == "SIM": args.vision = "SIM" - # Add the examples' folder to our path, so we can run example files - sys.path.insert(0, "example/") - - # Add the unit test folder to our path, so we can run tests - sys.path.insert(0, "tests/unit/") - - # Enable the logger, also pass-in optional logging level for console output - logger = setup_logger(level) - - # Initialize the rovecomm node - core.rovecomm_node = core.RoveComm(11000, ("127.0.0.1", 11111)) + # Make sure SIM mode is off when relative distance is enabled. + if args.relative_positioning == "ENABLE" and (args.mode == "SIM" or args.vision != "ZED"): + # Print warning message. + logger.warning("ZED relative positioning is not available when mode is SIM or vision mode isn't ZED") + # Force off. + args.relative_positioning = "DISABLE" + # Make sure SIM mode is off when relative distance is enabled. + if args.zed_magnetometer == "ENABLE" and (args.mode == "SIM" or args.vision != "ZED"): + # Print warning message. + logger.warning("ZED magnetometer heading is not available when mode is SIM or vision mode isn't ZED") + # Force off. + args.zed_magnetometer = "DISABLE" # Initialize the core handlers (excluding vision) core.setup(args.mode) # Initialize the core vision components - core.vision.setup(args.vision, args.stream) + core.vision.setup( + args.vision, + args.stream, + args.obstacle_avoidance, + args.yolo_classes, + args.relative_positioning, + args.zed_magnetometer, + ) # Initialize the Interfaces interfaces.setup() diff --git a/static_ip.sh b/static_ip.sh new file mode 100755 index 00000000..67c36cc7 --- /dev/null +++ b/static_ip.sh @@ -0,0 +1,54 @@ +#!/bin/bash + +NETWORK=/etc/network/interfaces + +if [ $1 = "on" ]; then + echo "Turning On - Static IP" + + echo "# interfaces(5) file used by ifup(8) and ifdown(8)" > "${NETWORK}" + echo "# Include files from /etc/network/interfaces.d:" >> "${NETWORK}" + echo "source-directory /etc/network/interface" >> "${NETWORK}" + echo "" >> "${NETWORK}" + echo "# Set static ip on ethernet interface of 192.168.1.139" >> "${NETWORK}" + echo "allow-hotplug eth0" >> "${NETWORK}" + echo "iface eth0 inet static" >> "${NETWORK}" + echo " address 192.168.1.139" >> "${NETWORK}" + echo " netmask 255.255.255.0" >> "${NETWORK}" + echo " gateway 192.168.0.1" >> "${NETWORK}" + echo " dns-nameservers 4.4.4.4" >> "${NETWORK}" + echo " dns-nameservers 8.8.8.8" >> "${NETWORK}" + echo "" >> "${NETWORK}" + + echo "Static IP has been turned ON" +elif [ $1 = "off" ]; then + echo "Turning Off - Static IP" + + echo "# interfaces(5) file used by ifup(8) and ifdown(8)" > "${NETWORK}" + echo "# Include files from /etc/network/interfaces.d:" >> "${NETWORK}" + echo "source-directory /etc/network/interface" >> "${NETWORK}" + echo "" >> "${NETWORK}" + echo "# Set static ip on ethernet interface of 192.168.1.139" >> "${NETWORK}" + echo "#allow-hotplug eth0" >> "${NETWORK}" + echo "#iface eth0 inet static" >> "${NETWORK}" + echo "# address 192.168.1.139" >> "${NETWORK}" + echo "# netmask 255.255.255.0" >> "${NETWORK}" + echo "# gateway 192.168.0.1" >> "${NETWORK}" + echo "# dns-nameservers 4.4.4.4" >> "${NETWORK}" + echo "# dns-nameservers 8.8.8.8" >> "${NETWORK}" + echo "" >> "${NETWORK}" + + echo "Static IP has been turned OFF" + echo "Make sure to disconnect from the network before trying to reach the internet!" +fi + +if [ $1 = "on" ] || [ $1 = "off" ]; then + echo "Restarting network-manager" + service network-manager restart + echo "Restarting networking" + service networking restart + echo "Restart Complete" +else + echo "Error: Static Preference not given" + echo "Example On: sudo ./static_ip.sh on" + echo "Example Off: sudo ./static_ip.sh off" +fi diff --git a/tests/unit/gps_navigate_test.py b/tests/unit/gps_navigate_test.py index 88884729..236d876d 100644 --- a/tests/unit/gps_navigate_test.py +++ b/tests/unit/gps_navigate_test.py @@ -78,7 +78,7 @@ def test_calculate_move_right(): left, right = gps_nav.calculate_move(goal_coord, current_coord, rolla_coord) # should be turning to the right - assert right == constants.MIN_DRIVE_POWER + assert right == constants.MIN_DRIVE_POWER or right == 0 assert left > 0 @@ -92,7 +92,7 @@ def test_calculate_move_left(): # should be turning to the left assert right > 0 - assert left == constants.MIN_DRIVE_POWER + assert left == constants.MIN_DRIVE_POWER or left == 0 def test_calculate_move_straight():