├── LICENSE ├── LPRNet_Pytorch ├── .idea │ ├── .gitignore │ ├── LPRNet_Pytorch.iml │ ├── inspectionProfiles │ │ ├── Project_Default.xml │ │ └── profiles_settings.xml │ ├── misc.xml │ └── modules.xml ├── data │ ├── NotoSansCJK-Regular.ttc │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-37.pyc │ │ ├── __init__.cpython-38.pyc │ │ ├── load_data.cpython-37.pyc │ │ └── load_data.cpython-38.pyc │ ├── load_data.py │ └── test │ │ ├── 京PL3N67.jpg │ │ ├── 川JK0707.jpg │ │ ├── 川X90621.jpg │ │ ├── 沪AMS087.jpg │ │ ├── 沪C21F13.jpg │ │ ├── 沪C8GK31.jpg │ │ ├── 皖A00E66.jpg │ │ ├── 皖A0C333.jpg │ │ ├── 皖A0C911.jpg │ │ ├── 苏A0X3B2.jpg │ │ ├── 苏A53D97.jpg │ │ ├── 苏A57NT9.jpg │ │ ├── 苏A8DC31.jpg │ │ ├── 苏AP48A8.jpg │ │ ├── 苏B810FT.jpg │ │ ├── 苏BH828L.jpg │ │ ├── 苏E5YR23.jpg │ │ ├── 苏E7R5Y0.jpg │ │ ├── 苏E9CD08.jpg │ │ ├── 苏EW0806.jpg │ │ ├── 苏EYV501.jpg │ │ ├── 苏G2F335.jpg │ │ ├── 苏HXN335.jpg │ │ ├── 闽D33U29.jpg │ │ ├── 鲁AW9V20.jpg │ │ ├── 鲁BE31L9.jpg │ │ ├── 鲁Q08F99.jpg │ │ └── 鲁R8D57Z.jpg ├── model │ ├── LPRNet.py │ ├── __init__.py │ └── __pycache__ │ │ ├── LPRNet.cpython-37.pyc │ │ └── __init__.cpython-37.pyc ├── predict_data.csv ├── test.py ├── train.py └── weights │ └── Final_LPRNet_model.pth ├── README.md └── Yolov7 ├── VOCCCPDlicense └── images │ └── try │ ├── 0275-93_75-201&483_486&587-491&584_211&566_183&474_463&492-0_0_27_14_28_29_29-93-58.jpg │ ├── 0275-93_82-352&510_649&606-629&619_349&588_339&500_619&531-0_0_28_28_21_33_29-84-25.jpg │ ├── 03-91_90-283&402_600&524-589&515_285&521_296&411_600&405-0_0_22_27_1_24_32-154-73.jpg │ └── 03-92_86-111&425_419&538-427&544_98&523_105&413_434&434-0_0_23_32_32_32_33-137-60.jpg ├── cfg └── training │ └── yolov7-e6e-ccpd.yaml ├── data ├── hyp.scratch.custom.yaml └── license.yaml ├── detect.py ├── models ├── __pycache__ │ ├── common.cpython-37.pyc │ ├── experimental.cpython-37.pyc │ └── yolo.cpython-37.pyc ├── common.py ├── experimental.py └── yolo.py ├── runs └── detect │ └── exp │ ├── 0275-93_75-201&483_486&587-491&584_211&566_183&474_463&492-0_0_27_14_28_29_29-93-58.jpg │ ├── 0275-93_82-352&510_649&606-629&619_349&588_339&500_619&531-0_0_28_28_21_33_29-84-25.jpg │ ├── 03-91_90-283&402_600&524-589&515_285&521_296&411_600&405-0_0_22_27_1_24_32-154-73.jpg │ ├── 03-92_86-111&425_419&538-427&544_98&523_105&413_434&434-0_0_23_32_32_32_33-137-60.jpg │ └── labels │ ├── 0275-93_75-201&483_486&587-491&584_211&566_183&474_463&492-0_0_27_14_28_29_29-93-58.txt │ ├── 0275-93_82-352&510_649&606-629&619_349&588_339&500_619&531-0_0_28_28_21_33_29-84-25.txt │ ├── 03-91_90-283&402_600&524-589&515_285&521_296&411_600&405-0_0_22_27_1_24_32-154-73.txt │ └── 03-92_86-111&425_419&538-427&544_98&523_105&413_434&434-0_0_23_32_32_32_33-137-60.txt └── utils ├── __pycache__ ├── autoanchor.cpython-37.pyc ├── datasets.cpython-37.pyc ├── general.cpython-37.pyc ├── google_utils.cpython-37.pyc ├── loss.cpython-37.pyc ├── metrics.cpython-37.pyc ├── plots.cpython-37.pyc └── torch_utils.cpython-37.pyc ├── activations.py ├── add_nms.py ├── autoanchor.py ├── datasets.py ├── general.py ├── google_utils.py ├── loss.py ├── metrics.py ├── plots.py └── torch_utils.py /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LPRNet_Pytorch/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # 默认忽略的文件 2 | /shelf/ 3 | /workspace.xml 4 | # 基于编辑器的 HTTP 客户端请求 5 | /httpRequests/ 6 | # Datasource local storage ignored files 7 | /dataSources/ 8 | /dataSources.local.xml 9 | -------------------------------------------------------------------------------- /LPRNet_Pytorch/.idea/LPRNet_Pytorch.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 12 | -------------------------------------------------------------------------------- /LPRNet_Pytorch/.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 13 | -------------------------------------------------------------------------------- /LPRNet_Pytorch/.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /LPRNet_Pytorch/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /LPRNet_Pytorch/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/NotoSansCJK-Regular.ttc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/NotoSansCJK-Regular.ttc -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # @Author: fanstuck 3 | # @Time: 2023/9/25 10:42 4 | # @File: __init__.py 5 | from .load_data import * -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/__pycache__/__init__.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/__pycache__/__init__.cpython-37.pyc -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/__pycache__/__init__.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/__pycache__/__init__.cpython-38.pyc -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/__pycache__/load_data.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/__pycache__/load_data.cpython-37.pyc -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/__pycache__/load_data.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/__pycache__/load_data.cpython-38.pyc -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/load_data.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # @Author: fanstuck 3 | # @Time: 2023/9/25 10:41 4 | # @File: load_data.py 5 | from torch.utils.data import * 6 | from imutils import paths 7 | import numpy as np 8 | import random 9 | import cv2 10 | import os 11 | 12 | CHARS = ['京', '沪', '津', '渝', '冀', '晋', '蒙', '辽', '吉', '黑', 13 | '苏', '浙', '皖', '闽', '赣', '鲁', '豫', '鄂', '湘', '粤', 14 | '桂', '琼', '川', '贵', '云', '藏', '陕', '甘', '青', '宁', 15 | '新', 16 | '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 17 | 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 18 | 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 19 | 'W', 'X', 'Y', 'Z', 'I', 'O', '-' 20 | ] 21 | 22 | CHARS_DICT = {char:i for i, char in enumerate(CHARS)} 23 | 24 | class LPRDataLoader(Dataset): 25 | def __init__(self, img_dir, imgSize, lpr_max_len, PreprocFun=None): 26 | self.img_dir = img_dir 27 | self.img_paths = [] 28 | for i in range(len(img_dir)): 29 | self.img_paths += [el for el in paths.list_images(img_dir[i])] 30 | random.shuffle(self.img_paths) 31 | self.img_size = imgSize 32 | self.lpr_max_len = lpr_max_len 33 | if PreprocFun is not None: 34 | self.PreprocFun = PreprocFun 35 | else: 36 | self.PreprocFun = self.transform 37 | 38 | def __len__(self): 39 | return len(self.img_paths) 40 | 41 | def __getitem__(self, index): 42 | filename = self.img_paths[index] 43 | Image = cv2.imdecode(np.fromfile(filename, dtype=np.uint8), -1) 44 | Image = cv2.cvtColor(Image, cv2.COLOR_RGB2BGR) 45 | height, width, _ = Image.shape 46 | if height != self.img_size[1] or width != self.img_size[0]: 47 | Image = cv2.resize(Image, self.img_size) 48 | Image = self.PreprocFun(Image) 49 | 50 | basename = os.path.basename(filename) 51 | imgname, suffix = os.path.splitext(basename) 52 | imgname = imgname.split("-")[0].split("_")[0] 53 | label = list() 54 | for c in imgname: 55 | # one_hot_base = np.zeros(len(CHARS)) 56 | # one_hot_base[CHARS_DICT[c]] = 1 57 | label.append(CHARS_DICT[c]) 58 | 59 | if len(label) == 8: 60 | if self.check(label) == False: 61 | print(imgname) 62 | assert 0, "Error label ^~^!!!" 63 | 64 | return Image, label, len(label) 65 | 66 | def transform(self, img): 67 | img = img.astype('float32') 68 | img -= 127.5 69 | img *= 0.0078125 70 | img = np.transpose(img, (2, 0, 1)) 71 | 72 | return img 73 | 74 | def check(self, label): 75 | if label[2] != CHARS_DICT['D'] and label[2] != CHARS_DICT['F'] \ 76 | and label[-1] != CHARS_DICT['D'] and label[-1] != CHARS_DICT['F']: 77 | print("Error label, Please check!") 78 | return False 79 | else: 80 | return True 81 | -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/test/京PL3N67.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/test/京PL3N67.jpg -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/test/川JK0707.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/test/川JK0707.jpg -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/test/川X90621.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/test/川X90621.jpg -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/test/沪AMS087.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/test/沪AMS087.jpg -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/test/沪C21F13.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/test/沪C21F13.jpg -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/test/沪C8GK31.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/test/沪C8GK31.jpg -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/test/皖A00E66.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/test/皖A00E66.jpg -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/test/皖A0C333.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/test/皖A0C333.jpg -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/test/皖A0C911.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/test/皖A0C911.jpg -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/test/苏A0X3B2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/test/苏A0X3B2.jpg -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/test/苏A53D97.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/test/苏A53D97.jpg -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/test/苏A57NT9.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/test/苏A57NT9.jpg -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/test/苏A8DC31.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/test/苏A8DC31.jpg -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/test/苏AP48A8.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/test/苏AP48A8.jpg -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/test/苏B810FT.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/test/苏B810FT.jpg -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/test/苏BH828L.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/test/苏BH828L.jpg -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/test/苏E5YR23.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/test/苏E5YR23.jpg -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/test/苏E7R5Y0.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/test/苏E7R5Y0.jpg -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/test/苏E9CD08.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/test/苏E9CD08.jpg -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/test/苏EW0806.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/test/苏EW0806.jpg -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/test/苏EYV501.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/test/苏EYV501.jpg -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/test/苏G2F335.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/test/苏G2F335.jpg -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/test/苏HXN335.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/test/苏HXN335.jpg -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/test/闽D33U29.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/test/闽D33U29.jpg -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/test/鲁AW9V20.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/test/鲁AW9V20.jpg -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/test/鲁BE31L9.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/test/鲁BE31L9.jpg -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/test/鲁Q08F99.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/test/鲁Q08F99.jpg -------------------------------------------------------------------------------- /LPRNet_Pytorch/data/test/鲁R8D57Z.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/data/test/鲁R8D57Z.jpg -------------------------------------------------------------------------------- /LPRNet_Pytorch/model/LPRNet.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # @Author: fanstuck 3 | # @Time: 2023/9/25 10:43 4 | # @File: LPRNet.py 5 | import torch.nn as nn 6 | import torch 7 | 8 | class small_basic_block(nn.Module): 9 | def __init__(self, ch_in, ch_out): 10 | super(small_basic_block, self).__init__() 11 | self.block = nn.Sequential( 12 | nn.Conv2d(ch_in, ch_out // 4, kernel_size=1), 13 | nn.ReLU(), 14 | nn.Conv2d(ch_out // 4, ch_out // 4, kernel_size=(3, 1), padding=(1, 0)), 15 | nn.ReLU(), 16 | nn.Conv2d(ch_out // 4, ch_out // 4, kernel_size=(1, 3), padding=(0, 1)), 17 | nn.ReLU(), 18 | nn.Conv2d(ch_out // 4, ch_out, kernel_size=1), 19 | ) 20 | def forward(self, x): 21 | return self.block(x) 22 | 23 | class LPRNet(nn.Module): 24 | def __init__(self, lpr_max_len, phase, class_num, dropout_rate): 25 | super(LPRNet, self).__init__() 26 | self.phase = phase 27 | self.lpr_max_len = lpr_max_len 28 | self.class_num = class_num 29 | self.backbone = nn.Sequential( 30 | nn.Conv2d(in_channels=3, out_channels=64, kernel_size=3, stride=1), # 0 31 | nn.BatchNorm2d(num_features=64), 32 | nn.ReLU(), # 2 33 | nn.MaxPool3d(kernel_size=(1, 3, 3), stride=(1, 1, 1)), 34 | small_basic_block(ch_in=64, ch_out=128), # *** 4 *** 35 | nn.BatchNorm2d(num_features=128), 36 | nn.ReLU(), # 6 37 | nn.MaxPool3d(kernel_size=(1, 3, 3), stride=(2, 1, 2)), 38 | small_basic_block(ch_in=64, ch_out=256), # 8 39 | nn.BatchNorm2d(num_features=256), 40 | nn.ReLU(), # 10 41 | small_basic_block(ch_in=256, ch_out=256), # *** 11 *** 42 | nn.BatchNorm2d(num_features=256), # 12 43 | nn.ReLU(), 44 | nn.MaxPool3d(kernel_size=(1, 3, 3), stride=(4, 1, 2)), # 14 45 | nn.Dropout(dropout_rate), 46 | nn.Conv2d(in_channels=64, out_channels=256, kernel_size=(1, 4), stride=1), # 16 47 | nn.BatchNorm2d(num_features=256), 48 | nn.ReLU(), # 18 49 | nn.Dropout(dropout_rate), 50 | nn.Conv2d(in_channels=256, out_channels=class_num, kernel_size=(13, 1), stride=1), # 20 51 | nn.BatchNorm2d(num_features=class_num), 52 | nn.ReLU(), # *** 22 *** 53 | ) 54 | self.container = nn.Sequential( 55 | nn.Conv2d(in_channels=448+self.class_num, out_channels=self.class_num, kernel_size=(1, 1), stride=(1, 1)), 56 | # nn.BatchNorm2d(num_features=self.class_num), 57 | # nn.ReLU(), 58 | # nn.Conv2d(in_channels=self.class_num, out_channels=self.lpr_max_len+1, kernel_size=3, stride=2), 59 | # nn.ReLU(), 60 | ) 61 | 62 | def forward(self, x): 63 | keep_features = list() 64 | for i, layer in enumerate(self.backbone.children()): 65 | x = layer(x) 66 | if i in [2, 6, 13, 22]: # [2, 4, 8, 11, 22] 67 | keep_features.append(x) 68 | 69 | global_context = list() 70 | for i, f in enumerate(keep_features): 71 | if i in [0, 1]: 72 | f = nn.AvgPool2d(kernel_size=5, stride=5)(f) 73 | if i in [2]: 74 | f = nn.AvgPool2d(kernel_size=(4, 10), stride=(4, 2))(f) 75 | f_pow = torch.pow(f, 2) 76 | f_mean = torch.mean(f_pow) 77 | f = torch.div(f, f_mean) 78 | global_context.append(f) 79 | 80 | x = torch.cat(global_context, 1) 81 | x = self.container(x) 82 | logits = torch.mean(x, dim=2) 83 | 84 | return logits 85 | 86 | def build_lprnet(lpr_max_len=8, phase=False, class_num=66, dropout_rate=0.5): 87 | 88 | Net = LPRNet(lpr_max_len, phase, class_num, dropout_rate) 89 | 90 | if phase == "train": 91 | return Net.train() 92 | else: 93 | return Net.eval() 94 | -------------------------------------------------------------------------------- /LPRNet_Pytorch/model/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # @Author: fanstuck 3 | # @Time: 2023/9/25 10:43 4 | # @File: __init__.py 5 | from .LPRNet import * -------------------------------------------------------------------------------- /LPRNet_Pytorch/model/__pycache__/LPRNet.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/model/__pycache__/LPRNet.cpython-37.pyc -------------------------------------------------------------------------------- /LPRNet_Pytorch/model/__pycache__/__init__.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/model/__pycache__/__init__.cpython-37.pyc -------------------------------------------------------------------------------- /LPRNet_Pytorch/predict_data.csv: -------------------------------------------------------------------------------- 1 | ,target_license,predict_license 2 | 0,苏AP48A8,GAP48A8 3 | 1,苏EW0806,7EW0806 4 | 2,皖A0C333,皖A0C333 5 | 3,苏E7R5Y0,苏E7R5Y0 6 | 4,苏E5YR23,苏E5YR23 7 | 5,京PL3N67,皖PL3N67 8 | 6,鲁BE31L9,皖BE31L9 9 | 7,鲁R8D57Z,皖R8D57Z 10 | 8,苏G2F335,浙G2F335 11 | 9,沪AMS087,沪AMS087 12 | 10,川JK0707,川JK0707 13 | 11,皖A0C911,皖A0C911 14 | 12,苏EYV501,苏EYV501 15 | 13,苏A53D97,苏A53D97 16 | 14,苏A8DC31,苏A8DC31 17 | 15,沪C21F13,沪C21F13 18 | 16,苏A0X3B2,苏A0X3B2 19 | 17,川X90621,川WX90621 20 | 18,鲁AW9V20,皖AW9V20 21 | 19,苏HXN335,皖HXN335 22 | -------------------------------------------------------------------------------- /LPRNet_Pytorch/test.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # @Author: fanstuck 3 | # @Time: 2023/9/25 10:46 4 | # @File: test.py 5 | # -*- coding: utf-8 -*- 6 | # /usr/bin/env/python3 7 | 8 | ''' 9 | test pretrained model. 10 | Author: aiboy.wei@outlook.com . 11 | ''' 12 | 13 | from data.load_data import CHARS, CHARS_DICT, LPRDataLoader 14 | from PIL import Image, ImageDraw, ImageFont 15 | from model.LPRNet import build_lprnet 16 | # import torch.backends.cudnn as cudnn 17 | from torch.autograd import Variable 18 | import torch.nn.functional as F 19 | from torch.utils.data import * 20 | from torch import optim 21 | import torch.nn as nn 22 | import numpy as np 23 | import argparse 24 | import torch 25 | import pandas as pd 26 | import time 27 | import cv2 28 | import os 29 | 30 | def get_parser(): 31 | parser = argparse.ArgumentParser(description='parameters to train net') 32 | parser.add_argument('--img_size', default=[94, 24], help='the image size') 33 | parser.add_argument('--test_img_dirs', default="./data/test", help='the test images path') 34 | parser.add_argument('--dropout_rate', default=0, help='dropout rate.') 35 | parser.add_argument('--lpr_max_len', default=8, help='license plate number max length.') 36 | parser.add_argument('--test_batch_size', default=10, help='testing batch size.') 37 | parser.add_argument('--phase_train', default=False, type=bool, help='train or test phase flag.') 38 | parser.add_argument('--num_workers', default=4, type=int, help='Number of workers used in dataloading') 39 | parser.add_argument('--cuda', default=True, type=bool, help='Use cuda to train model') 40 | parser.add_argument('--show', default=True, type=bool, help='show test image and its predict result or not.') 41 | parser.add_argument('--pretrained_model', default='./weights/Final_LPRNet_model.pth', help='pretrained base model') 42 | 43 | args = parser.parse_args() 44 | 45 | return args 46 | 47 | def collate_fn(batch): 48 | imgs = [] 49 | labels = [] 50 | lengths = [] 51 | for _, sample in enumerate(batch): 52 | img, label, length = sample 53 | imgs.append(torch.from_numpy(img)) 54 | labels.extend(label) 55 | lengths.append(length) 56 | labels = np.asarray(labels).flatten().astype(np.float32) 57 | 58 | return (torch.stack(imgs, 0), torch.from_numpy(labels), lengths) 59 | 60 | def test(): 61 | args = get_parser() 62 | 63 | lprnet = build_lprnet(lpr_max_len=args.lpr_max_len, phase=args.phase_train, class_num=len(CHARS), dropout_rate=args.dropout_rate) 64 | device = torch.device("cuda:0" if args.cuda else "cpu") 65 | lprnet.to(device) 66 | print("Successful to build network!") 67 | 68 | # load pretrained model 69 | if args.pretrained_model: 70 | lprnet.load_state_dict(torch.load(args.pretrained_model)) 71 | print("load pretrained model successful!") 72 | else: 73 | print("[Error] Can't found pretrained mode, please check!") 74 | return False 75 | 76 | test_img_dirs = os.path.expanduser(args.test_img_dirs) 77 | test_dataset = LPRDataLoader(test_img_dirs.split(','), args.img_size, args.lpr_max_len) 78 | try: 79 | Greedy_Decode_Eval(lprnet, test_dataset, args) 80 | finally: 81 | cv2.destroyAllWindows() 82 | 83 | def Greedy_Decode_Eval(Net, datasets, args): 84 | Net = Net.eval() 85 | epoch_size = len(datasets) // args.test_batch_size 86 | batch_iterator = iter(DataLoader(datasets, args.test_batch_size, shuffle=True, num_workers=args.num_workers, collate_fn=collate_fn)) 87 | 88 | Tp = 0 89 | Tn_1 = 0 90 | Tn_2 = 0 91 | t1 = time.time() 92 | for i in range(epoch_size): 93 | # load train data 94 | images, labels, lengths = next(batch_iterator) 95 | start = 0 96 | targets = [] 97 | for length in lengths: 98 | label = labels[start:start+length] 99 | targets.append(label) 100 | start += length 101 | targets = np.array([el.numpy() for el in targets]) 102 | imgs = images.numpy().copy() 103 | 104 | if args.cuda: 105 | images = Variable(images.cuda()) 106 | else: 107 | images = Variable(images) 108 | 109 | # forward 110 | prebs = Net(images) 111 | # greedy decode 112 | prebs = prebs.cpu().detach().numpy() 113 | preb_labels = list() 114 | for i in range(prebs.shape[0]): 115 | preb = prebs[i, :, :] 116 | preb_label = list() 117 | for j in range(preb.shape[1]): 118 | preb_label.append(np.argmax(preb[:, j], axis=0)) 119 | no_repeat_blank_label = list() 120 | pre_c = preb_label[0] 121 | if pre_c != len(CHARS) - 1: 122 | no_repeat_blank_label.append(pre_c) 123 | for c in preb_label: # dropout repeate label and blank label 124 | if (pre_c == c) or (c == len(CHARS) - 1): 125 | if c == len(CHARS) - 1: 126 | pre_c = c 127 | continue 128 | no_repeat_blank_label.append(c) 129 | pre_c = c 130 | preb_labels.append(no_repeat_blank_label) 131 | for i, label in enumerate(preb_labels): 132 | # show image and its predict label 133 | if args.show: 134 | show(imgs[i], label, targets[i]) 135 | if len(label) != len(targets[i]): 136 | Tn_1 += 1 137 | continue 138 | if (np.asarray(targets[i]) == np.asarray(label)).all(): 139 | Tp += 1 140 | else: 141 | Tn_2 += 1 142 | Acc = Tp * 1.0 / (Tp + Tn_1 + Tn_2) 143 | print("[Info] Test Accuracy: {} [{}:{}:{}:{}]".format(Acc, Tp, Tn_1, Tn_2, (Tp+Tn_1+Tn_2))) 144 | t2 = time.time() 145 | print("[Info] Test Speed: {}s 1/{}]".format((t2 - t1) / len(datasets), len(datasets))) 146 | 147 | def show(img, label, target): 148 | img = np.transpose(img, (1, 2, 0)) 149 | img *= 128. 150 | img += 127.5 151 | img = img.astype(np.uint8) 152 | 153 | lb = "" 154 | for i in label: 155 | lb += CHARS[i] 156 | tg = "" 157 | for j in target.tolist(): 158 | tg += CHARS[int(j)] 159 | 160 | flag = "F" 161 | if lb == tg: 162 | flag = "T" 163 | 164 | #img = cv2.putText(img, lb, (0,16), cv2.FONT_HERSHEY_COMPLEX_SMALL, 0.6, (0, 0, 255), 1) 165 | img = cv2ImgAddText(img, lb, (0, 0)) 166 | cv2.imshow("test", img) 167 | print("target: ", tg, " ### {} ### ".format(flag), "predict: ", lb) 168 | traget_file.append(tg) 169 | predict_data.append(lb) 170 | cv2.waitKey() 171 | cv2.destroyAllWindows() 172 | 173 | def cv2ImgAddText(img, text, pos, textColor=(255, 0, 0), textSize=20): 174 | if (isinstance(img, np.ndarray)): # detect opencv format or not 175 | img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) 176 | draw = ImageDraw.Draw(img) 177 | fontText = ImageFont.truetype("data/NotoSansCJK-Regular.ttc", textSize, encoding="utf-8") 178 | draw.text(pos, text, textColor, font=fontText) 179 | 180 | return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR) 181 | 182 | 183 | if __name__ == "__main__": 184 | traget_file=[] 185 | predict_data=[] 186 | test() 187 | dict_convert = {"target_license":traget_file,"predict_license": predict_data} 188 | print(len(traget_file)) 189 | print(len(predict_data)) 190 | df_convert = pd.DataFrame(dict_convert) 191 | df_convert.to_csv('./predict_data.csv',encoding='utf-8') 192 | -------------------------------------------------------------------------------- /LPRNet_Pytorch/train.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # @Author: fanstuck 3 | # @Time: 2023/9/25 10:44 4 | # @File: train.py 5 | # -*- coding: utf-8 -*- 6 | # /usr/bin/env/python3 7 | 8 | 9 | from data.load_data import CHARS, CHARS_DICT, LPRDataLoader 10 | from model.LPRNet import build_lprnet 11 | # import torch.backends.cudnn as cudnn 12 | from torch.autograd import Variable 13 | import torch.nn.functional as F 14 | from torch.utils.data import * 15 | from torch import optim 16 | import torch.nn as nn 17 | import numpy as np 18 | import argparse 19 | import torch 20 | import time 21 | import os 22 | 23 | def sparse_tuple_for_ctc(T_length, lengths): 24 | input_lengths = [] 25 | target_lengths = [] 26 | 27 | for ch in lengths: 28 | input_lengths.append(T_length) 29 | target_lengths.append(ch) 30 | 31 | return tuple(input_lengths), tuple(target_lengths) 32 | 33 | def adjust_learning_rate(optimizer, cur_epoch, base_lr, lr_schedule): 34 | """ 35 | Sets the learning rate 36 | """ 37 | lr = 0 38 | for i, e in enumerate(lr_schedule): 39 | if cur_epoch < e: 40 | lr = base_lr * (0.1 ** i) 41 | break 42 | if lr == 0: 43 | lr = base_lr 44 | for param_group in optimizer.param_groups: 45 | param_group['lr'] = lr 46 | 47 | return lr 48 | 49 | def get_parser(): 50 | parser = argparse.ArgumentParser(description='parameters to train net') 51 | parser.add_argument('--max_epoch', default=20, help='epoch to train the network') 52 | parser.add_argument('--img_size', default=[94, 24], help='the image size') 53 | parser.add_argument('--train_img_dirs', default="data/train", help='the train images path') 54 | parser.add_argument('--test_img_dirs', default="data/test", help='the test images path') 55 | parser.add_argument('--dropout_rate', default=0.5, help='dropout rate.') 56 | parser.add_argument('--learning_rate', default=0.0001, help='base value of learning rate.') 57 | parser.add_argument('--lpr_max_len', default=8, help='license plate number max length.') 58 | parser.add_argument('--train_batch_size', default=128, help='training batch size.') 59 | parser.add_argument('--test_batch_size', default=120, help='testing batch size.') 60 | parser.add_argument('--phase_train', default=True, type=bool, help='train or test phase flag.') 61 | parser.add_argument('--num_workers', default=8, type=int, help='Number of workers used in dataloading') 62 | parser.add_argument('--cuda', default=True, type=bool, help='Use cuda to train model') 63 | parser.add_argument('--resume_epoch', default=0, type=int, help='resume iter for retraining') 64 | parser.add_argument('--save_interval', default=2000, type=int, help='interval for save model state dict') 65 | parser.add_argument('--test_interval', default=2000, type=int, help='interval for evaluate') 66 | parser.add_argument('--momentum', default=0.9, type=float, help='momentum') 67 | parser.add_argument('--weight_decay', default=2e-5, type=float, help='Weight decay for SGD') 68 | parser.add_argument('--lr_schedule', default=[4, 8, 12, 14, 16], help='schedule for learning rate.') 69 | parser.add_argument('--save_folder', default='./weights/', help='Location to save checkpoint models') 70 | parser.add_argument('--pretrained_model', default='./weights/Final_LPRNet_model.pth', help='pretrained base model') 71 | #parser.add_argument('--pretrained_model', default='', help='pretrained base model') 72 | 73 | args = parser.parse_args() 74 | 75 | return args 76 | 77 | def collate_fn(batch): 78 | imgs = [] 79 | labels = [] 80 | lengths = [] 81 | for _, sample in enumerate(batch): 82 | img, label, length = sample 83 | imgs.append(torch.from_numpy(img)) 84 | labels.extend(label) 85 | lengths.append(length) 86 | labels = np.asarray(labels).flatten().astype(np.int) 87 | 88 | return (torch.stack(imgs, 0), torch.from_numpy(labels), lengths) 89 | 90 | def train(): 91 | args = get_parser() 92 | 93 | T_length = 18 # args.lpr_max_len 94 | epoch = 0 + args.resume_epoch 95 | loss_val = 0 96 | 97 | if not os.path.exists(args.save_folder): 98 | os.mkdir(args.save_folder) 99 | 100 | lprnet = build_lprnet(lpr_max_len=args.lpr_max_len, phase=args.phase_train, class_num=len(CHARS), dropout_rate=args.dropout_rate) 101 | device = torch.device("cuda:0" if args.cuda else "cpu") 102 | lprnet.to(device) 103 | print("Successful to build network!") 104 | 105 | # load pretrained model 106 | if args.pretrained_model: 107 | lprnet.load_state_dict(torch.load(args.pretrained_model)) 108 | print("load pretrained model successful!") 109 | else: 110 | def xavier(param): 111 | nn.init.xavier_uniform(param) 112 | 113 | def weights_init(m): 114 | for key in m.state_dict(): 115 | if key.split('.')[-1] == 'weight': 116 | if 'conv' in key: 117 | nn.init.kaiming_normal_(m.state_dict()[key], mode='fan_out') 118 | if 'bn' in key: 119 | m.state_dict()[key][...] = xavier(1) 120 | elif key.split('.')[-1] == 'bias': 121 | m.state_dict()[key][...] = 0.01 122 | 123 | lprnet.backbone.apply(weights_init) 124 | lprnet.container.apply(weights_init) 125 | print("initial net weights successful!") 126 | 127 | # define optimizer 128 | # optimizer = optim.SGD(lprnet.parameters(), lr=args.learning_rate, 129 | # momentum=args.momentum, weight_decay=args.weight_decay) 130 | optimizer = optim.RMSprop(lprnet.parameters(), lr=args.learning_rate, alpha = 0.9, eps=1e-08, 131 | momentum=args.momentum, weight_decay=args.weight_decay) 132 | train_img_dirs = os.path.expanduser(args.train_img_dirs) 133 | test_img_dirs = os.path.expanduser(args.test_img_dirs) 134 | train_dataset = LPRDataLoader(train_img_dirs.split(','), args.img_size, args.lpr_max_len) 135 | test_dataset = LPRDataLoader(test_img_dirs.split(','), args.img_size, args.lpr_max_len) 136 | 137 | epoch_size = len(train_dataset) // args.train_batch_size 138 | max_iter = args.max_epoch * epoch_size 139 | 140 | ctc_loss = nn.CTCLoss(blank=len(CHARS)-1, reduction='mean') # reduction: 'none' | 'mean' | 'sum' 141 | 142 | if args.resume_epoch > 0: 143 | start_iter = args.resume_epoch * epoch_size 144 | else: 145 | start_iter = 0 146 | 147 | for iteration in range(start_iter, max_iter): 148 | if iteration % epoch_size == 0: 149 | # create batch iterator 150 | batch_iterator = iter(DataLoader(train_dataset, args.train_batch_size, shuffle=True, num_workers=args.num_workers, collate_fn=collate_fn)) 151 | loss_val = 0 152 | epoch += 1 153 | 154 | if iteration !=0 and iteration % args.save_interval == 0: 155 | torch.save(lprnet.state_dict(), args.save_folder + 'LPRNet_' + '_iteration_' + repr(iteration) + '.pth') 156 | 157 | if (iteration + 1) % args.test_interval == 0: 158 | Greedy_Decode_Eval(lprnet, test_dataset, args) 159 | # lprnet.train() # should be switch to train mode 160 | 161 | start_time = time.time() 162 | # load train data 163 | images, labels, lengths = next(batch_iterator) 164 | # labels = np.array([el.numpy() for el in labels]).T 165 | # print(labels) 166 | # get ctc parameters 167 | input_lengths, target_lengths = sparse_tuple_for_ctc(T_length, lengths) 168 | # update lr 169 | lr = adjust_learning_rate(optimizer, epoch, args.learning_rate, args.lr_schedule) 170 | 171 | if args.cuda: 172 | images = Variable(images, requires_grad=False).cuda() 173 | labels = Variable(labels, requires_grad=False).cuda() 174 | else: 175 | images = Variable(images, requires_grad=False) 176 | labels = Variable(labels, requires_grad=False) 177 | 178 | # forward 179 | logits = lprnet(images) 180 | log_probs = logits.permute(2, 0, 1) # for ctc loss: T x N x C 181 | # print(labels.shape) 182 | log_probs = log_probs.log_softmax(2).requires_grad_() 183 | # log_probs = log_probs.detach().requires_grad_() 184 | # print(log_probs.shape) 185 | # backprop 186 | optimizer.zero_grad() 187 | loss = ctc_loss(log_probs, labels, input_lengths=input_lengths, target_lengths=target_lengths) 188 | if loss.item() == np.inf: 189 | continue 190 | loss.backward() 191 | optimizer.step() 192 | loss_val += loss.item() 193 | end_time = time.time() 194 | if iteration % 20 == 0: 195 | print('Epoch:' + repr(epoch) + ' || epochiter: ' + repr(iteration % epoch_size) + '/' + repr(epoch_size) 196 | + '|| Totel iter ' + repr(iteration) + ' || Loss: %.4f||' % (loss.item()) + 197 | 'Batch time: %.4f sec. ||' % (end_time - start_time) + 'LR: %.8f' % (lr)) 198 | # final test 199 | print("Final test Accuracy:") 200 | Greedy_Decode_Eval(lprnet, test_dataset, args) 201 | 202 | # save final parameters 203 | torch.save(lprnet.state_dict(), args.save_folder + 'Final_LPRNet_model.pth') 204 | 205 | def Greedy_Decode_Eval(Net, datasets, args): 206 | Net = Net.eval() 207 | epoch_size = len(datasets) // args.test_batch_size 208 | batch_iterator = iter(DataLoader(datasets, args.test_batch_size, shuffle=True, num_workers=args.num_workers, collate_fn=collate_fn)) 209 | 210 | Tp = 0 211 | Tn_1 = 0 212 | Tn_2 = 0 213 | t1 = time.time() 214 | for i in range(epoch_size): 215 | # load train data 216 | images, labels, lengths = next(batch_iterator) 217 | start = 0 218 | targets = [] 219 | for length in lengths: 220 | label = labels[start:start+length] 221 | targets.append(label) 222 | start += length 223 | targets = np.array([el.numpy() for el in targets]) 224 | 225 | if args.cuda: 226 | images = Variable(images.cuda()) 227 | else: 228 | images = Variable(images) 229 | 230 | # forward 231 | prebs = Net(images) 232 | # greedy decode 233 | prebs = prebs.cpu().detach().numpy() 234 | preb_labels = list() 235 | for i in range(prebs.shape[0]): 236 | preb = prebs[i, :, :] 237 | preb_label = list() 238 | for j in range(preb.shape[1]): 239 | preb_label.append(np.argmax(preb[:, j], axis=0)) 240 | no_repeat_blank_label = list() 241 | pre_c = preb_label[0] 242 | if pre_c != len(CHARS) - 1: 243 | no_repeat_blank_label.append(pre_c) 244 | for c in preb_label: # dropout repeate label and blank label 245 | if (pre_c == c) or (c == len(CHARS) - 1): 246 | if c == len(CHARS) - 1: 247 | pre_c = c 248 | continue 249 | no_repeat_blank_label.append(c) 250 | pre_c = c 251 | preb_labels.append(no_repeat_blank_label) 252 | for i, label in enumerate(preb_labels): 253 | if len(label) != len(targets[i]): 254 | Tn_1 += 1 255 | continue 256 | if (np.asarray(targets[i]) == np.asarray(label)).all(): 257 | Tp += 1 258 | else: 259 | Tn_2 += 1 260 | 261 | Acc = Tp * 1.0 / (Tp + Tn_1 + Tn_2) 262 | print("[Info] Test Accuracy: {} [{}:{}:{}:{}]".format(Acc, Tp, Tn_1, Tn_2, (Tp+Tn_1+Tn_2))) 263 | t2 = time.time() 264 | print("[Info] Test Speed: {}s 1/{}]".format((t2 - t1) / len(datasets), len(datasets))) 265 | 266 | 267 | if __name__ == "__main__": 268 | train() 269 | -------------------------------------------------------------------------------- /LPRNet_Pytorch/weights/Final_LPRNet_model.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/LPRNet_Pytorch/weights/Final_LPRNet_model.pth -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Yolov7-LPRNet 2 | 基于Yolov7-LPRNet的动态车牌目标识别算法模型 3 | 博客地址:https://blog.csdn.net/master_hunter/article/details/133631461 4 | ## 数据集 5 | CCPD:https://github.com/detectRecog/CCPD 6 | 7 | CCPD是一个大型的、多样化的、经过仔细标注的中国城市车牌开源数据集。CCPD数据集主要分为CCPD2019数据集和CCPD2020(CCPD-Green)数据集。CCPD2019数据集车牌类型仅有普通车牌(蓝色车牌),CCPD2020数据集车牌类型仅有新能源车牌(绿色车牌)。 8 | 9 | **在CCPD数据集中,每张图片仅包含一张车牌,车牌的车牌省份主要为皖。CCPD中的每幅图像都包含大量的标注信息,但是CCPD数据集没有专门的标注文件,每张图像的文件名就是该图像对应的数据标注**。 10 | 11 | 标注最困难的部分是注释四个顶点的位置。为了完成这项任务,数据发布者首先在10k图像上手动标记四个顶点的位置。然后设计了一个基于深度学习的检测模型,在对该网络进行良好训练后,对每幅图像的四个顶点位置进行自动标注。 12 | ## 前言 13 | 14 | 。我见过很多初学目标识别的同学基本上只花一周时间就可以参照案例实现一个目标检测的项目,这全靠YOLO强大的解耦性和部署简易性。初学者甚至只需要修改部分超参数接口,调整数据集就可以实现目标检测了。但是我想表达的并不是YOLO的原理有多么难理解,原理有多难推理。一般工作中要求我们能够运行并且能够完成目标检测出来就可以了,更重要的是数据集的标注。我们不需要完成几乎难以单人完成的造目标检测算法轮子的过程,我们需要理解YOLO算法中每个超参数的作用以及影响。就算我们能够训练出一定准确度的目标检测模型,我们还需要根据实际情况对生成结果进行一定的改写:例如对于图片来说一共出现了几种目标;对于一个视频来说,定位到具体时间出现了识别的目标。这都是需要我们反复学习再练习的本领。 15 | 16 | 完成目标检测后,我们应该输出定位出来的信息,YOLO是提供输出设定的超参数的,我们需要根据输出的信息对目标进行裁剪得到我们想要的目标之后再做上层处理。如果是车牌目标识别的项目,我们裁剪出来的车牌就可以进行OCR技术识别出车牌字符了,如果是安全帽识别项目,那么我们可以统计一张图片或者一帧中出现检测目标的个数做出判断,一切都需要根据实际业务需求为主。本篇文章主要是OCR模型对车牌进行字符识别,结合YOLO算法直接定位目标进行裁剪,裁剪后生成OCR训练数据集即可。 17 | ## 训练步骤 18 | ### 1.安装环境 19 | 利用Yolo训练模型十分简单并没有涉及到很复杂的步骤,如果是新手的话注意下载的torch版本是否符合本身NVDIA GPU的版本,需要根据NVIDIA支持最高的cuda版本去下载兼容的Torch版本,查看cuda版本可以通过终端输入:nvidia-smi 20 | 21 | ![f6b17a7a98f748ebaf58ee703f7489ef](https://github.com/Fanstuck/Yolov7-LPRNet/assets/62112487/04881d58-fc8e-4b82-97ae-a3348e0c8e6b) 22 | ### 2.修改Yolo配置文件 23 | 首先增加cfg/training/yolov7-e6e-ccpd.yaml文件,此配置文件可以参数动态调整网络规模,这里也不展开细讲,以后会有Yolov7源码详解系列,敬请期待,我们需要根据我们用到的官方yolo模型选择对于的yaml文件配置,我这里用的的yolov7-e6e模型训练,所以直接拿yolov7-e6e.yaml改写: 24 | ```` 25 | # parameters 26 | nc: 1 # number of classes 27 | depth_multiple: 1.0 # model depth multiple 28 | width_multiple: 1.0 # layer channel multiple 29 | ```` 30 | 其中nc是检测个数,depth_multiple是模型深度,width_multiple表示卷积通道的缩放因子,就是将配置里面的backbone和head部分有关Conv通道的设置,全部乘以该系数。通过这两个参数就可以实现不同复杂度的模型设计。然后是添加数据索引文件data/license.yaml: 31 | ```` 32 | train: ./split_dataset/images/train 33 | val: ./split_dataset/images/val 34 | test: ./split_dataset/images/test 35 | 36 | # number of classes 37 | nc : 1 38 | 39 | #class names 40 | names : ['license'] 41 | ```` 42 | ### 训练模型 43 | 前面train,val,test都对应着目录存放的训练数据集。之后修改train.py中的参数或者是直接在终端输入对应的参数自动目录,我一般是习惯直接在defalut下面修改,对应参数修改,一般来说修改这些就足够了: 44 | 45 | ```` 46 | parser.add_argument('--weights', type=str, default='weights/yolo7-e6e.pt', help='initial weights path') 47 | parser.add_argument('--cfg', type=str, default='cfg/yolov7-e6e-ccpd', help='model.yaml path') 48 | parser.add_argument('--data', type=str, default='data/license.yaml', help='data.yaml path') 49 | ```` 50 | 当然也可能出现内存溢出等问题,需要修改: 51 | ```` 52 | arser.add_argument('--batch-size', type=int, default=16, help='total batch size for all GPUs') 53 | parser.add_argument('--workers', type=int, default=8, help='maximum number of dataloader workers') 54 | ```` 55 | 这两个参数,具体参数根据自己硬件条件修改。 56 | ### 推理 57 | 这里需要将刚刚训练好的最好的权重传入到推理函数中去。然后就可以对图像视频进行推理了。 58 | 59 | 主要需要修改的参数是: 60 | ```` 61 | parser.add_argument('--weights', nargs='+', type=str, default='runs/train/exp/weights/best.pt', help='model.pt path(s)') 62 | parser.add_argument('--source', type=str, default='测试数据集目录或者图片', help='source') 63 | ```` 64 | 有问题的私信博主或者直接评论就可以了博主会长期维护此开源项目,目前此项目运行需要多部操作比较繁琐,我将不断更新版本优化,下一版本将加入UI以及一键部署环境和添加sh指令一键运行项目代码。下篇文章将详细解读LPRNet模型如何进行OCR识别, 再次希望对大家有帮助不吝点亮star~: 65 | 66 | 67 | -------------------------------------------------------------------------------- /Yolov7/VOCCCPDlicense/images/try/0275-93_75-201&483_486&587-491&584_211&566_183&474_463&492-0_0_27_14_28_29_29-93-58.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/Yolov7/VOCCCPDlicense/images/try/0275-93_75-201&483_486&587-491&584_211&566_183&474_463&492-0_0_27_14_28_29_29-93-58.jpg -------------------------------------------------------------------------------- /Yolov7/VOCCCPDlicense/images/try/0275-93_82-352&510_649&606-629&619_349&588_339&500_619&531-0_0_28_28_21_33_29-84-25.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/Yolov7/VOCCCPDlicense/images/try/0275-93_82-352&510_649&606-629&619_349&588_339&500_619&531-0_0_28_28_21_33_29-84-25.jpg -------------------------------------------------------------------------------- /Yolov7/VOCCCPDlicense/images/try/03-91_90-283&402_600&524-589&515_285&521_296&411_600&405-0_0_22_27_1_24_32-154-73.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/Yolov7/VOCCCPDlicense/images/try/03-91_90-283&402_600&524-589&515_285&521_296&411_600&405-0_0_22_27_1_24_32-154-73.jpg -------------------------------------------------------------------------------- /Yolov7/VOCCCPDlicense/images/try/03-92_86-111&425_419&538-427&544_98&523_105&413_434&434-0_0_23_32_32_32_33-137-60.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/Yolov7/VOCCCPDlicense/images/try/03-92_86-111&425_419&538-427&544_98&523_105&413_434&434-0_0_23_32_32_32_33-137-60.jpg -------------------------------------------------------------------------------- /Yolov7/cfg/training/yolov7-e6e-ccpd.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 1 # number of classes 3 | depth_multiple: 1.0 # model depth multiple 4 | width_multiple: 1.0 # layer channel multiple 5 | 6 | # anchors 7 | anchors: 8 | - [ 19,27, 44,40, 38,94 ] # P3/8 9 | - [ 96,68, 86,152, 180,137 ] # P4/16 10 | - [ 140,301, 303,264, 238,542 ] # P5/32 11 | - [ 436,615, 739,380, 925,792 ] # P6/64 12 | 13 | # yolov7 backbone 14 | backbone: 15 | # [from, number, module, args], 16 | [[-1, 1, ReOrg, []], # 0 17 | [-1, 1, Conv, [80, 3, 1]], # 1-P1/2 18 | 19 | [-1, 1, DownC, [160]], # 2-P2/4 20 | [-1, 1, Conv, [64, 1, 1]], 21 | [-2, 1, Conv, [64, 1, 1]], 22 | [-1, 1, Conv, [64, 3, 1]], 23 | [-1, 1, Conv, [64, 3, 1]], 24 | [-1, 1, Conv, [64, 3, 1]], 25 | [-1, 1, Conv, [64, 3, 1]], 26 | [-1, 1, Conv, [64, 3, 1]], 27 | [-1, 1, Conv, [64, 3, 1]], 28 | [[-1, -3, -5, -7, -8], 1, Concat, [1]], 29 | [-1, 1, Conv, [160, 1, 1]], # 12 30 | [-11, 1, Conv, [64, 1, 1]], 31 | [-12, 1, Conv, [64, 1, 1]], 32 | [-1, 1, Conv, [64, 3, 1]], 33 | [-1, 1, Conv, [64, 3, 1]], 34 | [-1, 1, Conv, [64, 3, 1]], 35 | [-1, 1, Conv, [64, 3, 1]], 36 | [-1, 1, Conv, [64, 3, 1]], 37 | [-1, 1, Conv, [64, 3, 1]], 38 | [[-1, -3, -5, -7, -8], 1, Concat, [1]], 39 | [-1, 1, Conv, [160, 1, 1]], # 22 40 | [[-1, -11], 1, Shortcut, [1]], # 23 41 | 42 | [-1, 1, DownC, [320]], # 24-P3/8 43 | [-1, 1, Conv, [128, 1, 1]], 44 | [-2, 1, Conv, [128, 1, 1]], 45 | [-1, 1, Conv, [128, 3, 1]], 46 | [-1, 1, Conv, [128, 3, 1]], 47 | [-1, 1, Conv, [128, 3, 1]], 48 | [-1, 1, Conv, [128, 3, 1]], 49 | [-1, 1, Conv, [128, 3, 1]], 50 | [-1, 1, Conv, [128, 3, 1]], 51 | [[-1, -3, -5, -7, -8], 1, Concat, [1]], 52 | [-1, 1, Conv, [320, 1, 1]], # 34 53 | [-11, 1, Conv, [128, 1, 1]], 54 | [-12, 1, Conv, [128, 1, 1]], 55 | [-1, 1, Conv, [128, 3, 1]], 56 | [-1, 1, Conv, [128, 3, 1]], 57 | [-1, 1, Conv, [128, 3, 1]], 58 | [-1, 1, Conv, [128, 3, 1]], 59 | [-1, 1, Conv, [128, 3, 1]], 60 | [-1, 1, Conv, [128, 3, 1]], 61 | [[-1, -3, -5, -7, -8], 1, Concat, [1]], 62 | [-1, 1, Conv, [320, 1, 1]], # 44 63 | [[-1, -11], 1, Shortcut, [1]], # 45 64 | 65 | [-1, 1, DownC, [640]], # 46-P4/16 66 | [-1, 1, Conv, [256, 1, 1]], 67 | [-2, 1, Conv, [256, 1, 1]], 68 | [-1, 1, Conv, [256, 3, 1]], 69 | [-1, 1, Conv, [256, 3, 1]], 70 | [-1, 1, Conv, [256, 3, 1]], 71 | [-1, 1, Conv, [256, 3, 1]], 72 | [-1, 1, Conv, [256, 3, 1]], 73 | [-1, 1, Conv, [256, 3, 1]], 74 | [[-1, -3, -5, -7, -8], 1, Concat, [1]], 75 | [-1, 1, Conv, [640, 1, 1]], # 56 76 | [-11, 1, Conv, [256, 1, 1]], 77 | [-12, 1, Conv, [256, 1, 1]], 78 | [-1, 1, Conv, [256, 3, 1]], 79 | [-1, 1, Conv, [256, 3, 1]], 80 | [-1, 1, Conv, [256, 3, 1]], 81 | [-1, 1, Conv, [256, 3, 1]], 82 | [-1, 1, Conv, [256, 3, 1]], 83 | [-1, 1, Conv, [256, 3, 1]], 84 | [[-1, -3, -5, -7, -8], 1, Concat, [1]], 85 | [-1, 1, Conv, [640, 1, 1]], # 66 86 | [[-1, -11], 1, Shortcut, [1]], # 67 87 | 88 | [-1, 1, DownC, [960]], # 68-P5/32 89 | [-1, 1, Conv, [384, 1, 1]], 90 | [-2, 1, Conv, [384, 1, 1]], 91 | [-1, 1, Conv, [384, 3, 1]], 92 | [-1, 1, Conv, [384, 3, 1]], 93 | [-1, 1, Conv, [384, 3, 1]], 94 | [-1, 1, Conv, [384, 3, 1]], 95 | [-1, 1, Conv, [384, 3, 1]], 96 | [-1, 1, Conv, [384, 3, 1]], 97 | [[-1, -3, -5, -7, -8], 1, Concat, [1]], 98 | [-1, 1, Conv, [960, 1, 1]], # 78 99 | [-11, 1, Conv, [384, 1, 1]], 100 | [-12, 1, Conv, [384, 1, 1]], 101 | [-1, 1, Conv, [384, 3, 1]], 102 | [-1, 1, Conv, [384, 3, 1]], 103 | [-1, 1, Conv, [384, 3, 1]], 104 | [-1, 1, Conv, [384, 3, 1]], 105 | [-1, 1, Conv, [384, 3, 1]], 106 | [-1, 1, Conv, [384, 3, 1]], 107 | [[-1, -3, -5, -7, -8], 1, Concat, [1]], 108 | [-1, 1, Conv, [960, 1, 1]], # 88 109 | [[-1, -11], 1, Shortcut, [1]], # 89 110 | 111 | [-1, 1, DownC, [1280]], # 90-P6/64 112 | [-1, 1, Conv, [512, 1, 1]], 113 | [-2, 1, Conv, [512, 1, 1]], 114 | [-1, 1, Conv, [512, 3, 1]], 115 | [-1, 1, Conv, [512, 3, 1]], 116 | [-1, 1, Conv, [512, 3, 1]], 117 | [-1, 1, Conv, [512, 3, 1]], 118 | [-1, 1, Conv, [512, 3, 1]], 119 | [-1, 1, Conv, [512, 3, 1]], 120 | [[-1, -3, -5, -7, -8], 1, Concat, [1]], 121 | [-1, 1, Conv, [1280, 1, 1]], # 100 122 | [-11, 1, Conv, [512, 1, 1]], 123 | [-12, 1, Conv, [512, 1, 1]], 124 | [-1, 1, Conv, [512, 3, 1]], 125 | [-1, 1, Conv, [512, 3, 1]], 126 | [-1, 1, Conv, [512, 3, 1]], 127 | [-1, 1, Conv, [512, 3, 1]], 128 | [-1, 1, Conv, [512, 3, 1]], 129 | [-1, 1, Conv, [512, 3, 1]], 130 | [[-1, -3, -5, -7, -8], 1, Concat, [1]], 131 | [-1, 1, Conv, [1280, 1, 1]], # 110 132 | [[-1, -11], 1, Shortcut, [1]], # 111 133 | ] 134 | 135 | # yolov7 head 136 | head: 137 | [[-1, 1, SPPCSPC, [640]], # 112 138 | 139 | [-1, 1, Conv, [480, 1, 1]], 140 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 141 | [89, 1, Conv, [480, 1, 1]], # route backbone P5 142 | [[-1, -2], 1, Concat, [1]], 143 | 144 | [-1, 1, Conv, [384, 1, 1]], 145 | [-2, 1, Conv, [384, 1, 1]], 146 | [-1, 1, Conv, [192, 3, 1]], 147 | [-1, 1, Conv, [192, 3, 1]], 148 | [-1, 1, Conv, [192, 3, 1]], 149 | [-1, 1, Conv, [192, 3, 1]], 150 | [-1, 1, Conv, [192, 3, 1]], 151 | [-1, 1, Conv, [192, 3, 1]], 152 | [[-1, -2, -3, -4, -5, -6, -7, -8], 1, Concat, [1]], 153 | [-1, 1, Conv, [480, 1, 1]], # 126 154 | [-11, 1, Conv, [384, 1, 1]], 155 | [-12, 1, Conv, [384, 1, 1]], 156 | [-1, 1, Conv, [192, 3, 1]], 157 | [-1, 1, Conv, [192, 3, 1]], 158 | [-1, 1, Conv, [192, 3, 1]], 159 | [-1, 1, Conv, [192, 3, 1]], 160 | [-1, 1, Conv, [192, 3, 1]], 161 | [-1, 1, Conv, [192, 3, 1]], 162 | [[-1, -2, -3, -4, -5, -6, -7, -8], 1, Concat, [1]], 163 | [-1, 1, Conv, [480, 1, 1]], # 136 164 | [[-1, -11], 1, Shortcut, [1]], # 137 165 | 166 | [-1, 1, Conv, [320, 1, 1]], 167 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 168 | [67, 1, Conv, [320, 1, 1]], # route backbone P4 169 | [[-1, -2], 1, Concat, [1]], 170 | 171 | [-1, 1, Conv, [256, 1, 1]], 172 | [-2, 1, Conv, [256, 1, 1]], 173 | [-1, 1, Conv, [128, 3, 1]], 174 | [-1, 1, Conv, [128, 3, 1]], 175 | [-1, 1, Conv, [128, 3, 1]], 176 | [-1, 1, Conv, [128, 3, 1]], 177 | [-1, 1, Conv, [128, 3, 1]], 178 | [-1, 1, Conv, [128, 3, 1]], 179 | [[-1, -2, -3, -4, -5, -6, -7, -8], 1, Concat, [1]], 180 | [-1, 1, Conv, [320, 1, 1]], # 151 181 | [-11, 1, Conv, [256, 1, 1]], 182 | [-12, 1, Conv, [256, 1, 1]], 183 | [-1, 1, Conv, [128, 3, 1]], 184 | [-1, 1, Conv, [128, 3, 1]], 185 | [-1, 1, Conv, [128, 3, 1]], 186 | [-1, 1, Conv, [128, 3, 1]], 187 | [-1, 1, Conv, [128, 3, 1]], 188 | [-1, 1, Conv, [128, 3, 1]], 189 | [[-1, -2, -3, -4, -5, -6, -7, -8], 1, Concat, [1]], 190 | [-1, 1, Conv, [320, 1, 1]], # 161 191 | [[-1, -11], 1, Shortcut, [1]], # 162 192 | 193 | [-1, 1, Conv, [160, 1, 1]], 194 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 195 | [45, 1, Conv, [160, 1, 1]], # route backbone P3 196 | [[-1, -2], 1, Concat, [1]], 197 | 198 | [-1, 1, Conv, [128, 1, 1]], 199 | [-2, 1, Conv, [128, 1, 1]], 200 | [-1, 1, Conv, [64, 3, 1]], 201 | [-1, 1, Conv, [64, 3, 1]], 202 | [-1, 1, Conv, [64, 3, 1]], 203 | [-1, 1, Conv, [64, 3, 1]], 204 | [-1, 1, Conv, [64, 3, 1]], 205 | [-1, 1, Conv, [64, 3, 1]], 206 | [[-1, -2, -3, -4, -5, -6, -7, -8], 1, Concat, [1]], 207 | [-1, 1, Conv, [160, 1, 1]], # 176 208 | [-11, 1, Conv, [128, 1, 1]], 209 | [-12, 1, Conv, [128, 1, 1]], 210 | [-1, 1, Conv, [64, 3, 1]], 211 | [-1, 1, Conv, [64, 3, 1]], 212 | [-1, 1, Conv, [64, 3, 1]], 213 | [-1, 1, Conv, [64, 3, 1]], 214 | [-1, 1, Conv, [64, 3, 1]], 215 | [-1, 1, Conv, [64, 3, 1]], 216 | [[-1, -2, -3, -4, -5, -6, -7, -8], 1, Concat, [1]], 217 | [-1, 1, Conv, [160, 1, 1]], # 186 218 | [[-1, -11], 1, Shortcut, [1]], # 187 219 | 220 | [-1, 1, DownC, [320]], 221 | [[-1, 162], 1, Concat, [1]], 222 | 223 | [-1, 1, Conv, [256, 1, 1]], 224 | [-2, 1, Conv, [256, 1, 1]], 225 | [-1, 1, Conv, [128, 3, 1]], 226 | [-1, 1, Conv, [128, 3, 1]], 227 | [-1, 1, Conv, [128, 3, 1]], 228 | [-1, 1, Conv, [128, 3, 1]], 229 | [-1, 1, Conv, [128, 3, 1]], 230 | [-1, 1, Conv, [128, 3, 1]], 231 | [[-1, -2, -3, -4, -5, -6, -7, -8], 1, Concat, [1]], 232 | [-1, 1, Conv, [320, 1, 1]], # 199 233 | [-11, 1, Conv, [256, 1, 1]], 234 | [-12, 1, Conv, [256, 1, 1]], 235 | [-1, 1, Conv, [128, 3, 1]], 236 | [-1, 1, Conv, [128, 3, 1]], 237 | [-1, 1, Conv, [128, 3, 1]], 238 | [-1, 1, Conv, [128, 3, 1]], 239 | [-1, 1, Conv, [128, 3, 1]], 240 | [-1, 1, Conv, [128, 3, 1]], 241 | [[-1, -2, -3, -4, -5, -6, -7, -8], 1, Concat, [1]], 242 | [-1, 1, Conv, [320, 1, 1]], # 209 243 | [[-1, -11], 1, Shortcut, [1]], # 210 244 | 245 | [-1, 1, DownC, [480]], 246 | [[-1, 137], 1, Concat, [1]], 247 | 248 | [-1, 1, Conv, [384, 1, 1]], 249 | [-2, 1, Conv, [384, 1, 1]], 250 | [-1, 1, Conv, [192, 3, 1]], 251 | [-1, 1, Conv, [192, 3, 1]], 252 | [-1, 1, Conv, [192, 3, 1]], 253 | [-1, 1, Conv, [192, 3, 1]], 254 | [-1, 1, Conv, [192, 3, 1]], 255 | [-1, 1, Conv, [192, 3, 1]], 256 | [[-1, -2, -3, -4, -5, -6, -7, -8], 1, Concat, [1]], 257 | [-1, 1, Conv, [480, 1, 1]], # 222 258 | [-11, 1, Conv, [384, 1, 1]], 259 | [-12, 1, Conv, [384, 1, 1]], 260 | [-1, 1, Conv, [192, 3, 1]], 261 | [-1, 1, Conv, [192, 3, 1]], 262 | [-1, 1, Conv, [192, 3, 1]], 263 | [-1, 1, Conv, [192, 3, 1]], 264 | [-1, 1, Conv, [192, 3, 1]], 265 | [-1, 1, Conv, [192, 3, 1]], 266 | [[-1, -2, -3, -4, -5, -6, -7, -8], 1, Concat, [1]], 267 | [-1, 1, Conv, [480, 1, 1]], # 232 268 | [[-1, -11], 1, Shortcut, [1]], # 233 269 | 270 | [-1, 1, DownC, [640]], 271 | [[-1, 112], 1, Concat, [1]], 272 | 273 | [-1, 1, Conv, [512, 1, 1]], 274 | [-2, 1, Conv, [512, 1, 1]], 275 | [-1, 1, Conv, [256, 3, 1]], 276 | [-1, 1, Conv, [256, 3, 1]], 277 | [-1, 1, Conv, [256, 3, 1]], 278 | [-1, 1, Conv, [256, 3, 1]], 279 | [-1, 1, Conv, [256, 3, 1]], 280 | [-1, 1, Conv, [256, 3, 1]], 281 | [[-1, -2, -3, -4, -5, -6, -7, -8], 1, Concat, [1]], 282 | [-1, 1, Conv, [640, 1, 1]], # 245 283 | [-11, 1, Conv, [512, 1, 1]], 284 | [-12, 1, Conv, [512, 1, 1]], 285 | [-1, 1, Conv, [256, 3, 1]], 286 | [-1, 1, Conv, [256, 3, 1]], 287 | [-1, 1, Conv, [256, 3, 1]], 288 | [-1, 1, Conv, [256, 3, 1]], 289 | [-1, 1, Conv, [256, 3, 1]], 290 | [-1, 1, Conv, [256, 3, 1]], 291 | [[-1, -2, -3, -4, -5, -6, -7, -8], 1, Concat, [1]], 292 | [-1, 1, Conv, [640, 1, 1]], # 255 293 | [[-1, -11], 1, Shortcut, [1]], # 256 294 | 295 | [187, 1, Conv, [320, 3, 1]], 296 | [210, 1, Conv, [640, 3, 1]], 297 | [233, 1, Conv, [960, 3, 1]], 298 | [256, 1, Conv, [1280, 3, 1]], 299 | 300 | [186, 1, Conv, [320, 3, 1]], 301 | [161, 1, Conv, [640, 3, 1]], 302 | [136, 1, Conv, [960, 3, 1]], 303 | [112, 1, Conv, [1280, 3, 1]], 304 | 305 | [[257,258,259,260,261,262,263,264], 1, IAuxDetect, [nc, anchors]], # Detect(P3, P4, P5, P6) 306 | ] 307 | -------------------------------------------------------------------------------- /Yolov7/data/hyp.scratch.custom.yaml: -------------------------------------------------------------------------------- 1 | lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3) 2 | lrf: 0.1 # final OneCycleLR learning rate (lr0 * lrf) 3 | momentum: 0.937 # SGD momentum/Adam beta1 4 | weight_decay: 0.0005 # optimizer weight decay 5e-4 5 | warmup_epochs: 3.0 # warmup epochs (fractions ok) 6 | warmup_momentum: 0.8 # warmup initial momentum 7 | warmup_bias_lr: 0.1 # warmup initial bias lr 8 | box: 0.05 # box loss gain 9 | cls: 0.3 # cls loss gain 10 | cls_pw: 1.0 # cls BCELoss positive_weight 11 | obj: 0.7 # obj loss gain (scale with pixels) 12 | obj_pw: 1.0 # obj BCELoss positive_weight 13 | iou_t: 0.20 # IoU training threshold 14 | anchor_t: 4.0 # anchor-multiple threshold 15 | # anchors: 3 # anchors per output layer (0 to ignore) 16 | fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5) 17 | hsv_h: 0.015 # image HSV-Hue augmentation (fraction) 18 | hsv_s: 0.7 # image HSV-Saturation augmentation (fraction) 19 | hsv_v: 0.4 # image HSV-Value augmentation (fraction) 20 | degrees: 0.0 # image rotation (+/- deg) 21 | translate: 0.2 # image translation (+/- fraction) 22 | scale: 0.5 # image scale (+/- gain) 23 | shear: 0.0 # image shear (+/- deg) 24 | perspective: 0.0 # image perspective (+/- fraction), range 0-0.001 25 | flipud: 0.0 # image flip up-down (probability) 26 | fliplr: 0.5 # image flip left-right (probability) 27 | mosaic: 1.0 # image mosaic (probability) 28 | mixup: 0.0 # image mixup (probability) 29 | copy_paste: 0.0 # image copy paste (probability) 30 | paste_in: 0.0 # image copy paste (probability), use 0 for faster training 31 | loss_ota: 1 # use ComputeLossOTA, use 0 for faster training -------------------------------------------------------------------------------- /Yolov7/data/license.yaml: -------------------------------------------------------------------------------- 1 | train: ./split_dataset/images/train # 21000 images 2 | val: ./split_dataset/images/val # 5000 images 3 | test: ./split_dataset/images/test # 4000 4 | 5 | # number of classes 6 | nc : 1 7 | 8 | #class names 9 | names : ['license'] -------------------------------------------------------------------------------- /Yolov7/detect.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import time 3 | from pathlib import Path 4 | 5 | import cv2 6 | import torch 7 | import torch.backends.cudnn as cudnn 8 | from numpy import random 9 | 10 | from models.experimental import attempt_load 11 | from utils.datasets import LoadStreams, LoadImages 12 | from utils.general import check_img_size, check_requirements, check_imshow, non_max_suppression, apply_classifier, \ 13 | scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path 14 | from utils.plots import plot_one_box 15 | from utils.torch_utils import select_device, load_classifier, time_synchronized, TracedModel 16 | 17 | 18 | def detect(save_img=False): 19 | source, weights, view_img, save_txt, imgsz, trace = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size, not opt.no_trace 20 | save_img = not opt.nosave and not source.endswith('.txt') # save inference images 21 | webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith( 22 | ('rtsp://', 'rtmp://', 'http://', 'https://')) 23 | 24 | # Directories 25 | save_dir = Path(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok)) # increment run 26 | (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir 27 | 28 | # Initialize 29 | set_logging() 30 | device = select_device(opt.device) 31 | half = device.type != 'cpu' # half precision only supported on CUDA 32 | 33 | # Load model 34 | model = attempt_load(weights, map_location=device) # load FP32 model 35 | stride = int(model.stride.max()) # model stride 36 | imgsz = check_img_size(imgsz, s=stride) # check img_size 37 | 38 | if trace: 39 | model = TracedModel(model, device, opt.img_size) 40 | 41 | if half: 42 | model.half() # to FP16 43 | 44 | # Second-stage classifier 45 | classify = False 46 | if classify: 47 | modelc = load_classifier(name='resnet101', n=2) # initialize 48 | modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']).to(device).eval() 49 | 50 | # Set Dataloader 51 | vid_path, vid_writer = None, None 52 | if webcam: 53 | view_img = check_imshow() 54 | cudnn.benchmark = True # set True to speed up constant image size inference 55 | dataset = LoadStreams(source, img_size=imgsz, stride=stride) 56 | else: 57 | dataset = LoadImages(source, img_size=imgsz, stride=stride) 58 | 59 | # Get names and colors 60 | names = model.module.names if hasattr(model, 'module') else model.names 61 | colors = [[random.randint(0, 255) for _ in range(3)] for _ in names] 62 | 63 | # Run inference 64 | if device.type != 'cpu': 65 | model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once 66 | old_img_w = old_img_h = imgsz 67 | old_img_b = 1 68 | 69 | t0 = time.time() 70 | for path, img, im0s, vid_cap in dataset: 71 | img = torch.from_numpy(img).to(device) 72 | img = img.half() if half else img.float() # uint8 to fp16/32 73 | img /= 255.0 # 0 - 255 to 0.0 - 1.0 74 | if img.ndimension() == 3: 75 | img = img.unsqueeze(0) 76 | 77 | # Warmup 78 | if device.type != 'cpu' and (old_img_b != img.shape[0] or old_img_h != img.shape[2] or old_img_w != img.shape[3]): 79 | old_img_b = img.shape[0] 80 | old_img_h = img.shape[2] 81 | old_img_w = img.shape[3] 82 | for i in range(3): 83 | model(img, augment=opt.augment)[0] 84 | 85 | # Inference 86 | t1 = time_synchronized() 87 | with torch.no_grad(): # Calculating gradients would cause a GPU memory leak 88 | pred = model(img, augment=opt.augment)[0] 89 | t2 = time_synchronized() 90 | 91 | # Apply NMS 92 | pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms) 93 | t3 = time_synchronized() 94 | 95 | # Apply Classifier 96 | if classify: 97 | pred = apply_classifier(pred, modelc, img, im0s) 98 | 99 | # Process detections 100 | for i, det in enumerate(pred): # detections per image 101 | if webcam: # batch_size >= 1 102 | p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count 103 | else: 104 | p, s, im0, frame = path, '', im0s, getattr(dataset, 'frame', 0) 105 | 106 | p = Path(p) # to Path 107 | save_path = str(save_dir / p.name) # img.jpg 108 | txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt 109 | gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh 110 | if len(det): 111 | # Rescale boxes from img_size to im0 size 112 | det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round() 113 | 114 | # Print results 115 | for c in det[:, -1].unique(): 116 | n = (det[:, -1] == c).sum() # detections per class 117 | s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string 118 | 119 | # Write results 120 | for *xyxy, conf, cls in reversed(det): 121 | if save_txt: # Write to file 122 | xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh 123 | line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh) # label format 124 | with open(txt_path + '.txt', 'a') as f: 125 | f.write(('%g ' * len(line)).rstrip() % line + '\n') 126 | 127 | if save_img or view_img: # Add bbox to image 128 | label = f'{names[int(cls)]} {conf:.2f}' 129 | plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=1) 130 | 131 | # Print time (inference + NMS) 132 | print(f'{s}Done. ({(1E3 * (t2 - t1)):.1f}ms) Inference, ({(1E3 * (t3 - t2)):.1f}ms) NMS') 133 | 134 | # Stream results 135 | if view_img: 136 | cv2.imshow(str(p), im0) 137 | cv2.waitKey(1) # 1 millisecond 138 | 139 | # Save results (image with detections) 140 | if save_img: 141 | if dataset.mode == 'image': 142 | cv2.imwrite(save_path, im0) 143 | print(f" The image with the result is saved in: {save_path}") 144 | else: # 'video' or 'stream' 145 | if vid_path != save_path: # new video 146 | vid_path = save_path 147 | if isinstance(vid_writer, cv2.VideoWriter): 148 | vid_writer.release() # release previous video writer 149 | if vid_cap: # video 150 | fps = vid_cap.get(cv2.CAP_PROP_FPS) 151 | w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) 152 | h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) 153 | else: # stream 154 | fps, w, h = 30, im0.shape[1], im0.shape[0] 155 | save_path += '.mp4' 156 | vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h)) 157 | vid_writer.write(im0) 158 | 159 | if save_txt or save_img: 160 | s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else '' 161 | #print(f"Results saved to {save_dir}{s}") 162 | 163 | print(f'Done. ({time.time() - t0:.3f}s)') 164 | 165 | 166 | if __name__ == '__main__': 167 | parser = argparse.ArgumentParser() 168 | parser.add_argument('--weights', nargs='+', type=str, default='weights/best.pt', help='model.pt path(s)') 169 | parser.add_argument('--source', type=str, default='VOCCCPDlicense/images/try', help='source') # file/folder, 0 for webcam 170 | parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)') 171 | parser.add_argument('--conf-thres', type=float, default=0.50, help='object confidence threshold') 172 | parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS') 173 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') 174 | parser.add_argument('--view-img', action='store_true', help='display results') 175 | parser.add_argument('--save-txt', action='store_true', help='save results to *.txt') 176 | parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels') 177 | parser.add_argument('--nosave', action='store_true', help='do not save images/videos') 178 | parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3') 179 | parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS') 180 | parser.add_argument('--augment', action='store_true', help='augmented inference') 181 | parser.add_argument('--update', action='store_true', help='update all models') 182 | parser.add_argument('--project', default='runs/detect', help='save results to project/name') 183 | parser.add_argument('--name', default='exp', help='save results to project/name') 184 | parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment') 185 | parser.add_argument('--no-trace', action='store_true', help='don`t trace model') 186 | opt = parser.parse_args() 187 | print(opt) 188 | #check_requirements(exclude=('pycocotools', 'thop')) 189 | 190 | with torch.no_grad(): 191 | if opt.update: # update all models (to fix SourceChangeWarning) 192 | for opt.weights in ['yolov7.pt']: 193 | detect() 194 | strip_optimizer(opt.weights) 195 | else: 196 | detect() 197 | -------------------------------------------------------------------------------- /Yolov7/models/__pycache__/common.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/Yolov7/models/__pycache__/common.cpython-37.pyc -------------------------------------------------------------------------------- /Yolov7/models/__pycache__/experimental.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/Yolov7/models/__pycache__/experimental.cpython-37.pyc -------------------------------------------------------------------------------- /Yolov7/models/__pycache__/yolo.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/Yolov7/models/__pycache__/yolo.cpython-37.pyc -------------------------------------------------------------------------------- /Yolov7/models/experimental.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import random 3 | import torch 4 | import torch.nn as nn 5 | 6 | from models.common import Conv, DWConv 7 | from utils.google_utils import attempt_download 8 | 9 | 10 | class CrossConv(nn.Module): 11 | # Cross Convolution Downsample 12 | def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False): 13 | # ch_in, ch_out, kernel, stride, groups, expansion, shortcut 14 | super(CrossConv, self).__init__() 15 | c_ = int(c2 * e) # hidden channels 16 | self.cv1 = Conv(c1, c_, (1, k), (1, s)) 17 | self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g) 18 | self.add = shortcut and c1 == c2 19 | 20 | def forward(self, x): 21 | return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x)) 22 | 23 | 24 | class Sum(nn.Module): 25 | # Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070 26 | def __init__(self, n, weight=False): # n: number of inputs 27 | super(Sum, self).__init__() 28 | self.weight = weight # apply weights boolean 29 | self.iter = range(n - 1) # iter object 30 | if weight: 31 | self.w = nn.Parameter(-torch.arange(1., n) / 2, requires_grad=True) # layer weights 32 | 33 | def forward(self, x): 34 | y = x[0] # no weight 35 | if self.weight: 36 | w = torch.sigmoid(self.w) * 2 37 | for i in self.iter: 38 | y = y + x[i + 1] * w[i] 39 | else: 40 | for i in self.iter: 41 | y = y + x[i + 1] 42 | return y 43 | 44 | 45 | class MixConv2d(nn.Module): 46 | # Mixed Depthwise Conv https://arxiv.org/abs/1907.09595 47 | def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): 48 | super(MixConv2d, self).__init__() 49 | groups = len(k) 50 | if equal_ch: # equal c_ per group 51 | i = torch.linspace(0, groups - 1E-6, c2).floor() # c2 indices 52 | c_ = [(i == g).sum() for g in range(groups)] # intermediate channels 53 | else: # equal weight.numel() per group 54 | b = [c2] + [0] * groups 55 | a = np.eye(groups + 1, groups, k=-1) 56 | a -= np.roll(a, 1, axis=1) 57 | a *= np.array(k) ** 2 58 | a[0] = 1 59 | c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b 60 | 61 | self.m = nn.ModuleList([nn.Conv2d(c1, int(c_[g]), k[g], s, k[g] // 2, bias=False) for g in range(groups)]) 62 | self.bn = nn.BatchNorm2d(c2) 63 | self.act = nn.LeakyReLU(0.1, inplace=True) 64 | 65 | def forward(self, x): 66 | return x + self.act(self.bn(torch.cat([m(x) for m in self.m], 1))) 67 | 68 | 69 | class Ensemble(nn.ModuleList): 70 | # Ensemble of models 71 | def __init__(self): 72 | super(Ensemble, self).__init__() 73 | 74 | def forward(self, x, augment=False): 75 | y = [] 76 | for module in self: 77 | y.append(module(x, augment)[0]) 78 | # y = torch.stack(y).max(0)[0] # max ensemble 79 | # y = torch.stack(y).mean(0) # mean ensemble 80 | y = torch.cat(y, 1) # nms ensemble 81 | return y, None # inference, train output 82 | 83 | 84 | 85 | 86 | 87 | class ORT_NMS(torch.autograd.Function): 88 | '''ONNX-Runtime NMS operation''' 89 | @staticmethod 90 | def forward(ctx, 91 | boxes, 92 | scores, 93 | max_output_boxes_per_class=torch.tensor([100]), 94 | iou_threshold=torch.tensor([0.45]), 95 | score_threshold=torch.tensor([0.25])): 96 | device = boxes.device 97 | batch = scores.shape[0] 98 | num_det = random.randint(0, 100) 99 | batches = torch.randint(0, batch, (num_det,)).sort()[0].to(device) 100 | idxs = torch.arange(100, 100 + num_det).to(device) 101 | zeros = torch.zeros((num_det,), dtype=torch.int64).to(device) 102 | selected_indices = torch.cat([batches[None], zeros[None], idxs[None]], 0).T.contiguous() 103 | selected_indices = selected_indices.to(torch.int64) 104 | return selected_indices 105 | 106 | @staticmethod 107 | def symbolic(g, boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold): 108 | return g.op("NonMaxSuppression", boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold) 109 | 110 | 111 | class TRT_NMS(torch.autograd.Function): 112 | '''TensorRT NMS operation''' 113 | @staticmethod 114 | def forward( 115 | ctx, 116 | boxes, 117 | scores, 118 | background_class=-1, 119 | box_coding=1, 120 | iou_threshold=0.45, 121 | max_output_boxes=100, 122 | plugin_version="1", 123 | score_activation=0, 124 | score_threshold=0.25, 125 | ): 126 | batch_size, num_boxes, num_classes = scores.shape 127 | num_det = torch.randint(0, max_output_boxes, (batch_size, 1), dtype=torch.int32) 128 | det_boxes = torch.randn(batch_size, max_output_boxes, 4) 129 | det_scores = torch.randn(batch_size, max_output_boxes) 130 | det_classes = torch.randint(0, num_classes, (batch_size, max_output_boxes), dtype=torch.int32) 131 | return num_det, det_boxes, det_scores, det_classes 132 | 133 | @staticmethod 134 | def symbolic(g, 135 | boxes, 136 | scores, 137 | background_class=-1, 138 | box_coding=1, 139 | iou_threshold=0.45, 140 | max_output_boxes=100, 141 | plugin_version="1", 142 | score_activation=0, 143 | score_threshold=0.25): 144 | out = g.op("TRT::EfficientNMS_TRT", 145 | boxes, 146 | scores, 147 | background_class_i=background_class, 148 | box_coding_i=box_coding, 149 | iou_threshold_f=iou_threshold, 150 | max_output_boxes_i=max_output_boxes, 151 | plugin_version_s=plugin_version, 152 | score_activation_i=score_activation, 153 | score_threshold_f=score_threshold, 154 | outputs=4) 155 | nums, boxes, scores, classes = out 156 | return nums, boxes, scores, classes 157 | 158 | 159 | class ONNX_ORT(nn.Module): 160 | '''onnx module with ONNX-Runtime NMS operation.''' 161 | def __init__(self, max_obj=100, iou_thres=0.45, score_thres=0.25, max_wh=640, device=None, n_classes=80): 162 | super().__init__() 163 | self.device = device if device else torch.device("cpu") 164 | self.max_obj = torch.tensor([max_obj]).to(device) 165 | self.iou_threshold = torch.tensor([iou_thres]).to(device) 166 | self.score_threshold = torch.tensor([score_thres]).to(device) 167 | self.max_wh = max_wh # if max_wh != 0 : non-agnostic else : agnostic 168 | self.convert_matrix = torch.tensor([[1, 0, 1, 0], [0, 1, 0, 1], [-0.5, 0, 0.5, 0], [0, -0.5, 0, 0.5]], 169 | dtype=torch.float32, 170 | device=self.device) 171 | self.n_classes=n_classes 172 | 173 | def forward(self, x): 174 | boxes = x[:, :, :4] 175 | conf = x[:, :, 4:5] 176 | scores = x[:, :, 5:] 177 | if self.n_classes == 1: 178 | scores = conf # for models with one class, cls_loss is 0 and cls_conf is always 0.5, 179 | # so there is no need to multiplicate. 180 | else: 181 | scores *= conf # conf = obj_conf * cls_conf 182 | boxes @= self.convert_matrix 183 | max_score, category_id = scores.max(2, keepdim=True) 184 | dis = category_id.float() * self.max_wh 185 | nmsbox = boxes + dis 186 | max_score_tp = max_score.transpose(1, 2).contiguous() 187 | selected_indices = ORT_NMS.apply(nmsbox, max_score_tp, self.max_obj, self.iou_threshold, self.score_threshold) 188 | X, Y = selected_indices[:, 0], selected_indices[:, 2] 189 | selected_boxes = boxes[X, Y, :] 190 | selected_categories = category_id[X, Y, :].float() 191 | selected_scores = max_score[X, Y, :] 192 | X = X.unsqueeze(1).float() 193 | return torch.cat([X, selected_boxes, selected_categories, selected_scores], 1) 194 | 195 | class ONNX_TRT(nn.Module): 196 | '''onnx module with TensorRT NMS operation.''' 197 | def __init__(self, max_obj=100, iou_thres=0.45, score_thres=0.25, max_wh=None ,device=None, n_classes=80): 198 | super().__init__() 199 | assert max_wh is None 200 | self.device = device if device else torch.device('cpu') 201 | self.background_class = -1, 202 | self.box_coding = 1, 203 | self.iou_threshold = iou_thres 204 | self.max_obj = max_obj 205 | self.plugin_version = '1' 206 | self.score_activation = 0 207 | self.score_threshold = score_thres 208 | self.n_classes=n_classes 209 | 210 | def forward(self, x): 211 | boxes = x[:, :, :4] 212 | conf = x[:, :, 4:5] 213 | scores = x[:, :, 5:] 214 | if self.n_classes == 1: 215 | scores = conf # for models with one class, cls_loss is 0 and cls_conf is always 0.5, 216 | # so there is no need to multiplicate. 217 | else: 218 | scores *= conf # conf = obj_conf * cls_conf 219 | num_det, det_boxes, det_scores, det_classes = TRT_NMS.apply(boxes, scores, self.background_class, self.box_coding, 220 | self.iou_threshold, self.max_obj, 221 | self.plugin_version, self.score_activation, 222 | self.score_threshold) 223 | return num_det, det_boxes, det_scores, det_classes 224 | 225 | 226 | class End2End(nn.Module): 227 | '''export onnx or tensorrt model with NMS operation.''' 228 | def __init__(self, model, max_obj=100, iou_thres=0.45, score_thres=0.25, max_wh=None, device=None, n_classes=80): 229 | super().__init__() 230 | device = device if device else torch.device('cpu') 231 | assert isinstance(max_wh,(int)) or max_wh is None 232 | self.model = model.to(device) 233 | self.model.model[-1].end2end = True 234 | self.patch_model = ONNX_TRT if max_wh is None else ONNX_ORT 235 | self.end2end = self.patch_model(max_obj, iou_thres, score_thres, max_wh, device, n_classes) 236 | self.end2end.eval() 237 | 238 | def forward(self, x): 239 | x = self.model(x) 240 | x = self.end2end(x) 241 | return x 242 | 243 | 244 | 245 | 246 | 247 | def attempt_load(weights, map_location=None): 248 | # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a 249 | model = Ensemble() 250 | for w in weights if isinstance(weights, list) else [weights]: 251 | attempt_download(w) 252 | ckpt = torch.load(w, map_location=map_location) # load 253 | model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().fuse().eval()) # FP32 model 254 | 255 | # Compatibility updates 256 | for m in model.modules(): 257 | if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]: 258 | m.inplace = True # pytorch 1.7.0 compatibility 259 | elif type(m) is nn.Upsample: 260 | m.recompute_scale_factor = None # torch 1.11.0 compatibility 261 | elif type(m) is Conv: 262 | m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility 263 | 264 | if len(model) == 1: 265 | return model[-1] # return model 266 | else: 267 | print('Ensemble created with %s\n' % weights) 268 | for k in ['names', 'stride']: 269 | setattr(model, k, getattr(model[-1], k)) 270 | return model # return ensemble 271 | 272 | 273 | -------------------------------------------------------------------------------- /Yolov7/runs/detect/exp/0275-93_75-201&483_486&587-491&584_211&566_183&474_463&492-0_0_27_14_28_29_29-93-58.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/Yolov7/runs/detect/exp/0275-93_75-201&483_486&587-491&584_211&566_183&474_463&492-0_0_27_14_28_29_29-93-58.jpg -------------------------------------------------------------------------------- /Yolov7/runs/detect/exp/0275-93_82-352&510_649&606-629&619_349&588_339&500_619&531-0_0_28_28_21_33_29-84-25.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/Yolov7/runs/detect/exp/0275-93_82-352&510_649&606-629&619_349&588_339&500_619&531-0_0_28_28_21_33_29-84-25.jpg -------------------------------------------------------------------------------- /Yolov7/runs/detect/exp/03-91_90-283&402_600&524-589&515_285&521_296&411_600&405-0_0_22_27_1_24_32-154-73.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/Yolov7/runs/detect/exp/03-91_90-283&402_600&524-589&515_285&521_296&411_600&405-0_0_22_27_1_24_32-154-73.jpg -------------------------------------------------------------------------------- /Yolov7/runs/detect/exp/03-92_86-111&425_419&538-427&544_98&523_105&413_434&434-0_0_23_32_32_32_33-137-60.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/Yolov7/runs/detect/exp/03-92_86-111&425_419&538-427&544_98&523_105&413_434&434-0_0_23_32_32_32_33-137-60.jpg -------------------------------------------------------------------------------- /Yolov7/runs/detect/exp/labels/0275-93_75-201&483_486&587-491&584_211&566_183&474_463&492-0_0_27_14_28_29_29-93-58.txt: -------------------------------------------------------------------------------- 1 | 0 0.46875 0.458621 0.381944 0.0775862 2 | -------------------------------------------------------------------------------- /Yolov7/runs/detect/exp/labels/0275-93_82-352&510_649&606-629&619_349&588_339&500_619&531-0_0_28_28_21_33_29-84-25.txt: -------------------------------------------------------------------------------- 1 | 0 0.679167 0.483621 0.377778 0.0913793 2 | -------------------------------------------------------------------------------- /Yolov7/runs/detect/exp/labels/03-91_90-283&402_600&524-589&515_285&521_296&411_600&405-0_0_22_27_1_24_32-154-73.txt: -------------------------------------------------------------------------------- 1 | 0 0.604167 0.399569 0.427778 0.087069 2 | -------------------------------------------------------------------------------- /Yolov7/runs/detect/exp/labels/03-92_86-111&425_419&538-427&544_98&523_105&413_434&434-0_0_23_32_32_32_33-137-60.txt: -------------------------------------------------------------------------------- 1 | 0 0.364583 0.414655 0.459722 0.0948276 2 | -------------------------------------------------------------------------------- /Yolov7/utils/__pycache__/autoanchor.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/Yolov7/utils/__pycache__/autoanchor.cpython-37.pyc -------------------------------------------------------------------------------- /Yolov7/utils/__pycache__/datasets.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/Yolov7/utils/__pycache__/datasets.cpython-37.pyc -------------------------------------------------------------------------------- /Yolov7/utils/__pycache__/general.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/Yolov7/utils/__pycache__/general.cpython-37.pyc -------------------------------------------------------------------------------- /Yolov7/utils/__pycache__/google_utils.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/Yolov7/utils/__pycache__/google_utils.cpython-37.pyc -------------------------------------------------------------------------------- /Yolov7/utils/__pycache__/loss.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/Yolov7/utils/__pycache__/loss.cpython-37.pyc -------------------------------------------------------------------------------- /Yolov7/utils/__pycache__/metrics.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/Yolov7/utils/__pycache__/metrics.cpython-37.pyc -------------------------------------------------------------------------------- /Yolov7/utils/__pycache__/plots.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/Yolov7/utils/__pycache__/plots.cpython-37.pyc -------------------------------------------------------------------------------- /Yolov7/utils/__pycache__/torch_utils.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fanstuck/Yolov7-LPRNet/13f962fb37309ffa0c27f9c888877e7986960177/Yolov7/utils/__pycache__/torch_utils.cpython-37.pyc -------------------------------------------------------------------------------- /Yolov7/utils/activations.py: -------------------------------------------------------------------------------- 1 | # Activation functions 2 | 3 | import torch 4 | import torch.nn as nn 5 | import torch.nn.functional as F 6 | 7 | 8 | # SiLU https://arxiv.org/pdf/1606.08415.pdf ---------------------------------------------------------------------------- 9 | class SiLU(nn.Module): # export-friendly version of nn.SiLU() 10 | @staticmethod 11 | def forward(x): 12 | return x * torch.sigmoid(x) 13 | 14 | 15 | class Hardswish(nn.Module): # export-friendly version of nn.Hardswish() 16 | @staticmethod 17 | def forward(x): 18 | # return x * F.hardsigmoid(x) # for torchscript and CoreML 19 | return x * F.hardtanh(x + 3, 0., 6.) / 6. # for torchscript, CoreML and ONNX 20 | 21 | 22 | class MemoryEfficientSwish(nn.Module): 23 | class F(torch.autograd.Function): 24 | @staticmethod 25 | def forward(ctx, x): 26 | ctx.save_for_backward(x) 27 | return x * torch.sigmoid(x) 28 | 29 | @staticmethod 30 | def backward(ctx, grad_output): 31 | x = ctx.saved_tensors[0] 32 | sx = torch.sigmoid(x) 33 | return grad_output * (sx * (1 + x * (1 - sx))) 34 | 35 | def forward(self, x): 36 | return self.F.apply(x) 37 | 38 | 39 | # Mish https://github.com/digantamisra98/Mish -------------------------------------------------------------------------- 40 | class Mish(nn.Module): 41 | @staticmethod 42 | def forward(x): 43 | return x * F.softplus(x).tanh() 44 | 45 | 46 | class MemoryEfficientMish(nn.Module): 47 | class F(torch.autograd.Function): 48 | @staticmethod 49 | def forward(ctx, x): 50 | ctx.save_for_backward(x) 51 | return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x))) 52 | 53 | @staticmethod 54 | def backward(ctx, grad_output): 55 | x = ctx.saved_tensors[0] 56 | sx = torch.sigmoid(x) 57 | fx = F.softplus(x).tanh() 58 | return grad_output * (fx + x * sx * (1 - fx * fx)) 59 | 60 | def forward(self, x): 61 | return self.F.apply(x) 62 | 63 | 64 | # FReLU https://arxiv.org/abs/2007.11824 ------------------------------------------------------------------------------- 65 | class FReLU(nn.Module): 66 | def __init__(self, c1, k=3): # ch_in, kernel 67 | super().__init__() 68 | self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False) 69 | self.bn = nn.BatchNorm2d(c1) 70 | 71 | def forward(self, x): 72 | return torch.max(x, self.bn(self.conv(x))) 73 | -------------------------------------------------------------------------------- /Yolov7/utils/add_nms.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import onnx 3 | from onnx import shape_inference 4 | try: 5 | import onnx_graphsurgeon as gs 6 | except Exception as e: 7 | print('Import onnx_graphsurgeon failure: %s' % e) 8 | 9 | import logging 10 | 11 | LOGGER = logging.getLogger(__name__) 12 | 13 | class RegisterNMS(object): 14 | def __init__( 15 | self, 16 | onnx_model_path: str, 17 | precision: str = "fp32", 18 | ): 19 | 20 | self.graph = gs.import_onnx(onnx.load(onnx_model_path)) 21 | assert self.graph 22 | LOGGER.info("ONNX graph created successfully") 23 | # Fold constants via ONNX-GS that PyTorch2ONNX may have missed 24 | self.graph.fold_constants() 25 | self.precision = precision 26 | self.batch_size = 1 27 | def infer(self): 28 | """ 29 | Sanitize the graph by cleaning any unconnected nodes, do a topological resort, 30 | and fold constant inputs values. When possible, run shape inference on the 31 | ONNX graph to determine tensor shapes. 32 | """ 33 | for _ in range(3): 34 | count_before = len(self.graph.nodes) 35 | 36 | self.graph.cleanup().toposort() 37 | try: 38 | for node in self.graph.nodes: 39 | for o in node.outputs: 40 | o.shape = None 41 | model = gs.export_onnx(self.graph) 42 | model = shape_inference.infer_shapes(model) 43 | self.graph = gs.import_onnx(model) 44 | except Exception as e: 45 | LOGGER.info(f"Shape inference could not be performed at this time:\n{e}") 46 | try: 47 | self.graph.fold_constants(fold_shapes=True) 48 | except TypeError as e: 49 | LOGGER.error( 50 | "This version of ONNX GraphSurgeon does not support folding shapes, " 51 | f"please upgrade your onnx_graphsurgeon module. Error:\n{e}" 52 | ) 53 | raise 54 | 55 | count_after = len(self.graph.nodes) 56 | if count_before == count_after: 57 | # No new folding occurred in this iteration, so we can stop for now. 58 | break 59 | 60 | def save(self, output_path): 61 | """ 62 | Save the ONNX model to the given location. 63 | Args: 64 | output_path: Path pointing to the location where to write 65 | out the updated ONNX model. 66 | """ 67 | self.graph.cleanup().toposort() 68 | model = gs.export_onnx(self.graph) 69 | onnx.save(model, output_path) 70 | LOGGER.info(f"Saved ONNX model to {output_path}") 71 | 72 | def register_nms( 73 | self, 74 | *, 75 | score_thresh: float = 0.25, 76 | nms_thresh: float = 0.45, 77 | detections_per_img: int = 100, 78 | ): 79 | """ 80 | Register the ``EfficientNMS_TRT`` plugin node. 81 | NMS expects these shapes for its input tensors: 82 | - box_net: [batch_size, number_boxes, 4] 83 | - class_net: [batch_size, number_boxes, number_labels] 84 | Args: 85 | score_thresh (float): The scalar threshold for score (low scoring boxes are removed). 86 | nms_thresh (float): The scalar threshold for IOU (new boxes that have high IOU 87 | overlap with previously selected boxes are removed). 88 | detections_per_img (int): Number of best detections to keep after NMS. 89 | """ 90 | 91 | self.infer() 92 | # Find the concat node at the end of the network 93 | op_inputs = self.graph.outputs 94 | op = "EfficientNMS_TRT" 95 | attrs = { 96 | "plugin_version": "1", 97 | "background_class": -1, # no background class 98 | "max_output_boxes": detections_per_img, 99 | "score_threshold": score_thresh, 100 | "iou_threshold": nms_thresh, 101 | "score_activation": False, 102 | "box_coding": 0, 103 | } 104 | 105 | if self.precision == "fp32": 106 | dtype_output = np.float32 107 | elif self.precision == "fp16": 108 | dtype_output = np.float16 109 | else: 110 | raise NotImplementedError(f"Currently not supports precision: {self.precision}") 111 | 112 | # NMS Outputs 113 | output_num_detections = gs.Variable( 114 | name="num_dets", 115 | dtype=np.int32, 116 | shape=[self.batch_size, 1], 117 | ) # A scalar indicating the number of valid detections per batch image. 118 | output_boxes = gs.Variable( 119 | name="det_boxes", 120 | dtype=dtype_output, 121 | shape=[self.batch_size, detections_per_img, 4], 122 | ) 123 | output_scores = gs.Variable( 124 | name="det_scores", 125 | dtype=dtype_output, 126 | shape=[self.batch_size, detections_per_img], 127 | ) 128 | output_labels = gs.Variable( 129 | name="det_classes", 130 | dtype=np.int32, 131 | shape=[self.batch_size, detections_per_img], 132 | ) 133 | 134 | op_outputs = [output_num_detections, output_boxes, output_scores, output_labels] 135 | 136 | # Create the NMS Plugin node with the selected inputs. The outputs of the node will also 137 | # become the final outputs of the graph. 138 | self.graph.layer(op=op, name="batched_nms", inputs=op_inputs, outputs=op_outputs, attrs=attrs) 139 | LOGGER.info(f"Created NMS plugin '{op}' with attributes: {attrs}") 140 | 141 | self.graph.outputs = op_outputs 142 | 143 | self.infer() 144 | 145 | def save(self, output_path): 146 | """ 147 | Save the ONNX model to the given location. 148 | Args: 149 | output_path: Path pointing to the location where to write 150 | out the updated ONNX model. 151 | """ 152 | self.graph.cleanup().toposort() 153 | model = gs.export_onnx(self.graph) 154 | onnx.save(model, output_path) 155 | LOGGER.info(f"Saved ONNX model to {output_path}") 156 | -------------------------------------------------------------------------------- /Yolov7/utils/autoanchor.py: -------------------------------------------------------------------------------- 1 | # Auto-anchor utils 2 | 3 | import numpy as np 4 | import torch 5 | import yaml 6 | from scipy.cluster.vq import kmeans 7 | from tqdm import tqdm 8 | 9 | from utils.general import colorstr 10 | 11 | 12 | def check_anchor_order(m): 13 | # Check anchor order against stride order for YOLO Detect() module m, and correct if necessary 14 | a = m.anchor_grid.prod(-1).view(-1) # anchor area 15 | da = a[-1] - a[0] # delta a 16 | ds = m.stride[-1] - m.stride[0] # delta s 17 | if da.sign() != ds.sign(): # same order 18 | print('Reversing anchor order') 19 | m.anchors[:] = m.anchors.flip(0) 20 | m.anchor_grid[:] = m.anchor_grid.flip(0) 21 | 22 | 23 | def check_anchors(dataset, model, thr=4.0, imgsz=640): 24 | # Check anchor fit to data, recompute if necessary 25 | prefix = colorstr('autoanchor: ') 26 | print(f'\n{prefix}Analyzing anchors... ', end='') 27 | m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect() 28 | shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True) 29 | scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale 30 | wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh 31 | 32 | def metric(k): # compute metric 33 | r = wh[:, None] / k[None] 34 | x = torch.min(r, 1. / r).min(2)[0] # ratio metric 35 | best = x.max(1)[0] # best_x 36 | aat = (x > 1. / thr).float().sum(1).mean() # anchors above threshold 37 | bpr = (best > 1. / thr).float().mean() # best possible recall 38 | return bpr, aat 39 | 40 | anchors = m.anchor_grid.clone().cpu().view(-1, 2) # current anchors 41 | bpr, aat = metric(anchors) 42 | print(f'anchors/target = {aat:.2f}, Best Possible Recall (BPR) = {bpr:.4f}', end='') 43 | if bpr < 0.98: # threshold to recompute 44 | print('. Attempting to improve anchors, please wait...') 45 | na = m.anchor_grid.numel() // 2 # number of anchors 46 | try: 47 | anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False) 48 | except Exception as e: 49 | print(f'{prefix}ERROR: {e}') 50 | new_bpr = metric(anchors)[0] 51 | if new_bpr > bpr: # replace anchors 52 | anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors) 53 | m.anchor_grid[:] = anchors.clone().view_as(m.anchor_grid) # for inference 54 | check_anchor_order(m) 55 | m.anchors[:] = anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1) # loss 56 | print(f'{prefix}New anchors saved to model. Update model *.yaml to use these anchors in the future.') 57 | else: 58 | print(f'{prefix}Original anchors better than new anchors. Proceeding with original anchors.') 59 | print('') # newline 60 | 61 | 62 | def kmean_anchors(path='./data/coco.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True): 63 | """ Creates kmeans-evolved anchors from training dataset 64 | 65 | Arguments: 66 | path: path to dataset *.yaml, or a loaded dataset 67 | n: number of anchors 68 | img_size: image size used for training 69 | thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0 70 | gen: generations to evolve anchors using genetic algorithm 71 | verbose: print all results 72 | 73 | Return: 74 | k: kmeans evolved anchors 75 | 76 | Usage: 77 | from utils.autoanchor import *; _ = kmean_anchors() 78 | """ 79 | thr = 1. / thr 80 | prefix = colorstr('autoanchor: ') 81 | 82 | def metric(k, wh): # compute metrics 83 | r = wh[:, None] / k[None] 84 | x = torch.min(r, 1. / r).min(2)[0] # ratio metric 85 | # x = wh_iou(wh, torch.tensor(k)) # iou metric 86 | return x, x.max(1)[0] # x, best_x 87 | 88 | def anchor_fitness(k): # mutation fitness 89 | _, best = metric(torch.tensor(k, dtype=torch.float32), wh) 90 | return (best * (best > thr).float()).mean() # fitness 91 | 92 | def print_results(k): 93 | k = k[np.argsort(k.prod(1))] # sort small to large 94 | x, best = metric(k, wh0) 95 | bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr 96 | print(f'{prefix}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr') 97 | print(f'{prefix}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, ' 98 | f'past_thr={x[x > thr].mean():.3f}-mean: ', end='') 99 | for i, x in enumerate(k): 100 | print('%i,%i' % (round(x[0]), round(x[1])), end=', ' if i < len(k) - 1 else '\n') # use in *.cfg 101 | return k 102 | 103 | if isinstance(path, str): # *.yaml file 104 | with open(path) as f: 105 | data_dict = yaml.load(f, Loader=yaml.SafeLoader) # model dict 106 | from utils.datasets import LoadImagesAndLabels 107 | dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True) 108 | else: 109 | dataset = path # dataset 110 | 111 | # Get label wh 112 | shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True) 113 | wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh 114 | 115 | # Filter 116 | i = (wh0 < 3.0).any(1).sum() 117 | if i: 118 | print(f'{prefix}WARNING: Extremely small objects found. {i} of {len(wh0)} labels are < 3 pixels in size.') 119 | wh = wh0[(wh0 >= 2.0).any(1)] # filter > 2 pixels 120 | # wh = wh * (np.random.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1 121 | 122 | # Kmeans calculation 123 | print(f'{prefix}Running kmeans for {n} anchors on {len(wh)} points...') 124 | s = wh.std(0) # sigmas for whitening 125 | k, dist = kmeans(wh / s, n, iter=30) # points, mean distance 126 | assert len(k) == n, print(f'{prefix}ERROR: scipy.cluster.vq.kmeans requested {n} points but returned only {len(k)}') 127 | k *= s 128 | wh = torch.tensor(wh, dtype=torch.float32) # filtered 129 | wh0 = torch.tensor(wh0, dtype=torch.float32) # unfiltered 130 | k = print_results(k) 131 | 132 | # Plot 133 | # k, d = [None] * 20, [None] * 20 134 | # for i in tqdm(range(1, 21)): 135 | # k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance 136 | # fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True) 137 | # ax = ax.ravel() 138 | # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.') 139 | # fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh 140 | # ax[0].hist(wh[wh[:, 0]<100, 0],400) 141 | # ax[1].hist(wh[wh[:, 1]<100, 1],400) 142 | # fig.savefig('wh.png', dpi=200) 143 | 144 | # Evolve 145 | npr = np.random 146 | f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma 147 | pbar = tqdm(range(gen), desc=f'{prefix}Evolving anchors with Genetic Algorithm:') # progress bar 148 | for _ in pbar: 149 | v = np.ones(sh) 150 | while (v == 1).all(): # mutate until a change occurs (prevent duplicates) 151 | v = ((npr.random(sh) < mp) * npr.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0) 152 | kg = (k.copy() * v).clip(min=2.0) 153 | fg = anchor_fitness(kg) 154 | if fg > f: 155 | f, k = fg, kg.copy() 156 | pbar.desc = f'{prefix}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}' 157 | if verbose: 158 | print_results(k) 159 | 160 | return print_results(k) 161 | -------------------------------------------------------------------------------- /Yolov7/utils/general.py: -------------------------------------------------------------------------------- 1 | # YOLOR general utils 2 | 3 | import glob 4 | import logging 5 | import math 6 | import os 7 | import platform 8 | import random 9 | import re 10 | import subprocess 11 | import time 12 | from pathlib import Path 13 | 14 | import cv2 15 | import numpy as np 16 | import pandas as pd 17 | import torch 18 | import torchvision 19 | import yaml 20 | 21 | from utils.google_utils import gsutil_getsize 22 | from utils.metrics import fitness 23 | from utils.torch_utils import init_torch_seeds 24 | 25 | # Settings 26 | torch.set_printoptions(linewidth=320, precision=5, profile='long') 27 | np.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format}) # format short g, %precision=5 28 | pd.options.display.max_columns = 10 29 | cv2.setNumThreads(0) # prevent OpenCV from multithreading (incompatible with PyTorch DataLoader) 30 | os.environ['NUMEXPR_MAX_THREADS'] = str(min(os.cpu_count(), 8)) # NumExpr max threads 31 | 32 | 33 | def set_logging(rank=-1): 34 | logging.basicConfig( 35 | format="%(message)s", 36 | level=logging.INFO if rank in [-1, 0] else logging.WARN) 37 | 38 | 39 | def init_seeds(seed=0): 40 | # Initialize random number generator (RNG) seeds 41 | random.seed(seed) 42 | np.random.seed(seed) 43 | init_torch_seeds(seed) 44 | 45 | 46 | def get_latest_run(search_dir='.'): 47 | # Return path to most recent 'last.pt' in /runs (i.e. to --resume from) 48 | last_list = glob.glob(f'{search_dir}/**/last*.pt', recursive=True) 49 | return max(last_list, key=os.path.getctime) if last_list else '' 50 | 51 | 52 | def isdocker(): 53 | # Is environment a Docker container 54 | return Path('/workspace').exists() # or Path('/.dockerenv').exists() 55 | 56 | 57 | def emojis(str=''): 58 | # Return platform-dependent emoji-safe version of string 59 | return str.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else str 60 | 61 | 62 | def check_online(): 63 | # Check internet connectivity 64 | import socket 65 | try: 66 | socket.create_connection(("1.1.1.1", 443), 5) # check host accesability 67 | return True 68 | except OSError: 69 | return False 70 | 71 | 72 | def check_git_status(): 73 | # Recommend 'git pull' if code is out of date 74 | print(colorstr('github: '), end='') 75 | try: 76 | assert Path('.git').exists(), 'skipping check (not a git repository)' 77 | assert not isdocker(), 'skipping check (Docker image)' 78 | assert check_online(), 'skipping check (offline)' 79 | 80 | cmd = 'git fetch && git config --get remote.origin.url' 81 | url = subprocess.check_output(cmd, shell=True).decode().strip().rstrip('.git') # github repo url 82 | branch = subprocess.check_output('git rev-parse --abbrev-ref HEAD', shell=True).decode().strip() # checked out 83 | n = int(subprocess.check_output(f'git rev-list {branch}..origin/master --count', shell=True)) # commits behind 84 | if n > 0: 85 | s = f"⚠️ WARNING: code is out of date by {n} commit{'s' * (n > 1)}. " \ 86 | f"Use 'git pull' to update or 'git clone {url}' to download latest." 87 | else: 88 | s = f'up to date with {url} ✅' 89 | print(emojis(s)) # emoji-safe 90 | except Exception as e: 91 | print(e) 92 | 93 | 94 | def check_requirements(requirements='requirements.txt', exclude=()): 95 | # Check installed dependencies meet requirements (pass *.txt file or list of packages) 96 | import pkg_resources as pkg 97 | prefix = colorstr('red', 'bold', 'requirements:') 98 | if isinstance(requirements, (str, Path)): # requirements.txt file 99 | file = Path(requirements) 100 | if not file.exists(): 101 | print(f"{prefix} {file.resolve()} not found, check failed.") 102 | return 103 | requirements = [f'{x.name}{x.specifier}' for x in pkg.parse_requirements(file.open()) if x.name not in exclude] 104 | else: # list or tuple of packages 105 | requirements = [x for x in requirements if x not in exclude] 106 | 107 | n = 0 # number of packages updates 108 | for r in requirements: 109 | try: 110 | pkg.require(r) 111 | except Exception as e: # DistributionNotFound or VersionConflict if requirements not met 112 | n += 1 113 | print(f"{prefix} {e.req} not found and is required by YOLOR, attempting auto-update...") 114 | print(subprocess.check_output(f"pip install '{e.req}'", shell=True).decode()) 115 | 116 | if n: # if packages updated 117 | source = file.resolve() if 'file' in locals() else requirements 118 | s = f"{prefix} {n} package{'s' * (n > 1)} updated per {source}\n" \ 119 | f"{prefix} ⚠️ {colorstr('bold', 'Restart runtime or rerun command for updates to take effect')}\n" 120 | print(emojis(s)) # emoji-safe 121 | 122 | 123 | def check_img_size(img_size, s=32): 124 | # Verify img_size is a multiple of stride s 125 | new_size = make_divisible(img_size, int(s)) # ceil gs-multiple 126 | if new_size != img_size: 127 | print('WARNING: --img-size %g must be multiple of max stride %g, updating to %g' % (img_size, s, new_size)) 128 | return new_size 129 | 130 | 131 | def check_imshow(): 132 | # Check if environment supports image displays 133 | try: 134 | assert not isdocker(), 'cv2.imshow() is disabled in Docker environments' 135 | cv2.imshow('test', np.zeros((1, 1, 3))) 136 | cv2.waitKey(1) 137 | cv2.destroyAllWindows() 138 | cv2.waitKey(1) 139 | return True 140 | except Exception as e: 141 | print(f'WARNING: Environment does not support cv2.imshow() or PIL Image.show() image displays\n{e}') 142 | return False 143 | 144 | 145 | def check_file(file): 146 | # Search for file if not found 147 | if Path(file).is_file() or file == '': 148 | return file 149 | else: 150 | files = glob.glob('./**/' + file, recursive=True) # find file 151 | assert len(files), f'File Not Found: {file}' # assert file was found 152 | assert len(files) == 1, f"Multiple files match '{file}', specify exact path: {files}" # assert unique 153 | return files[0] # return file 154 | 155 | 156 | def check_dataset(dict): 157 | # Download dataset if not found locally 158 | val, s = dict.get('val'), dict.get('download') 159 | if val and len(val): 160 | val = [Path(x).resolve() for x in (val if isinstance(val, list) else [val])] # val path 161 | if not all(x.exists() for x in val): 162 | print('\nWARNING: Dataset not found, nonexistent paths: %s' % [str(x) for x in val if not x.exists()]) 163 | if s and len(s): # download script 164 | print('Downloading %s ...' % s) 165 | if s.startswith('http') and s.endswith('.zip'): # URL 166 | f = Path(s).name # filename 167 | torch.hub.download_url_to_file(s, f) 168 | r = os.system('unzip -q %s -d ../ && rm %s' % (f, f)) # unzip 169 | else: # bash script 170 | r = os.system(s) 171 | print('Dataset autodownload %s\n' % ('success' if r == 0 else 'failure')) # analyze return value 172 | else: 173 | raise Exception('Dataset not found.') 174 | 175 | 176 | def make_divisible(x, divisor): 177 | # Returns x evenly divisible by divisor 178 | return math.ceil(x / divisor) * divisor 179 | 180 | 181 | def clean_str(s): 182 | # Cleans a string by replacing special characters with underscore _ 183 | return re.sub(pattern="[|@#!¡·$€%&()=?¿^*;:,¨´><+]", repl="_", string=s) 184 | 185 | 186 | def one_cycle(y1=0.0, y2=1.0, steps=100): 187 | # lambda function for sinusoidal ramp from y1 to y2 188 | return lambda x: ((1 - math.cos(x * math.pi / steps)) / 2) * (y2 - y1) + y1 189 | 190 | 191 | def colorstr(*input): 192 | # Colors a string https://en.wikipedia.org/wiki/ANSI_escape_code, i.e. colorstr('blue', 'hello world') 193 | *args, string = input if len(input) > 1 else ('blue', 'bold', input[0]) # color arguments, string 194 | colors = {'black': '\033[30m', # basic colors 195 | 'red': '\033[31m', 196 | 'green': '\033[32m', 197 | 'yellow': '\033[33m', 198 | 'blue': '\033[34m', 199 | 'magenta': '\033[35m', 200 | 'cyan': '\033[36m', 201 | 'white': '\033[37m', 202 | 'bright_black': '\033[90m', # bright colors 203 | 'bright_red': '\033[91m', 204 | 'bright_green': '\033[92m', 205 | 'bright_yellow': '\033[93m', 206 | 'bright_blue': '\033[94m', 207 | 'bright_magenta': '\033[95m', 208 | 'bright_cyan': '\033[96m', 209 | 'bright_white': '\033[97m', 210 | 'end': '\033[0m', # misc 211 | 'bold': '\033[1m', 212 | 'underline': '\033[4m'} 213 | return ''.join(colors[x] for x in args) + f'{string}' + colors['end'] 214 | 215 | 216 | def labels_to_class_weights(labels, nc=80): 217 | # Get class weights (inverse frequency) from training labels 218 | if labels[0] is None: # no labels loaded 219 | return torch.Tensor() 220 | 221 | labels = np.concatenate(labels, 0) # labels.shape = (866643, 5) for COCO 222 | classes = labels[:, 0].astype(np.int32) # labels = [class xywh] 223 | weights = np.bincount(classes, minlength=nc) # occurrences per class 224 | 225 | # Prepend gridpoint count (for uCE training) 226 | # gpi = ((320 / 32 * np.array([1, 2, 4])) ** 2 * 3).sum() # gridpoints per image 227 | # weights = np.hstack([gpi * len(labels) - weights.sum() * 9, weights * 9]) ** 0.5 # prepend gridpoints to start 228 | 229 | weights[weights == 0] = 1 # replace empty bins with 1 230 | weights = 1 / weights # number of targets per class 231 | weights /= weights.sum() # normalize 232 | return torch.from_numpy(weights) 233 | 234 | 235 | def labels_to_image_weights(labels, nc=80, class_weights=np.ones(80)): 236 | # Produces image weights based on class_weights and image contents 237 | class_counts = np.array([np.bincount(x[:, 0].astype(np.int32), minlength=nc) for x in labels]) 238 | image_weights = (class_weights.reshape(1, nc) * class_counts).sum(1) 239 | # index = random.choices(range(n), weights=image_weights, k=1) # weight image sample 240 | return image_weights 241 | 242 | 243 | def coco80_to_coco91_class(): # converts 80-index (val2014) to 91-index (paper) 244 | # https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/ 245 | # a = np.loadtxt('data/coco.names', dtype='str', delimiter='\n') 246 | # b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='\n') 247 | # x1 = [list(a[i] == b).index(True) + 1 for i in range(80)] # darknet to coco 248 | # x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)] # coco to darknet 249 | 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, 250 | 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, 251 | 64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90] 252 | return x 253 | 254 | 255 | def xyxy2xywh(x): 256 | # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right 257 | y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) 258 | y[:, 0] = (x[:, 0] + x[:, 2]) / 2 # x center 259 | y[:, 1] = (x[:, 1] + x[:, 3]) / 2 # y center 260 | y[:, 2] = x[:, 2] - x[:, 0] # width 261 | y[:, 3] = x[:, 3] - x[:, 1] # height 262 | return y 263 | 264 | 265 | def xywh2xyxy(x): 266 | # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right 267 | y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) 268 | y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x 269 | y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y 270 | y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x 271 | y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y 272 | return y 273 | 274 | 275 | def xywhn2xyxy(x, w=640, h=640, padw=0, padh=0): 276 | # Convert nx4 boxes from [x, y, w, h] normalized to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right 277 | y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) 278 | y[:, 0] = w * (x[:, 0] - x[:, 2] / 2) + padw # top left x 279 | y[:, 1] = h * (x[:, 1] - x[:, 3] / 2) + padh # top left y 280 | y[:, 2] = w * (x[:, 0] + x[:, 2] / 2) + padw # bottom right x 281 | y[:, 3] = h * (x[:, 1] + x[:, 3] / 2) + padh # bottom right y 282 | return y 283 | 284 | 285 | def xyn2xy(x, w=640, h=640, padw=0, padh=0): 286 | # Convert normalized segments into pixel segments, shape (n,2) 287 | y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) 288 | y[:, 0] = w * x[:, 0] + padw # top left x 289 | y[:, 1] = h * x[:, 1] + padh # top left y 290 | return y 291 | 292 | 293 | def segment2box(segment, width=640, height=640): 294 | # Convert 1 segment label to 1 box label, applying inside-image constraint, i.e. (xy1, xy2, ...) to (xyxy) 295 | x, y = segment.T # segment xy 296 | inside = (x >= 0) & (y >= 0) & (x <= width) & (y <= height) 297 | x, y, = x[inside], y[inside] 298 | return np.array([x.min(), y.min(), x.max(), y.max()]) if any(x) else np.zeros((1, 4)) # xyxy 299 | 300 | 301 | def segments2boxes(segments): 302 | # Convert segment labels to box labels, i.e. (cls, xy1, xy2, ...) to (cls, xywh) 303 | boxes = [] 304 | for s in segments: 305 | x, y = s.T # segment xy 306 | boxes.append([x.min(), y.min(), x.max(), y.max()]) # cls, xyxy 307 | return xyxy2xywh(np.array(boxes)) # cls, xywh 308 | 309 | 310 | def resample_segments(segments, n=1000): 311 | # Up-sample an (n,2) segment 312 | for i, s in enumerate(segments): 313 | s = np.concatenate((s, s[0:1, :]), axis=0) 314 | x = np.linspace(0, len(s) - 1, n) 315 | xp = np.arange(len(s)) 316 | segments[i] = np.concatenate([np.interp(x, xp, s[:, i]) for i in range(2)]).reshape(2, -1).T # segment xy 317 | return segments 318 | 319 | 320 | def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None): 321 | # Rescale coords (xyxy) from img1_shape to img0_shape 322 | if ratio_pad is None: # calculate from img0_shape 323 | gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new 324 | pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding 325 | else: 326 | gain = ratio_pad[0][0] 327 | pad = ratio_pad[1] 328 | 329 | coords[:, [0, 2]] -= pad[0] # x padding 330 | coords[:, [1, 3]] -= pad[1] # y padding 331 | coords[:, :4] /= gain 332 | clip_coords(coords, img0_shape) 333 | return coords 334 | 335 | 336 | def clip_coords(boxes, img_shape): 337 | # Clip bounding xyxy bounding boxes to image shape (height, width) 338 | boxes[:, 0].clamp_(0, img_shape[1]) # x1 339 | boxes[:, 1].clamp_(0, img_shape[0]) # y1 340 | boxes[:, 2].clamp_(0, img_shape[1]) # x2 341 | boxes[:, 3].clamp_(0, img_shape[0]) # y2 342 | 343 | 344 | def bbox_iou(box1, box2, x1y1x2y2=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-7): 345 | # Returns the IoU of box1 to box2. box1 is 4, box2 is nx4 346 | box2 = box2.T 347 | 348 | # Get the coordinates of bounding boxes 349 | if x1y1x2y2: # x1, y1, x2, y2 = box1 350 | b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3] 351 | b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3] 352 | else: # transform from xywh to xyxy 353 | b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2 354 | b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2 355 | b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2 356 | b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2 357 | 358 | # Intersection area 359 | inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \ 360 | (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0) 361 | 362 | # Union Area 363 | w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps 364 | w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps 365 | union = w1 * h1 + w2 * h2 - inter + eps 366 | 367 | iou = inter / union 368 | 369 | if GIoU or DIoU or CIoU: 370 | cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex (smallest enclosing box) width 371 | ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height 372 | if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1 373 | c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared 374 | rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + 375 | (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center distance squared 376 | if DIoU: 377 | return iou - rho2 / c2 # DIoU 378 | elif CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47 379 | v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / (h2 + eps)) - torch.atan(w1 / (h1 + eps)), 2) 380 | with torch.no_grad(): 381 | alpha = v / (v - iou + (1 + eps)) 382 | return iou - (rho2 / c2 + v * alpha) # CIoU 383 | else: # GIoU https://arxiv.org/pdf/1902.09630.pdf 384 | c_area = cw * ch + eps # convex area 385 | return iou - (c_area - union) / c_area # GIoU 386 | else: 387 | return iou # IoU 388 | 389 | 390 | 391 | 392 | def bbox_alpha_iou(box1, box2, x1y1x2y2=False, GIoU=False, DIoU=False, CIoU=False, alpha=2, eps=1e-9): 393 | # Returns tsqrt_he IoU of box1 to box2. box1 is 4, box2 is nx4 394 | box2 = box2.T 395 | 396 | # Get the coordinates of bounding boxes 397 | if x1y1x2y2: # x1, y1, x2, y2 = box1 398 | b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3] 399 | b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3] 400 | else: # transform from xywh to xyxy 401 | b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2 402 | b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2 403 | b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2 404 | b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2 405 | 406 | # Intersection area 407 | inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \ 408 | (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0) 409 | 410 | # Union Area 411 | w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps 412 | w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps 413 | union = w1 * h1 + w2 * h2 - inter + eps 414 | 415 | # change iou into pow(iou+eps) 416 | # iou = inter / union 417 | iou = torch.pow(inter/union + eps, alpha) 418 | # beta = 2 * alpha 419 | if GIoU or DIoU or CIoU: 420 | cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex (smallest enclosing box) width 421 | ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height 422 | if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1 423 | c2 = (cw ** 2 + ch ** 2) ** alpha + eps # convex diagonal 424 | rho_x = torch.abs(b2_x1 + b2_x2 - b1_x1 - b1_x2) 425 | rho_y = torch.abs(b2_y1 + b2_y2 - b1_y1 - b1_y2) 426 | rho2 = ((rho_x ** 2 + rho_y ** 2) / 4) ** alpha # center distance 427 | if DIoU: 428 | return iou - rho2 / c2 # DIoU 429 | elif CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47 430 | v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2) 431 | with torch.no_grad(): 432 | alpha_ciou = v / ((1 + eps) - inter / union + v) 433 | # return iou - (rho2 / c2 + v * alpha_ciou) # CIoU 434 | return iou - (rho2 / c2 + torch.pow(v * alpha_ciou + eps, alpha)) # CIoU 435 | else: # GIoU https://arxiv.org/pdf/1902.09630.pdf 436 | # c_area = cw * ch + eps # convex area 437 | # return iou - (c_area - union) / c_area # GIoU 438 | c_area = torch.max(cw * ch + eps, union) # convex area 439 | return iou - torch.pow((c_area - union) / c_area + eps, alpha) # GIoU 440 | else: 441 | return iou # torch.log(iou+eps) or iou 442 | 443 | 444 | def box_iou(box1, box2): 445 | # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py 446 | """ 447 | Return intersection-over-union (Jaccard index) of boxes. 448 | Both sets of boxes are expected to be in (x1, y1, x2, y2) format. 449 | Arguments: 450 | box1 (Tensor[N, 4]) 451 | box2 (Tensor[M, 4]) 452 | Returns: 453 | iou (Tensor[N, M]): the NxM matrix containing the pairwise 454 | IoU values for every element in boxes1 and boxes2 455 | """ 456 | 457 | def box_area(box): 458 | # box = 4xn 459 | return (box[2] - box[0]) * (box[3] - box[1]) 460 | 461 | area1 = box_area(box1.T) 462 | area2 = box_area(box2.T) 463 | 464 | # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2) 465 | inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2) 466 | return inter / (area1[:, None] + area2 - inter) # iou = inter / (area1 + area2 - inter) 467 | 468 | 469 | def wh_iou(wh1, wh2): 470 | # Returns the nxm IoU matrix. wh1 is nx2, wh2 is mx2 471 | wh1 = wh1[:, None] # [N,1,2] 472 | wh2 = wh2[None] # [1,M,2] 473 | inter = torch.min(wh1, wh2).prod(2) # [N,M] 474 | return inter / (wh1.prod(2) + wh2.prod(2) - inter) # iou = inter / (area1 + area2 - inter) 475 | 476 | 477 | def box_giou(box1, box2): 478 | """ 479 | Return generalized intersection-over-union (Jaccard index) between two sets of boxes. 480 | Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with 481 | ``0 <= x1 < x2`` and ``0 <= y1 < y2``. 482 | Args: 483 | boxes1 (Tensor[N, 4]): first set of boxes 484 | boxes2 (Tensor[M, 4]): second set of boxes 485 | Returns: 486 | Tensor[N, M]: the NxM matrix containing the pairwise generalized IoU values 487 | for every element in boxes1 and boxes2 488 | """ 489 | 490 | def box_area(box): 491 | # box = 4xn 492 | return (box[2] - box[0]) * (box[3] - box[1]) 493 | 494 | area1 = box_area(box1.T) 495 | area2 = box_area(box2.T) 496 | 497 | inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2) 498 | union = (area1[:, None] + area2 - inter) 499 | 500 | iou = inter / union 501 | 502 | lti = torch.min(box1[:, None, :2], box2[:, :2]) 503 | rbi = torch.max(box1[:, None, 2:], box2[:, 2:]) 504 | 505 | whi = (rbi - lti).clamp(min=0) # [N,M,2] 506 | areai = whi[:, :, 0] * whi[:, :, 1] 507 | 508 | return iou - (areai - union) / areai 509 | 510 | 511 | def box_ciou(box1, box2, eps: float = 1e-7): 512 | """ 513 | Return complete intersection-over-union (Jaccard index) between two sets of boxes. 514 | Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with 515 | ``0 <= x1 < x2`` and ``0 <= y1 < y2``. 516 | Args: 517 | boxes1 (Tensor[N, 4]): first set of boxes 518 | boxes2 (Tensor[M, 4]): second set of boxes 519 | eps (float, optional): small number to prevent division by zero. Default: 1e-7 520 | Returns: 521 | Tensor[N, M]: the NxM matrix containing the pairwise complete IoU values 522 | for every element in boxes1 and boxes2 523 | """ 524 | 525 | def box_area(box): 526 | # box = 4xn 527 | return (box[2] - box[0]) * (box[3] - box[1]) 528 | 529 | area1 = box_area(box1.T) 530 | area2 = box_area(box2.T) 531 | 532 | inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2) 533 | union = (area1[:, None] + area2 - inter) 534 | 535 | iou = inter / union 536 | 537 | lti = torch.min(box1[:, None, :2], box2[:, :2]) 538 | rbi = torch.max(box1[:, None, 2:], box2[:, 2:]) 539 | 540 | whi = (rbi - lti).clamp(min=0) # [N,M,2] 541 | diagonal_distance_squared = (whi[:, :, 0] ** 2) + (whi[:, :, 1] ** 2) + eps 542 | 543 | # centers of boxes 544 | x_p = (box1[:, None, 0] + box1[:, None, 2]) / 2 545 | y_p = (box1[:, None, 1] + box1[:, None, 3]) / 2 546 | x_g = (box2[:, 0] + box2[:, 2]) / 2 547 | y_g = (box2[:, 1] + box2[:, 3]) / 2 548 | # The distance between boxes' centers squared. 549 | centers_distance_squared = (x_p - x_g) ** 2 + (y_p - y_g) ** 2 550 | 551 | w_pred = box1[:, None, 2] - box1[:, None, 0] 552 | h_pred = box1[:, None, 3] - box1[:, None, 1] 553 | 554 | w_gt = box2[:, 2] - box2[:, 0] 555 | h_gt = box2[:, 3] - box2[:, 1] 556 | 557 | v = (4 / (torch.pi ** 2)) * torch.pow((torch.atan(w_gt / h_gt) - torch.atan(w_pred / h_pred)), 2) 558 | with torch.no_grad(): 559 | alpha = v / (1 - iou + v + eps) 560 | return iou - (centers_distance_squared / diagonal_distance_squared) - alpha * v 561 | 562 | 563 | def box_diou(box1, box2, eps: float = 1e-7): 564 | """ 565 | Return distance intersection-over-union (Jaccard index) between two sets of boxes. 566 | Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with 567 | ``0 <= x1 < x2`` and ``0 <= y1 < y2``. 568 | Args: 569 | boxes1 (Tensor[N, 4]): first set of boxes 570 | boxes2 (Tensor[M, 4]): second set of boxes 571 | eps (float, optional): small number to prevent division by zero. Default: 1e-7 572 | Returns: 573 | Tensor[N, M]: the NxM matrix containing the pairwise distance IoU values 574 | for every element in boxes1 and boxes2 575 | """ 576 | 577 | def box_area(box): 578 | # box = 4xn 579 | return (box[2] - box[0]) * (box[3] - box[1]) 580 | 581 | area1 = box_area(box1.T) 582 | area2 = box_area(box2.T) 583 | 584 | inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2) 585 | union = (area1[:, None] + area2 - inter) 586 | 587 | iou = inter / union 588 | 589 | lti = torch.min(box1[:, None, :2], box2[:, :2]) 590 | rbi = torch.max(box1[:, None, 2:], box2[:, 2:]) 591 | 592 | whi = (rbi - lti).clamp(min=0) # [N,M,2] 593 | diagonal_distance_squared = (whi[:, :, 0] ** 2) + (whi[:, :, 1] ** 2) + eps 594 | 595 | # centers of boxes 596 | x_p = (box1[:, None, 0] + box1[:, None, 2]) / 2 597 | y_p = (box1[:, None, 1] + box1[:, None, 3]) / 2 598 | x_g = (box2[:, 0] + box2[:, 2]) / 2 599 | y_g = (box2[:, 1] + box2[:, 3]) / 2 600 | # The distance between boxes' centers squared. 601 | centers_distance_squared = (x_p - x_g) ** 2 + (y_p - y_g) ** 2 602 | 603 | # The distance IoU is the IoU penalized by a normalized 604 | # distance between boxes' centers squared. 605 | return iou - (centers_distance_squared / diagonal_distance_squared) 606 | 607 | 608 | def non_max_suppression(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, multi_label=False, 609 | labels=()): 610 | """Runs Non-Maximum Suppression (NMS) on inference results 611 | 612 | Returns: 613 | list of detections, on (n,6) tensor per image [xyxy, conf, cls] 614 | """ 615 | 616 | nc = prediction.shape[2] - 5 # number of classes 617 | xc = prediction[..., 4] > conf_thres # candidates 618 | 619 | # Settings 620 | min_wh, max_wh = 2, 4096 # (pixels) minimum and maximum box width and height 621 | max_det = 300 # maximum number of detections per image 622 | max_nms = 30000 # maximum number of boxes into torchvision.ops.nms() 623 | time_limit = 10.0 # seconds to quit after 624 | redundant = True # require redundant detections 625 | multi_label &= nc > 1 # multiple labels per box (adds 0.5ms/img) 626 | merge = False # use merge-NMS 627 | 628 | t = time.time() 629 | output = [torch.zeros((0, 6), device=prediction.device)] * prediction.shape[0] 630 | for xi, x in enumerate(prediction): # image index, image inference 631 | # Apply constraints 632 | # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height 633 | x = x[xc[xi]] # confidence 634 | 635 | # Cat apriori labels if autolabelling 636 | if labels and len(labels[xi]): 637 | l = labels[xi] 638 | v = torch.zeros((len(l), nc + 5), device=x.device) 639 | v[:, :4] = l[:, 1:5] # box 640 | v[:, 4] = 1.0 # conf 641 | v[range(len(l)), l[:, 0].long() + 5] = 1.0 # cls 642 | x = torch.cat((x, v), 0) 643 | 644 | # If none remain process next image 645 | if not x.shape[0]: 646 | continue 647 | 648 | # Compute conf 649 | if nc == 1: 650 | x[:, 5:] = x[:, 4:5] # for models with one class, cls_loss is 0 and cls_conf is always 0.5, 651 | # so there is no need to multiplicate. 652 | else: 653 | x[:, 5:] *= x[:, 4:5] # conf = obj_conf * cls_conf 654 | 655 | # Box (center x, center y, width, height) to (x1, y1, x2, y2) 656 | box = xywh2xyxy(x[:, :4]) 657 | 658 | # Detections matrix nx6 (xyxy, conf, cls) 659 | if multi_label: 660 | i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T 661 | x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1) 662 | else: # best class only 663 | conf, j = x[:, 5:].max(1, keepdim=True) 664 | x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres] 665 | 666 | # Filter by class 667 | if classes is not None: 668 | x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)] 669 | 670 | # Apply finite constraint 671 | # if not torch.isfinite(x).all(): 672 | # x = x[torch.isfinite(x).all(1)] 673 | 674 | # Check shape 675 | n = x.shape[0] # number of boxes 676 | if not n: # no boxes 677 | continue 678 | elif n > max_nms: # excess boxes 679 | x = x[x[:, 4].argsort(descending=True)[:max_nms]] # sort by confidence 680 | 681 | # Batched NMS 682 | c = x[:, 5:6] * (0 if agnostic else max_wh) # classes 683 | boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores 684 | i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS 685 | if i.shape[0] > max_det: # limit detections 686 | i = i[:max_det] 687 | if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean) 688 | # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4) 689 | iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix 690 | weights = iou * scores[None] # box weights 691 | x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes 692 | if redundant: 693 | i = i[iou.sum(1) > 1] # require redundancy 694 | 695 | output[xi] = x[i] 696 | if (time.time() - t) > time_limit: 697 | print(f'WARNING: NMS time limit {time_limit}s exceeded') 698 | break # time limit exceeded 699 | 700 | return output 701 | 702 | 703 | def non_max_suppression_kpt(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, multi_label=False, 704 | labels=(), kpt_label=False, nc=None, nkpt=None): 705 | """Runs Non-Maximum Suppression (NMS) on inference results 706 | 707 | Returns: 708 | list of detections, on (n,6) tensor per image [xyxy, conf, cls] 709 | """ 710 | if nc is None: 711 | nc = prediction.shape[2] - 5 if not kpt_label else prediction.shape[2] - 56 # number of classes 712 | xc = prediction[..., 4] > conf_thres # candidates 713 | 714 | # Settings 715 | min_wh, max_wh = 2, 4096 # (pixels) minimum and maximum box width and height 716 | max_det = 300 # maximum number of detections per image 717 | max_nms = 30000 # maximum number of boxes into torchvision.ops.nms() 718 | time_limit = 10.0 # seconds to quit after 719 | redundant = True # require redundant detections 720 | multi_label &= nc > 1 # multiple labels per box (adds 0.5ms/img) 721 | merge = False # use merge-NMS 722 | 723 | t = time.time() 724 | output = [torch.zeros((0,6), device=prediction.device)] * prediction.shape[0] 725 | for xi, x in enumerate(prediction): # image index, image inference 726 | # Apply constraints 727 | # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height 728 | x = x[xc[xi]] # confidence 729 | 730 | # Cat apriori labels if autolabelling 731 | if labels and len(labels[xi]): 732 | l = labels[xi] 733 | v = torch.zeros((len(l), nc + 5), device=x.device) 734 | v[:, :4] = l[:, 1:5] # box 735 | v[:, 4] = 1.0 # conf 736 | v[range(len(l)), l[:, 0].long() + 5] = 1.0 # cls 737 | x = torch.cat((x, v), 0) 738 | 739 | # If none remain process next image 740 | if not x.shape[0]: 741 | continue 742 | 743 | # Compute conf 744 | x[:, 5:5+nc] *= x[:, 4:5] # conf = obj_conf * cls_conf 745 | 746 | # Box (center x, center y, width, height) to (x1, y1, x2, y2) 747 | box = xywh2xyxy(x[:, :4]) 748 | 749 | # Detections matrix nx6 (xyxy, conf, cls) 750 | if multi_label: 751 | i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T 752 | x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1) 753 | else: # best class only 754 | if not kpt_label: 755 | conf, j = x[:, 5:].max(1, keepdim=True) 756 | x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres] 757 | else: 758 | kpts = x[:, 6:] 759 | conf, j = x[:, 5:6].max(1, keepdim=True) 760 | x = torch.cat((box, conf, j.float(), kpts), 1)[conf.view(-1) > conf_thres] 761 | 762 | 763 | # Filter by class 764 | if classes is not None: 765 | x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)] 766 | 767 | # Apply finite constraint 768 | # if not torch.isfinite(x).all(): 769 | # x = x[torch.isfinite(x).all(1)] 770 | 771 | # Check shape 772 | n = x.shape[0] # number of boxes 773 | if not n: # no boxes 774 | continue 775 | elif n > max_nms: # excess boxes 776 | x = x[x[:, 4].argsort(descending=True)[:max_nms]] # sort by confidence 777 | 778 | # Batched NMS 779 | c = x[:, 5:6] * (0 if agnostic else max_wh) # classes 780 | boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores 781 | i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS 782 | if i.shape[0] > max_det: # limit detections 783 | i = i[:max_det] 784 | if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean) 785 | # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4) 786 | iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix 787 | weights = iou * scores[None] # box weights 788 | x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes 789 | if redundant: 790 | i = i[iou.sum(1) > 1] # require redundancy 791 | 792 | output[xi] = x[i] 793 | if (time.time() - t) > time_limit: 794 | print(f'WARNING: NMS time limit {time_limit}s exceeded') 795 | break # time limit exceeded 796 | 797 | return output 798 | 799 | 800 | def strip_optimizer(f='best.pt', s=''): # from utils.general import *; strip_optimizer() 801 | # Strip optimizer from 'f' to finalize training, optionally save as 's' 802 | x = torch.load(f, map_location=torch.device('cpu')) 803 | if x.get('ema'): 804 | x['model'] = x['ema'] # replace model with ema 805 | for k in 'optimizer', 'training_results', 'wandb_id', 'ema', 'updates': # keys 806 | x[k] = None 807 | x['epoch'] = -1 808 | x['model'].half() # to FP16 809 | for p in x['model'].parameters(): 810 | p.requires_grad = False 811 | torch.save(x, s or f) 812 | mb = os.path.getsize(s or f) / 1E6 # filesize 813 | print(f"Optimizer stripped from {f},{(' saved as %s,' % s) if s else ''} {mb:.1f}MB") 814 | 815 | 816 | def print_mutation(hyp, results, yaml_file='hyp_evolved.yaml', bucket=''): 817 | # Print mutation results to evolve.txt (for use with train.py --evolve) 818 | a = '%10s' * len(hyp) % tuple(hyp.keys()) # hyperparam keys 819 | b = '%10.3g' * len(hyp) % tuple(hyp.values()) # hyperparam values 820 | c = '%10.4g' * len(results) % results # results (P, R, mAP@0.5, mAP@0.5:0.95, val_losses x 3) 821 | print('\n%s\n%s\nEvolved fitness: %s\n' % (a, b, c)) 822 | 823 | if bucket: 824 | url = 'gs://%s/evolve.txt' % bucket 825 | if gsutil_getsize(url) > (os.path.getsize('evolve.txt') if os.path.exists('evolve.txt') else 0): 826 | os.system('gsutil cp %s .' % url) # download evolve.txt if larger than local 827 | 828 | with open('evolve.txt', 'a') as f: # append result 829 | f.write(c + b + '\n') 830 | x = np.unique(np.loadtxt('evolve.txt', ndmin=2), axis=0) # load unique rows 831 | x = x[np.argsort(-fitness(x))] # sort 832 | np.savetxt('evolve.txt', x, '%10.3g') # save sort by fitness 833 | 834 | # Save yaml 835 | for i, k in enumerate(hyp.keys()): 836 | hyp[k] = float(x[0, i + 7]) 837 | with open(yaml_file, 'w') as f: 838 | results = tuple(x[0, :7]) 839 | c = '%10.4g' * len(results) % results # results (P, R, mAP@0.5, mAP@0.5:0.95, val_losses x 3) 840 | f.write('# Hyperparameter Evolution Results\n# Generations: %g\n# Metrics: ' % len(x) + c + '\n\n') 841 | yaml.dump(hyp, f, sort_keys=False) 842 | 843 | if bucket: 844 | os.system('gsutil cp evolve.txt %s gs://%s' % (yaml_file, bucket)) # upload 845 | 846 | 847 | def apply_classifier(x, model, img, im0): 848 | # applies a second stage classifier to yolo outputs 849 | im0 = [im0] if isinstance(im0, np.ndarray) else im0 850 | for i, d in enumerate(x): # per image 851 | if d is not None and len(d): 852 | d = d.clone() 853 | 854 | # Reshape and pad cutouts 855 | b = xyxy2xywh(d[:, :4]) # boxes 856 | b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # rectangle to square 857 | b[:, 2:] = b[:, 2:] * 1.3 + 30 # pad 858 | d[:, :4] = xywh2xyxy(b).long() 859 | 860 | # Rescale boxes from img_size to im0 size 861 | scale_coords(img.shape[2:], d[:, :4], im0[i].shape) 862 | 863 | # Classes 864 | pred_cls1 = d[:, 5].long() 865 | ims = [] 866 | for j, a in enumerate(d): # per item 867 | cutout = im0[i][int(a[1]):int(a[3]), int(a[0]):int(a[2])] 868 | im = cv2.resize(cutout, (224, 224)) # BGR 869 | # cv2.imwrite('test%i.jpg' % j, cutout) 870 | 871 | im = im[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416 872 | im = np.ascontiguousarray(im, dtype=np.float32) # uint8 to float32 873 | im /= 255.0 # 0 - 255 to 0.0 - 1.0 874 | ims.append(im) 875 | 876 | pred_cls2 = model(torch.Tensor(ims).to(d.device)).argmax(1) # classifier prediction 877 | x[i] = x[i][pred_cls1 == pred_cls2] # retain matching class detections 878 | 879 | return x 880 | 881 | 882 | def increment_path(path, exist_ok=True, sep=''): 883 | # Increment path, i.e. runs/exp --> runs/exp{sep}0, runs/exp{sep}1 etc. 884 | path = Path(path) # os-agnostic 885 | if (path.exists() and exist_ok) or (not path.exists()): 886 | return str(path) 887 | else: 888 | dirs = glob.glob(f"{path}{sep}*") # similar paths 889 | matches = [re.search(rf"%s{sep}(\d+)" % path.stem, d) for d in dirs] 890 | i = [int(m.groups()[0]) for m in matches if m] # indices 891 | n = max(i) + 1 if i else 2 # increment number 892 | return f"{path}{sep}{n}" # update path 893 | -------------------------------------------------------------------------------- /Yolov7/utils/google_utils.py: -------------------------------------------------------------------------------- 1 | # Google utils: https://cloud.google.com/storage/docs/reference/libraries 2 | 3 | import os 4 | import platform 5 | import subprocess 6 | import time 7 | from pathlib import Path 8 | 9 | import requests 10 | import torch 11 | 12 | 13 | def gsutil_getsize(url=''): 14 | # gs://bucket/file size https://cloud.google.com/storage/docs/gsutil/commands/du 15 | s = subprocess.check_output(f'gsutil du {url}', shell=True).decode('utf-8') 16 | return eval(s.split(' ')[0]) if len(s) else 0 # bytes 17 | 18 | 19 | def attempt_download(file, repo='WongKinYiu/yolov7'): 20 | # Attempt file download if does not exist 21 | file = Path(str(file).strip().replace("'", '').lower()) 22 | 23 | if not file.exists(): 24 | try: 25 | response = requests.get(f'https://api.github.com/repos/{repo}/releases/latest').json() # github api 26 | assets = [x['name'] for x in response['assets']] # release assets 27 | tag = response['tag_name'] # i.e. 'v1.0' 28 | except: # fallback plan 29 | assets = ['yolov7.pt', 'yolov7-tiny.pt', 'yolov7x.pt', 'yolov7-d6.pt', 'yolov7-e6.pt', 30 | 'yolov7-e6e.pt', 'yolov7-w6.pt'] 31 | tag = subprocess.check_output('git tag', shell=True).decode().split()[-1] 32 | 33 | name = file.name 34 | if name in assets: 35 | msg = f'{file} missing, try downloading from https://github.com/{repo}/releases/' 36 | redundant = False # second download option 37 | try: # GitHub 38 | url = f'https://github.com/{repo}/releases/download/{tag}/{name}' 39 | print(f'Downloading {url} to {file}...') 40 | torch.hub.download_url_to_file(url, file) 41 | assert file.exists() and file.stat().st_size > 1E6 # check 42 | except Exception as e: # GCP 43 | print(f'Download error: {e}') 44 | assert redundant, 'No secondary mirror' 45 | url = f'https://storage.googleapis.com/{repo}/ckpt/{name}' 46 | print(f'Downloading {url} to {file}...') 47 | os.system(f'curl -L {url} -o {file}') # torch.hub.download_url_to_file(url, weights) 48 | finally: 49 | if not file.exists() or file.stat().st_size < 1E6: # check 50 | file.unlink(missing_ok=True) # remove partial downloads 51 | print(f'ERROR: Download failure: {msg}') 52 | print('') 53 | return 54 | 55 | 56 | def gdrive_download(id='', file='tmp.zip'): 57 | # Downloads a file from Google Drive. from yolov7.utils.google_utils import *; gdrive_download() 58 | t = time.time() 59 | file = Path(file) 60 | cookie = Path('cookie') # gdrive cookie 61 | print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='') 62 | file.unlink(missing_ok=True) # remove existing file 63 | cookie.unlink(missing_ok=True) # remove existing cookie 64 | 65 | # Attempt file download 66 | out = "NUL" if platform.system() == "Windows" else "/dev/null" 67 | os.system(f'curl -c ./cookie -s -L "drive.google.com/uc?export=download&id={id}" > {out}') 68 | if os.path.exists('cookie'): # large file 69 | s = f'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm={get_token()}&id={id}" -o {file}' 70 | else: # small file 71 | s = f'curl -s -L -o {file} "drive.google.com/uc?export=download&id={id}"' 72 | r = os.system(s) # execute, capture return 73 | cookie.unlink(missing_ok=True) # remove existing cookie 74 | 75 | # Error check 76 | if r != 0: 77 | file.unlink(missing_ok=True) # remove partial 78 | print('Download error ') # raise Exception('Download error') 79 | return r 80 | 81 | # Unzip if archive 82 | if file.suffix == '.zip': 83 | print('unzipping... ', end='') 84 | os.system(f'unzip -q {file}') # unzip 85 | file.unlink() # remove zip to free space 86 | 87 | print(f'Done ({time.time() - t:.1f}s)') 88 | return r 89 | 90 | 91 | def get_token(cookie="./cookie"): 92 | with open(cookie) as f: 93 | for line in f: 94 | if "download" in line: 95 | return line.split()[-1] 96 | return "" 97 | 98 | # def upload_blob(bucket_name, source_file_name, destination_blob_name): 99 | # # Uploads a file to a bucket 100 | # # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python 101 | # 102 | # storage_client = storage.Client() 103 | # bucket = storage_client.get_bucket(bucket_name) 104 | # blob = bucket.blob(destination_blob_name) 105 | # 106 | # blob.upload_from_filename(source_file_name) 107 | # 108 | # print('File {} uploaded to {}.'.format( 109 | # source_file_name, 110 | # destination_blob_name)) 111 | # 112 | # 113 | # def download_blob(bucket_name, source_blob_name, destination_file_name): 114 | # # Uploads a blob from a bucket 115 | # storage_client = storage.Client() 116 | # bucket = storage_client.get_bucket(bucket_name) 117 | # blob = bucket.blob(source_blob_name) 118 | # 119 | # blob.download_to_filename(destination_file_name) 120 | # 121 | # print('Blob {} downloaded to {}.'.format( 122 | # source_blob_name, 123 | # destination_file_name)) 124 | -------------------------------------------------------------------------------- /Yolov7/utils/metrics.py: -------------------------------------------------------------------------------- 1 | # Model validation metrics 2 | 3 | from pathlib import Path 4 | 5 | import matplotlib.pyplot as plt 6 | import numpy as np 7 | import torch 8 | 9 | from . import general 10 | 11 | 12 | def fitness(x): 13 | # Model fitness as a weighted combination of metrics 14 | w = [0.0, 0.0, 0.1, 0.9] # weights for [P, R, mAP@0.5, mAP@0.5:0.95] 15 | return (x[:, :4] * w).sum(1) 16 | 17 | 18 | def ap_per_class(tp, conf, pred_cls, target_cls, v5_metric=False, plot=False, save_dir='.', names=()): 19 | """ Compute the average precision, given the recall and precision curves. 20 | Source: https://github.com/rafaelpadilla/Object-Detection-Metrics. 21 | # Arguments 22 | tp: True positives (nparray, nx1 or nx10). 23 | conf: Objectness value from 0-1 (nparray). 24 | pred_cls: Predicted object classes (nparray). 25 | target_cls: True object classes (nparray). 26 | plot: Plot precision-recall curve at mAP@0.5 27 | save_dir: Plot save directory 28 | # Returns 29 | The average precision as computed in py-faster-rcnn. 30 | """ 31 | 32 | # Sort by objectness 33 | i = np.argsort(-conf) 34 | tp, conf, pred_cls = tp[i], conf[i], pred_cls[i] 35 | 36 | # Find unique classes 37 | unique_classes = np.unique(target_cls) 38 | nc = unique_classes.shape[0] # number of classes, number of detections 39 | 40 | # Create Precision-Recall curve and compute AP for each class 41 | px, py = np.linspace(0, 1, 1000), [] # for plotting 42 | ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000)) 43 | for ci, c in enumerate(unique_classes): 44 | i = pred_cls == c 45 | n_l = (target_cls == c).sum() # number of labels 46 | n_p = i.sum() # number of predictions 47 | 48 | if n_p == 0 or n_l == 0: 49 | continue 50 | else: 51 | # Accumulate FPs and TPs 52 | fpc = (1 - tp[i]).cumsum(0) 53 | tpc = tp[i].cumsum(0) 54 | 55 | # Recall 56 | recall = tpc / (n_l + 1e-16) # recall curve 57 | r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases 58 | 59 | # Precision 60 | precision = tpc / (tpc + fpc) # precision curve 61 | p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1) # p at pr_score 62 | 63 | # AP from recall-precision curve 64 | for j in range(tp.shape[1]): 65 | ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j], v5_metric=v5_metric) 66 | if plot and j == 0: 67 | py.append(np.interp(px, mrec, mpre)) # precision at mAP@0.5 68 | 69 | # Compute F1 (harmonic mean of precision and recall) 70 | f1 = 2 * p * r / (p + r + 1e-16) 71 | if plot: 72 | plot_pr_curve(px, py, ap, Path(save_dir) / 'PR_curve.png', names) 73 | plot_mc_curve(px, f1, Path(save_dir) / 'F1_curve.png', names, ylabel='F1') 74 | plot_mc_curve(px, p, Path(save_dir) / 'P_curve.png', names, ylabel='Precision') 75 | plot_mc_curve(px, r, Path(save_dir) / 'R_curve.png', names, ylabel='Recall') 76 | 77 | i = f1.mean(0).argmax() # max F1 index 78 | return p[:, i], r[:, i], ap, f1[:, i], unique_classes.astype('int32') 79 | 80 | 81 | def compute_ap(recall, precision, v5_metric=False): 82 | """ Compute the average precision, given the recall and precision curves 83 | # Arguments 84 | recall: The recall curve (list) 85 | precision: The precision curve (list) 86 | v5_metric: Assume maximum recall to be 1.0, as in YOLOv5, MMDetetion etc. 87 | # Returns 88 | Average precision, precision curve, recall curve 89 | """ 90 | 91 | # Append sentinel values to beginning and end 92 | if v5_metric: # New YOLOv5 metric, same as MMDetection and Detectron2 repositories 93 | mrec = np.concatenate(([0.], recall, [1.0])) 94 | else: # Old YOLOv5 metric, i.e. default YOLOv7 metric 95 | mrec = np.concatenate(([0.], recall, [recall[-1] + 0.01])) 96 | mpre = np.concatenate(([1.], precision, [0.])) 97 | 98 | # Compute the precision envelope 99 | mpre = np.flip(np.maximum.accumulate(np.flip(mpre))) 100 | 101 | # Integrate area under curve 102 | method = 'interp' # methods: 'continuous', 'interp' 103 | if method == 'interp': 104 | x = np.linspace(0, 1, 101) # 101-point interp (COCO) 105 | ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate 106 | else: # 'continuous' 107 | i = np.where(mrec[1:] != mrec[:-1])[0] # points where x axis (recall) changes 108 | ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve 109 | 110 | return ap, mpre, mrec 111 | 112 | 113 | class ConfusionMatrix: 114 | # Updated version of https://github.com/kaanakan/object_detection_confusion_matrix 115 | def __init__(self, nc, conf=0.25, iou_thres=0.45): 116 | self.matrix = np.zeros((nc + 1, nc + 1)) 117 | self.nc = nc # number of classes 118 | self.conf = conf 119 | self.iou_thres = iou_thres 120 | 121 | def process_batch(self, detections, labels): 122 | """ 123 | Return intersection-over-union (Jaccard index) of boxes. 124 | Both sets of boxes are expected to be in (x1, y1, x2, y2) format. 125 | Arguments: 126 | detections (Array[N, 6]), x1, y1, x2, y2, conf, class 127 | labels (Array[M, 5]), class, x1, y1, x2, y2 128 | Returns: 129 | None, updates confusion matrix accordingly 130 | """ 131 | detections = detections[detections[:, 4] > self.conf] 132 | gt_classes = labels[:, 0].int() 133 | detection_classes = detections[:, 5].int() 134 | iou = general.box_iou(labels[:, 1:], detections[:, :4]) 135 | 136 | x = torch.where(iou > self.iou_thres) 137 | if x[0].shape[0]: 138 | matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy() 139 | if x[0].shape[0] > 1: 140 | matches = matches[matches[:, 2].argsort()[::-1]] 141 | matches = matches[np.unique(matches[:, 1], return_index=True)[1]] 142 | matches = matches[matches[:, 2].argsort()[::-1]] 143 | matches = matches[np.unique(matches[:, 0], return_index=True)[1]] 144 | else: 145 | matches = np.zeros((0, 3)) 146 | 147 | n = matches.shape[0] > 0 148 | m0, m1, _ = matches.transpose().astype(np.int16) 149 | for i, gc in enumerate(gt_classes): 150 | j = m0 == i 151 | if n and sum(j) == 1: 152 | self.matrix[gc, detection_classes[m1[j]]] += 1 # correct 153 | else: 154 | self.matrix[self.nc, gc] += 1 # background FP 155 | 156 | if n: 157 | for i, dc in enumerate(detection_classes): 158 | if not any(m1 == i): 159 | self.matrix[dc, self.nc] += 1 # background FN 160 | 161 | def matrix(self): 162 | return self.matrix 163 | 164 | def plot(self, save_dir='', names=()): 165 | try: 166 | import seaborn as sn 167 | 168 | array = self.matrix / (self.matrix.sum(0).reshape(1, self.nc + 1) + 1E-6) # normalize 169 | array[array < 0.005] = np.nan # don't annotate (would appear as 0.00) 170 | 171 | fig = plt.figure(figsize=(12, 9), tight_layout=True) 172 | sn.set(font_scale=1.0 if self.nc < 50 else 0.8) # for label size 173 | labels = (0 < len(names) < 99) and len(names) == self.nc # apply names to ticklabels 174 | sn.heatmap(array, annot=self.nc < 30, annot_kws={"size": 8}, cmap='Blues', fmt='.2f', square=True, 175 | xticklabels=names + ['background FP'] if labels else "auto", 176 | yticklabels=names + ['background FN'] if labels else "auto").set_facecolor((1, 1, 1)) 177 | fig.axes[0].set_xlabel('True') 178 | fig.axes[0].set_ylabel('Predicted') 179 | fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250) 180 | except Exception as e: 181 | pass 182 | 183 | def print(self): 184 | for i in range(self.nc + 1): 185 | print(' '.join(map(str, self.matrix[i]))) 186 | 187 | 188 | # Plots ---------------------------------------------------------------------------------------------------------------- 189 | 190 | def plot_pr_curve(px, py, ap, save_dir='pr_curve.png', names=()): 191 | # Precision-recall curve 192 | fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True) 193 | py = np.stack(py, axis=1) 194 | 195 | if 0 < len(names) < 21: # display per-class legend if < 21 classes 196 | for i, y in enumerate(py.T): 197 | ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}') # plot(recall, precision) 198 | else: 199 | ax.plot(px, py, linewidth=1, color='grey') # plot(recall, precision) 200 | 201 | ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f mAP@0.5' % ap[:, 0].mean()) 202 | ax.set_xlabel('Recall') 203 | ax.set_ylabel('Precision') 204 | ax.set_xlim(0, 1) 205 | ax.set_ylim(0, 1) 206 | plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left") 207 | fig.savefig(Path(save_dir), dpi=250) 208 | 209 | 210 | def plot_mc_curve(px, py, save_dir='mc_curve.png', names=(), xlabel='Confidence', ylabel='Metric'): 211 | # Metric-confidence curve 212 | fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True) 213 | 214 | if 0 < len(names) < 21: # display per-class legend if < 21 classes 215 | for i, y in enumerate(py): 216 | ax.plot(px, y, linewidth=1, label=f'{names[i]}') # plot(confidence, metric) 217 | else: 218 | ax.plot(px, py.T, linewidth=1, color='grey') # plot(confidence, metric) 219 | 220 | y = py.mean(0) 221 | ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}') 222 | ax.set_xlabel(xlabel) 223 | ax.set_ylabel(ylabel) 224 | ax.set_xlim(0, 1) 225 | ax.set_ylim(0, 1) 226 | plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left") 227 | fig.savefig(Path(save_dir), dpi=250) 228 | -------------------------------------------------------------------------------- /Yolov7/utils/plots.py: -------------------------------------------------------------------------------- 1 | # Plotting utils 2 | 3 | import glob 4 | import math 5 | import os 6 | import random 7 | from copy import copy 8 | from pathlib import Path 9 | 10 | import cv2 11 | import matplotlib 12 | import matplotlib.pyplot as plt 13 | import numpy as np 14 | import pandas as pd 15 | import seaborn as sns 16 | import torch 17 | import yaml 18 | from PIL import Image, ImageDraw, ImageFont 19 | from scipy.signal import butter, filtfilt 20 | 21 | from utils.general import xywh2xyxy, xyxy2xywh 22 | from utils.metrics import fitness 23 | 24 | # Settings 25 | matplotlib.rc('font', **{'size': 11}) 26 | matplotlib.use('Agg') # for writing to files only 27 | 28 | 29 | def color_list(): 30 | # Return first 10 plt colors as (r,g,b) https://stackoverflow.com/questions/51350872/python-from-color-name-to-rgb 31 | def hex2rgb(h): 32 | return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4)) 33 | 34 | return [hex2rgb(h) for h in matplotlib.colors.TABLEAU_COLORS.values()] # or BASE_ (8), CSS4_ (148), XKCD_ (949) 35 | 36 | 37 | def hist2d(x, y, n=100): 38 | # 2d histogram used in labels.png and evolve.png 39 | xedges, yedges = np.linspace(x.min(), x.max(), n), np.linspace(y.min(), y.max(), n) 40 | hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges)) 41 | xidx = np.clip(np.digitize(x, xedges) - 1, 0, hist.shape[0] - 1) 42 | yidx = np.clip(np.digitize(y, yedges) - 1, 0, hist.shape[1] - 1) 43 | return np.log(hist[xidx, yidx]) 44 | 45 | 46 | def butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5): 47 | # https://stackoverflow.com/questions/28536191/how-to-filter-smooth-with-scipy-numpy 48 | def butter_lowpass(cutoff, fs, order): 49 | nyq = 0.5 * fs 50 | normal_cutoff = cutoff / nyq 51 | return butter(order, normal_cutoff, btype='low', analog=False) 52 | 53 | b, a = butter_lowpass(cutoff, fs, order=order) 54 | return filtfilt(b, a, data) # forward-backward filter 55 | 56 | 57 | def plot_one_box(x, img, color=None, label=None, line_thickness=3): 58 | # Plots one bounding box on image img 59 | tl = line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1 # line/font thickness 60 | color = color or [random.randint(0, 255) for _ in range(3)] 61 | c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3])) 62 | cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA) 63 | if label: 64 | tf = max(tl - 1, 1) # font thickness 65 | t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0] 66 | c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3 67 | cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA) # filled 68 | cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA) 69 | 70 | 71 | def plot_one_box_PIL(box, img, color=None, label=None, line_thickness=None): 72 | img = Image.fromarray(img) 73 | draw = ImageDraw.Draw(img) 74 | line_thickness = line_thickness or max(int(min(img.size) / 200), 2) 75 | draw.rectangle(box, width=line_thickness, outline=tuple(color)) # plot 76 | if label: 77 | fontsize = max(round(max(img.size) / 40), 12) 78 | font = ImageFont.truetype("Arial.ttf", fontsize) 79 | txt_width, txt_height = font.getsize(label) 80 | draw.rectangle([box[0], box[1] - txt_height + 4, box[0] + txt_width, box[1]], fill=tuple(color)) 81 | draw.text((box[0], box[1] - txt_height + 1), label, fill=(255, 255, 255), font=font) 82 | return np.asarray(img) 83 | 84 | 85 | def plot_wh_methods(): # from utils.plots import *; plot_wh_methods() 86 | # Compares the two methods for width-height anchor multiplication 87 | # https://github.com/ultralytics/yolov3/issues/168 88 | x = np.arange(-4.0, 4.0, .1) 89 | ya = np.exp(x) 90 | yb = torch.sigmoid(torch.from_numpy(x)).numpy() * 2 91 | 92 | fig = plt.figure(figsize=(6, 3), tight_layout=True) 93 | plt.plot(x, ya, '.-', label='YOLOv3') 94 | plt.plot(x, yb ** 2, '.-', label='YOLOR ^2') 95 | plt.plot(x, yb ** 1.6, '.-', label='YOLOR ^1.6') 96 | plt.xlim(left=-4, right=4) 97 | plt.ylim(bottom=0, top=6) 98 | plt.xlabel('input') 99 | plt.ylabel('output') 100 | plt.grid() 101 | plt.legend() 102 | fig.savefig('comparison.png', dpi=200) 103 | 104 | 105 | def output_to_target(output): 106 | # Convert model output to target format [batch_id, class_id, x, y, w, h, conf] 107 | targets = [] 108 | for i, o in enumerate(output): 109 | for *box, conf, cls in o.cpu().numpy(): 110 | targets.append([i, cls, *list(*xyxy2xywh(np.array(box)[None])), conf]) 111 | return np.array(targets) 112 | 113 | 114 | def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=640, max_subplots=16): 115 | # Plot image grid with labels 116 | 117 | if isinstance(images, torch.Tensor): 118 | images = images.cpu().float().numpy() 119 | if isinstance(targets, torch.Tensor): 120 | targets = targets.cpu().numpy() 121 | 122 | # un-normalise 123 | if np.max(images[0]) <= 1: 124 | images *= 255 125 | 126 | tl = 3 # line thickness 127 | tf = max(tl - 1, 1) # font thickness 128 | bs, _, h, w = images.shape # batch size, _, height, width 129 | bs = min(bs, max_subplots) # limit plot images 130 | ns = np.ceil(bs ** 0.5) # number of subplots (square) 131 | 132 | # Check if we should resize 133 | scale_factor = max_size / max(h, w) 134 | if scale_factor < 1: 135 | h = math.ceil(scale_factor * h) 136 | w = math.ceil(scale_factor * w) 137 | 138 | colors = color_list() # list of colors 139 | mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init 140 | for i, img in enumerate(images): 141 | if i == max_subplots: # if last batch has fewer images than we expect 142 | break 143 | 144 | block_x = int(w * (i // ns)) 145 | block_y = int(h * (i % ns)) 146 | 147 | img = img.transpose(1, 2, 0) 148 | if scale_factor < 1: 149 | img = cv2.resize(img, (w, h)) 150 | 151 | mosaic[block_y:block_y + h, block_x:block_x + w, :] = img 152 | if len(targets) > 0: 153 | image_targets = targets[targets[:, 0] == i] 154 | boxes = xywh2xyxy(image_targets[:, 2:6]).T 155 | classes = image_targets[:, 1].astype('int') 156 | labels = image_targets.shape[1] == 6 # labels if no conf column 157 | conf = None if labels else image_targets[:, 6] # check for confidence presence (label vs pred) 158 | 159 | if boxes.shape[1]: 160 | if boxes.max() <= 1.01: # if normalized with tolerance 0.01 161 | boxes[[0, 2]] *= w # scale to pixels 162 | boxes[[1, 3]] *= h 163 | elif scale_factor < 1: # absolute coords need scale if image scales 164 | boxes *= scale_factor 165 | boxes[[0, 2]] += block_x 166 | boxes[[1, 3]] += block_y 167 | for j, box in enumerate(boxes.T): 168 | cls = int(classes[j]) 169 | color = colors[cls % len(colors)] 170 | cls = names[cls] if names else cls 171 | if labels or conf[j] > 0.25: # 0.25 conf thresh 172 | label = '%s' % cls if labels else '%s %.1f' % (cls, conf[j]) 173 | plot_one_box(box, mosaic, label=label, color=color, line_thickness=tl) 174 | 175 | # Draw image filename labels 176 | if paths: 177 | label = Path(paths[i]).name[:40] # trim to 40 char 178 | t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0] 179 | cv2.putText(mosaic, label, (block_x + 5, block_y + t_size[1] + 5), 0, tl / 3, [220, 220, 220], thickness=tf, 180 | lineType=cv2.LINE_AA) 181 | 182 | # Image border 183 | cv2.rectangle(mosaic, (block_x, block_y), (block_x + w, block_y + h), (255, 255, 255), thickness=3) 184 | 185 | if fname: 186 | r = min(1280. / max(h, w) / ns, 1.0) # ratio to limit image size 187 | mosaic = cv2.resize(mosaic, (int(ns * w * r), int(ns * h * r)), interpolation=cv2.INTER_AREA) 188 | # cv2.imwrite(fname, cv2.cvtColor(mosaic, cv2.COLOR_BGR2RGB)) # cv2 save 189 | Image.fromarray(mosaic).save(fname) # PIL save 190 | return mosaic 191 | 192 | 193 | def plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=''): 194 | # Plot LR simulating training for full epochs 195 | optimizer, scheduler = copy(optimizer), copy(scheduler) # do not modify originals 196 | y = [] 197 | for _ in range(epochs): 198 | scheduler.step() 199 | y.append(optimizer.param_groups[0]['lr']) 200 | plt.plot(y, '.-', label='LR') 201 | plt.xlabel('epoch') 202 | plt.ylabel('LR') 203 | plt.grid() 204 | plt.xlim(0, epochs) 205 | plt.ylim(0) 206 | plt.savefig(Path(save_dir) / 'LR.png', dpi=200) 207 | plt.close() 208 | 209 | 210 | def plot_test_txt(): # from utils.plots import *; plot_test() 211 | # Plot test.txt histograms 212 | x = np.loadtxt('test.txt', dtype=np.float32) 213 | box = xyxy2xywh(x[:, :4]) 214 | cx, cy = box[:, 0], box[:, 1] 215 | 216 | fig, ax = plt.subplots(1, 1, figsize=(6, 6), tight_layout=True) 217 | ax.hist2d(cx, cy, bins=600, cmax=10, cmin=0) 218 | ax.set_aspect('equal') 219 | plt.savefig('hist2d.png', dpi=300) 220 | 221 | fig, ax = plt.subplots(1, 2, figsize=(12, 6), tight_layout=True) 222 | ax[0].hist(cx, bins=600) 223 | ax[1].hist(cy, bins=600) 224 | plt.savefig('hist1d.png', dpi=200) 225 | 226 | 227 | def plot_targets_txt(): # from utils.plots import *; plot_targets_txt() 228 | # Plot targets.txt histograms 229 | x = np.loadtxt('targets.txt', dtype=np.float32).T 230 | s = ['x targets', 'y targets', 'width targets', 'height targets'] 231 | fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True) 232 | ax = ax.ravel() 233 | for i in range(4): 234 | ax[i].hist(x[i], bins=100, label='%.3g +/- %.3g' % (x[i].mean(), x[i].std())) 235 | ax[i].legend() 236 | ax[i].set_title(s[i]) 237 | plt.savefig('targets.jpg', dpi=200) 238 | 239 | 240 | def plot_study_txt(path='', x=None): # from utils.plots import *; plot_study_txt() 241 | # Plot study.txt generated by test.py 242 | fig, ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True) 243 | # ax = ax.ravel() 244 | 245 | fig2, ax2 = plt.subplots(1, 1, figsize=(8, 4), tight_layout=True) 246 | # for f in [Path(path) / f'study_coco_{x}.txt' for x in ['yolor-p6', 'yolor-w6', 'yolor-e6', 'yolor-d6']]: 247 | for f in sorted(Path(path).glob('study*.txt')): 248 | y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T 249 | x = np.arange(y.shape[1]) if x is None else np.array(x) 250 | s = ['P', 'R', 'mAP@.5', 'mAP@.5:.95', 't_inference (ms/img)', 't_NMS (ms/img)', 't_total (ms/img)'] 251 | # for i in range(7): 252 | # ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8) 253 | # ax[i].set_title(s[i]) 254 | 255 | j = y[3].argmax() + 1 256 | ax2.plot(y[6, 1:j], y[3, 1:j] * 1E2, '.-', linewidth=2, markersize=8, 257 | label=f.stem.replace('study_coco_', '').replace('yolo', 'YOLO')) 258 | 259 | ax2.plot(1E3 / np.array([209, 140, 97, 58, 35, 18]), [34.6, 40.5, 43.0, 47.5, 49.7, 51.5], 260 | 'k.-', linewidth=2, markersize=8, alpha=.25, label='EfficientDet') 261 | 262 | ax2.grid(alpha=0.2) 263 | ax2.set_yticks(np.arange(20, 60, 5)) 264 | ax2.set_xlim(0, 57) 265 | ax2.set_ylim(30, 55) 266 | ax2.set_xlabel('GPU Speed (ms/img)') 267 | ax2.set_ylabel('COCO AP val') 268 | ax2.legend(loc='lower right') 269 | plt.savefig(str(Path(path).name) + '.png', dpi=300) 270 | 271 | 272 | def plot_labels(labels, names=(), save_dir=Path(''), loggers=None): 273 | # plot dataset labels 274 | print('Plotting labels... ') 275 | c, b = labels[:, 0], labels[:, 1:].transpose() # classes, boxes 276 | nc = int(c.max() + 1) # number of classes 277 | colors = color_list() 278 | x = pd.DataFrame(b.transpose(), columns=['x', 'y', 'width', 'height']) 279 | 280 | # seaborn correlogram 281 | sns.pairplot(x, corner=True, diag_kind='auto', kind='hist', diag_kws=dict(bins=50), plot_kws=dict(pmax=0.9)) 282 | plt.savefig(save_dir / 'labels_correlogram.jpg', dpi=200) 283 | plt.close() 284 | 285 | # matplotlib labels 286 | matplotlib.use('svg') # faster 287 | ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel() 288 | ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8) 289 | ax[0].set_ylabel('instances') 290 | if 0 < len(names) < 30: 291 | ax[0].set_xticks(range(len(names))) 292 | ax[0].set_xticklabels(names, rotation=90, fontsize=10) 293 | else: 294 | ax[0].set_xlabel('classes') 295 | sns.histplot(x, x='x', y='y', ax=ax[2], bins=50, pmax=0.9) 296 | sns.histplot(x, x='width', y='height', ax=ax[3], bins=50, pmax=0.9) 297 | 298 | # rectangles 299 | labels[:, 1:3] = 0.5 # center 300 | labels[:, 1:] = xywh2xyxy(labels[:, 1:]) * 2000 301 | img = Image.fromarray(np.ones((2000, 2000, 3), dtype=np.uint8) * 255) 302 | for cls, *box in labels[:1000]: 303 | ImageDraw.Draw(img).rectangle(box, width=1, outline=colors[int(cls) % 10]) # plot 304 | ax[1].imshow(img) 305 | ax[1].axis('off') 306 | 307 | for a in [0, 1, 2, 3]: 308 | for s in ['top', 'right', 'left', 'bottom']: 309 | ax[a].spines[s].set_visible(False) 310 | 311 | plt.savefig(save_dir / 'labels.jpg', dpi=200) 312 | matplotlib.use('Agg') 313 | plt.close() 314 | 315 | # loggers 316 | for k, v in loggers.items() or {}: 317 | if k == 'wandb' and v: 318 | v.log({"Labels": [v.Image(str(x), caption=x.name) for x in save_dir.glob('*labels*.jpg')]}, commit=False) 319 | 320 | 321 | def plot_evolution(yaml_file='data/hyp.finetune.yaml'): # from utils.plots import *; plot_evolution() 322 | # Plot hyperparameter evolution results in evolve.txt 323 | with open(yaml_file) as f: 324 | hyp = yaml.load(f, Loader=yaml.SafeLoader) 325 | x = np.loadtxt('evolve.txt', ndmin=2) 326 | f = fitness(x) 327 | # weights = (f - f.min()) ** 2 # for weighted results 328 | plt.figure(figsize=(10, 12), tight_layout=True) 329 | matplotlib.rc('font', **{'size': 8}) 330 | for i, (k, v) in enumerate(hyp.items()): 331 | y = x[:, i + 7] 332 | # mu = (y * weights).sum() / weights.sum() # best weighted result 333 | mu = y[f.argmax()] # best single result 334 | plt.subplot(6, 5, i + 1) 335 | plt.scatter(y, f, c=hist2d(y, f, 20), cmap='viridis', alpha=.8, edgecolors='none') 336 | plt.plot(mu, f.max(), 'k+', markersize=15) 337 | plt.title('%s = %.3g' % (k, mu), fontdict={'size': 9}) # limit to 40 characters 338 | if i % 5 != 0: 339 | plt.yticks([]) 340 | print('%15s: %.3g' % (k, mu)) 341 | plt.savefig('evolve.png', dpi=200) 342 | print('\nPlot saved as evolve.png') 343 | 344 | 345 | def profile_idetection(start=0, stop=0, labels=(), save_dir=''): 346 | # Plot iDetection '*.txt' per-image logs. from utils.plots import *; profile_idetection() 347 | ax = plt.subplots(2, 4, figsize=(12, 6), tight_layout=True)[1].ravel() 348 | s = ['Images', 'Free Storage (GB)', 'RAM Usage (GB)', 'Battery', 'dt_raw (ms)', 'dt_smooth (ms)', 'real-world FPS'] 349 | files = list(Path(save_dir).glob('frames*.txt')) 350 | for fi, f in enumerate(files): 351 | try: 352 | results = np.loadtxt(f, ndmin=2).T[:, 90:-30] # clip first and last rows 353 | n = results.shape[1] # number of rows 354 | x = np.arange(start, min(stop, n) if stop else n) 355 | results = results[:, x] 356 | t = (results[0] - results[0].min()) # set t0=0s 357 | results[0] = x 358 | for i, a in enumerate(ax): 359 | if i < len(results): 360 | label = labels[fi] if len(labels) else f.stem.replace('frames_', '') 361 | a.plot(t, results[i], marker='.', label=label, linewidth=1, markersize=5) 362 | a.set_title(s[i]) 363 | a.set_xlabel('time (s)') 364 | # if fi == len(files) - 1: 365 | # a.set_ylim(bottom=0) 366 | for side in ['top', 'right']: 367 | a.spines[side].set_visible(False) 368 | else: 369 | a.remove() 370 | except Exception as e: 371 | print('Warning: Plotting error for %s; %s' % (f, e)) 372 | 373 | ax[1].legend() 374 | plt.savefig(Path(save_dir) / 'idetection_profile.png', dpi=200) 375 | 376 | 377 | def plot_results_overlay(start=0, stop=0): # from utils.plots import *; plot_results_overlay() 378 | # Plot training 'results*.txt', overlaying train and val losses 379 | s = ['train', 'train', 'train', 'Precision', 'mAP@0.5', 'val', 'val', 'val', 'Recall', 'mAP@0.5:0.95'] # legends 380 | t = ['Box', 'Objectness', 'Classification', 'P-R', 'mAP-F1'] # titles 381 | for f in sorted(glob.glob('results*.txt') + glob.glob('../../Downloads/results*.txt')): 382 | results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T 383 | n = results.shape[1] # number of rows 384 | x = range(start, min(stop, n) if stop else n) 385 | fig, ax = plt.subplots(1, 5, figsize=(14, 3.5), tight_layout=True) 386 | ax = ax.ravel() 387 | for i in range(5): 388 | for j in [i, i + 5]: 389 | y = results[j, x] 390 | ax[i].plot(x, y, marker='.', label=s[j]) 391 | # y_smooth = butter_lowpass_filtfilt(y) 392 | # ax[i].plot(x, np.gradient(y_smooth), marker='.', label=s[j]) 393 | 394 | ax[i].set_title(t[i]) 395 | ax[i].legend() 396 | ax[i].set_ylabel(f) if i == 0 else None # add filename 397 | fig.savefig(f.replace('.txt', '.png'), dpi=200) 398 | 399 | 400 | def plot_results(start=0, stop=0, bucket='', id=(), labels=(), save_dir=''): 401 | # Plot training 'results*.txt'. from utils.plots import *; plot_results(save_dir='runs/train/exp') 402 | fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True) 403 | ax = ax.ravel() 404 | s = ['Box', 'Objectness', 'Classification', 'Precision', 'Recall', 405 | 'val Box', 'val Objectness', 'val Classification', 'mAP@0.5', 'mAP@0.5:0.95'] 406 | if bucket: 407 | # files = ['https://storage.googleapis.com/%s/results%g.txt' % (bucket, x) for x in id] 408 | files = ['results%g.txt' % x for x in id] 409 | c = ('gsutil cp ' + '%s ' * len(files) + '.') % tuple('gs://%s/results%g.txt' % (bucket, x) for x in id) 410 | os.system(c) 411 | else: 412 | files = list(Path(save_dir).glob('results*.txt')) 413 | assert len(files), 'No results.txt files found in %s, nothing to plot.' % os.path.abspath(save_dir) 414 | for fi, f in enumerate(files): 415 | try: 416 | results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T 417 | n = results.shape[1] # number of rows 418 | x = range(start, min(stop, n) if stop else n) 419 | for i in range(10): 420 | y = results[i, x] 421 | if i in [0, 1, 2, 5, 6, 7]: 422 | y[y == 0] = np.nan # don't show zero loss values 423 | # y /= y[0] # normalize 424 | label = labels[fi] if len(labels) else f.stem 425 | ax[i].plot(x, y, marker='.', label=label, linewidth=2, markersize=8) 426 | ax[i].set_title(s[i]) 427 | # if i in [5, 6, 7]: # share train and val loss y axes 428 | # ax[i].get_shared_y_axes().join(ax[i], ax[i - 5]) 429 | except Exception as e: 430 | print('Warning: Plotting error for %s; %s' % (f, e)) 431 | 432 | ax[1].legend() 433 | fig.savefig(Path(save_dir) / 'results.png', dpi=200) 434 | 435 | 436 | def output_to_keypoint(output): 437 | # Convert model output to target format [batch_id, class_id, x, y, w, h, conf] 438 | targets = [] 439 | for i, o in enumerate(output): 440 | kpts = o[:,6:] 441 | o = o[:,:6] 442 | for index, (*box, conf, cls) in enumerate(o.detach().cpu().numpy()): 443 | targets.append([i, cls, *list(*xyxy2xywh(np.array(box)[None])), conf, *list(kpts.detach().cpu().numpy()[index])]) 444 | return np.array(targets) 445 | 446 | 447 | def plot_skeleton_kpts(im, kpts, steps, orig_shape=None): 448 | #Plot the skeleton and keypointsfor coco datatset 449 | palette = np.array([[255, 128, 0], [255, 153, 51], [255, 178, 102], 450 | [230, 230, 0], [255, 153, 255], [153, 204, 255], 451 | [255, 102, 255], [255, 51, 255], [102, 178, 255], 452 | [51, 153, 255], [255, 153, 153], [255, 102, 102], 453 | [255, 51, 51], [153, 255, 153], [102, 255, 102], 454 | [51, 255, 51], [0, 255, 0], [0, 0, 255], [255, 0, 0], 455 | [255, 255, 255]]) 456 | 457 | skeleton = [[16, 14], [14, 12], [17, 15], [15, 13], [12, 13], [6, 12], 458 | [7, 13], [6, 7], [6, 8], [7, 9], [8, 10], [9, 11], [2, 3], 459 | [1, 2], [1, 3], [2, 4], [3, 5], [4, 6], [5, 7]] 460 | 461 | pose_limb_color = palette[[9, 9, 9, 9, 7, 7, 7, 0, 0, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16]] 462 | pose_kpt_color = palette[[16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9]] 463 | radius = 5 464 | num_kpts = len(kpts) // steps 465 | 466 | for kid in range(num_kpts): 467 | r, g, b = pose_kpt_color[kid] 468 | x_coord, y_coord = kpts[steps * kid], kpts[steps * kid + 1] 469 | if not (x_coord % 640 == 0 or y_coord % 640 == 0): 470 | if steps == 3: 471 | conf = kpts[steps * kid + 2] 472 | if conf < 0.5: 473 | continue 474 | cv2.circle(im, (int(x_coord), int(y_coord)), radius, (int(r), int(g), int(b)), -1) 475 | 476 | for sk_id, sk in enumerate(skeleton): 477 | r, g, b = pose_limb_color[sk_id] 478 | pos1 = (int(kpts[(sk[0]-1)*steps]), int(kpts[(sk[0]-1)*steps+1])) 479 | pos2 = (int(kpts[(sk[1]-1)*steps]), int(kpts[(sk[1]-1)*steps+1])) 480 | if steps == 3: 481 | conf1 = kpts[(sk[0]-1)*steps+2] 482 | conf2 = kpts[(sk[1]-1)*steps+2] 483 | if conf1<0.5 or conf2<0.5: 484 | continue 485 | if pos1[0]%640 == 0 or pos1[1]%640==0 or pos1[0]<0 or pos1[1]<0: 486 | continue 487 | if pos2[0] % 640 == 0 or pos2[1] % 640 == 0 or pos2[0]<0 or pos2[1]<0: 488 | continue 489 | cv2.line(im, pos1, pos2, (int(r), int(g), int(b)), thickness=2) 490 | -------------------------------------------------------------------------------- /Yolov7/utils/torch_utils.py: -------------------------------------------------------------------------------- 1 | # YOLOR PyTorch utils 2 | 3 | import datetime 4 | import logging 5 | import math 6 | import os 7 | import platform 8 | import subprocess 9 | import time 10 | from contextlib import contextmanager 11 | from copy import deepcopy 12 | from pathlib import Path 13 | 14 | import torch 15 | import torch.backends.cudnn as cudnn 16 | import torch.nn as nn 17 | import torch.nn.functional as F 18 | import torchvision 19 | 20 | try: 21 | import thop # for FLOPS computation 22 | except ImportError: 23 | thop = None 24 | logger = logging.getLogger(__name__) 25 | 26 | 27 | @contextmanager 28 | def torch_distributed_zero_first(local_rank: int): 29 | """ 30 | Decorator to make all processes in distributed training wait for each local_master to do something. 31 | """ 32 | if local_rank not in [-1, 0]: 33 | torch.distributed.barrier() 34 | yield 35 | if local_rank == 0: 36 | torch.distributed.barrier() 37 | 38 | 39 | def init_torch_seeds(seed=0): 40 | # Speed-reproducibility tradeoff https://pytorch.org/docs/stable/notes/randomness.html 41 | torch.manual_seed(seed) 42 | if seed == 0: # slower, more reproducible 43 | cudnn.benchmark, cudnn.deterministic = False, True 44 | else: # faster, less reproducible 45 | cudnn.benchmark, cudnn.deterministic = True, False 46 | 47 | 48 | def date_modified(path=__file__): 49 | # return human-readable file modification date, i.e. '2021-3-26' 50 | t = datetime.datetime.fromtimestamp(Path(path).stat().st_mtime) 51 | return f'{t.year}-{t.month}-{t.day}' 52 | 53 | 54 | def git_describe(path=Path(__file__).parent): # path must be a directory 55 | # return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe 56 | s = f'git -C {path} describe --tags --long --always' 57 | try: 58 | return subprocess.check_output(s, shell=True, stderr=subprocess.STDOUT).decode()[:-1] 59 | except subprocess.CalledProcessError as e: 60 | return '' # not a git repository 61 | 62 | 63 | def select_device(device='', batch_size=None): 64 | # device = 'cpu' or '0' or '0,1,2,3' 65 | s = f'YOLOR 🚀 {git_describe() or date_modified()} torch {torch.__version__} ' # string 66 | cpu = device.lower() == 'cpu' 67 | if cpu: 68 | os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False 69 | elif device: # non-cpu device requested 70 | os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable 71 | assert torch.cuda.is_available(), f'CUDA unavailable, invalid device {device} requested' # check availability 72 | 73 | cuda = not cpu and torch.cuda.is_available() 74 | if cuda: 75 | n = torch.cuda.device_count() 76 | if n > 1 and batch_size: # check that batch_size is compatible with device_count 77 | assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}' 78 | space = ' ' * len(s) 79 | for i, d in enumerate(device.split(',') if device else range(n)): 80 | p = torch.cuda.get_device_properties(i) 81 | s += f"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / 1024 ** 2}MB)\n" # bytes to MB 82 | else: 83 | s += 'CPU\n' 84 | 85 | logger.info(s.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else s) # emoji-safe 86 | return torch.device('cuda:0' if cuda else 'cpu') 87 | 88 | 89 | def time_synchronized(): 90 | # pytorch-accurate time 91 | if torch.cuda.is_available(): 92 | torch.cuda.synchronize() 93 | return time.time() 94 | 95 | 96 | def profile(x, ops, n=100, device=None): 97 | # profile a pytorch module or list of modules. Example usage: 98 | # x = torch.randn(16, 3, 640, 640) # input 99 | # m1 = lambda x: x * torch.sigmoid(x) 100 | # m2 = nn.SiLU() 101 | # profile(x, [m1, m2], n=100) # profile speed over 100 iterations 102 | 103 | device = device or torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') 104 | x = x.to(device) 105 | x.requires_grad = True 106 | print(torch.__version__, device.type, torch.cuda.get_device_properties(0) if device.type == 'cuda' else '') 107 | print(f"\n{'Params':>12s}{'GFLOPS':>12s}{'forward (ms)':>16s}{'backward (ms)':>16s}{'input':>24s}{'output':>24s}") 108 | for m in ops if isinstance(ops, list) else [ops]: 109 | m = m.to(device) if hasattr(m, 'to') else m # device 110 | m = m.half() if hasattr(m, 'half') and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m # type 111 | dtf, dtb, t = 0., 0., [0., 0., 0.] # dt forward, backward 112 | try: 113 | flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # GFLOPS 114 | except: 115 | flops = 0 116 | 117 | for _ in range(n): 118 | t[0] = time_synchronized() 119 | y = m(x) 120 | t[1] = time_synchronized() 121 | try: 122 | _ = y.sum().backward() 123 | t[2] = time_synchronized() 124 | except: # no backward method 125 | t[2] = float('nan') 126 | dtf += (t[1] - t[0]) * 1000 / n # ms per op forward 127 | dtb += (t[2] - t[1]) * 1000 / n # ms per op backward 128 | 129 | s_in = tuple(x.shape) if isinstance(x, torch.Tensor) else 'list' 130 | s_out = tuple(y.shape) if isinstance(y, torch.Tensor) else 'list' 131 | p = sum(list(x.numel() for x in m.parameters())) if isinstance(m, nn.Module) else 0 # parameters 132 | print(f'{p:12}{flops:12.4g}{dtf:16.4g}{dtb:16.4g}{str(s_in):>24s}{str(s_out):>24s}') 133 | 134 | 135 | def is_parallel(model): 136 | return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel) 137 | 138 | 139 | def intersect_dicts(da, db, exclude=()): 140 | # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values 141 | 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} 142 | 143 | 144 | def initialize_weights(model): 145 | for m in model.modules(): 146 | t = type(m) 147 | if t is nn.Conv2d: 148 | pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') 149 | elif t is nn.BatchNorm2d: 150 | m.eps = 1e-3 151 | m.momentum = 0.03 152 | elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6]: 153 | m.inplace = True 154 | 155 | 156 | def find_modules(model, mclass=nn.Conv2d): 157 | # Finds layer indices matching module class 'mclass' 158 | return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)] 159 | 160 | 161 | def sparsity(model): 162 | # Return global model sparsity 163 | a, b = 0., 0. 164 | for p in model.parameters(): 165 | a += p.numel() 166 | b += (p == 0).sum() 167 | return b / a 168 | 169 | 170 | def prune(model, amount=0.3): 171 | # Prune model to requested global sparsity 172 | import torch.nn.utils.prune as prune 173 | print('Pruning model... ', end='') 174 | for name, m in model.named_modules(): 175 | if isinstance(m, nn.Conv2d): 176 | prune.l1_unstructured(m, name='weight', amount=amount) # prune 177 | prune.remove(m, 'weight') # make permanent 178 | print(' %.3g global sparsity' % sparsity(model)) 179 | 180 | 181 | def fuse_conv_and_bn(conv, bn): 182 | # Fuse convolution and batchnorm layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/ 183 | fusedconv = nn.Conv2d(conv.in_channels, 184 | conv.out_channels, 185 | kernel_size=conv.kernel_size, 186 | stride=conv.stride, 187 | padding=conv.padding, 188 | groups=conv.groups, 189 | bias=True).requires_grad_(False).to(conv.weight.device) 190 | 191 | # prepare filters 192 | w_conv = conv.weight.clone().view(conv.out_channels, -1) 193 | w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var))) 194 | fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.shape)) 195 | 196 | # prepare spatial bias 197 | b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias 198 | b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps)) 199 | fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn) 200 | 201 | return fusedconv 202 | 203 | 204 | def model_info(model, verbose=False, img_size=640): 205 | # Model information. img_size may be int or list, i.e. img_size=640 or img_size=[640, 320] 206 | n_p = sum(x.numel() for x in model.parameters()) # number parameters 207 | n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients 208 | if verbose: 209 | print('%5s %40s %9s %12s %20s %10s %10s' % ('layer', 'name', 'gradient', 'parameters', 'shape', 'mu', 'sigma')) 210 | for i, (name, p) in enumerate(model.named_parameters()): 211 | name = name.replace('module_list.', '') 212 | print('%5g %40s %9s %12g %20s %10.3g %10.3g' % 213 | (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std())) 214 | 215 | try: # FLOPS 216 | from thop import profile 217 | stride = max(int(model.stride.max()), 32) if hasattr(model, 'stride') else 32 218 | img = torch.zeros((1, model.yaml.get('ch', 3), stride, stride), device=next(model.parameters()).device) # input 219 | flops = profile(deepcopy(model), inputs=(img,), verbose=False)[0] / 1E9 * 2 # stride GFLOPS 220 | img_size = img_size if isinstance(img_size, list) else [img_size, img_size] # expand if int/float 221 | fs = ', %.1f GFLOPS' % (flops * img_size[0] / stride * img_size[1] / stride) # 640x640 GFLOPS 222 | except (ImportError, Exception): 223 | fs = '' 224 | 225 | logger.info(f"Model Summary: {len(list(model.modules()))} layers, {n_p} parameters, {n_g} gradients{fs}") 226 | 227 | 228 | def load_classifier(name='resnet101', n=2): 229 | # Loads a pretrained model reshaped to n-class output 230 | model = torchvision.models.__dict__[name](pretrained=True) 231 | 232 | # ResNet model properties 233 | # input_size = [3, 224, 224] 234 | # input_space = 'RGB' 235 | # input_range = [0, 1] 236 | # mean = [0.485, 0.456, 0.406] 237 | # std = [0.229, 0.224, 0.225] 238 | 239 | # Reshape output to n classes 240 | filters = model.fc.weight.shape[1] 241 | model.fc.bias = nn.Parameter(torch.zeros(n), requires_grad=True) 242 | model.fc.weight = nn.Parameter(torch.zeros(n, filters), requires_grad=True) 243 | model.fc.out_features = n 244 | return model 245 | 246 | 247 | def scale_img(img, ratio=1.0, same_shape=False, gs=32): # img(16,3,256,416) 248 | # scales img(bs,3,y,x) by ratio constrained to gs-multiple 249 | if ratio == 1.0: 250 | return img 251 | else: 252 | h, w = img.shape[2:] 253 | s = (int(h * ratio), int(w * ratio)) # new size 254 | img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize 255 | if not same_shape: # pad/crop img 256 | h, w = [math.ceil(x * ratio / gs) * gs for x in (h, w)] 257 | return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean 258 | 259 | 260 | def copy_attr(a, b, include=(), exclude=()): 261 | # Copy attributes from b to a, options to only include [...] and to exclude [...] 262 | for k, v in b.__dict__.items(): 263 | if (len(include) and k not in include) or k.startswith('_') or k in exclude: 264 | continue 265 | else: 266 | setattr(a, k, v) 267 | 268 | 269 | class ModelEMA: 270 | """ Model Exponential Moving Average from https://github.com/rwightman/pytorch-image-models 271 | Keep a moving average of everything in the model state_dict (parameters and buffers). 272 | This is intended to allow functionality like 273 | https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage 274 | A smoothed version of the weights is necessary for some training schemes to perform well. 275 | This class is sensitive where it is initialized in the sequence of model init, 276 | GPU assignment and distributed training wrappers. 277 | """ 278 | 279 | def __init__(self, model, decay=0.9999, updates=0): 280 | # Create EMA 281 | self.ema = deepcopy(model.module if is_parallel(model) else model).eval() # FP32 EMA 282 | # if next(model.parameters()).device.type != 'cpu': 283 | # self.ema.half() # FP16 EMA 284 | self.updates = updates # number of EMA updates 285 | self.decay = lambda x: decay * (1 - math.exp(-x / 2000)) # decay exponential ramp (to help early epochs) 286 | for p in self.ema.parameters(): 287 | p.requires_grad_(False) 288 | 289 | def update(self, model): 290 | # Update EMA parameters 291 | with torch.no_grad(): 292 | self.updates += 1 293 | d = self.decay(self.updates) 294 | 295 | msd = model.module.state_dict() if is_parallel(model) else model.state_dict() # model state_dict 296 | for k, v in self.ema.state_dict().items(): 297 | if v.dtype.is_floating_point: 298 | v *= d 299 | v += (1. - d) * msd[k].detach() 300 | 301 | def update_attr(self, model, include=(), exclude=('process_group', 'reducer')): 302 | # Update EMA attributes 303 | copy_attr(self.ema, model, include, exclude) 304 | 305 | 306 | class BatchNormXd(torch.nn.modules.batchnorm._BatchNorm): 307 | def _check_input_dim(self, input): 308 | # The only difference between BatchNorm1d, BatchNorm2d, BatchNorm3d, etc 309 | # is this method that is overwritten by the sub-class 310 | # This original goal of this method was for tensor sanity checks 311 | # If you're ok bypassing those sanity checks (eg. if you trust your inference 312 | # to provide the right dimensional inputs), then you can just use this method 313 | # for easy conversion from SyncBatchNorm 314 | # (unfortunately, SyncBatchNorm does not store the original class - if it did 315 | # we could return the one that was originally created) 316 | return 317 | 318 | def revert_sync_batchnorm(module): 319 | # this is very similar to the function that it is trying to revert: 320 | # https://github.com/pytorch/pytorch/blob/c8b3686a3e4ba63dc59e5dcfe5db3430df256833/torch/nn/modules/batchnorm.py#L679 321 | module_output = module 322 | if isinstance(module, torch.nn.modules.batchnorm.SyncBatchNorm): 323 | new_cls = BatchNormXd 324 | module_output = BatchNormXd(module.num_features, 325 | module.eps, module.momentum, 326 | module.affine, 327 | module.track_running_stats) 328 | if module.affine: 329 | with torch.no_grad(): 330 | module_output.weight = module.weight 331 | module_output.bias = module.bias 332 | module_output.running_mean = module.running_mean 333 | module_output.running_var = module.running_var 334 | module_output.num_batches_tracked = module.num_batches_tracked 335 | if hasattr(module, "qconfig"): 336 | module_output.qconfig = module.qconfig 337 | for name, child in module.named_children(): 338 | module_output.add_module(name, revert_sync_batchnorm(child)) 339 | del module 340 | return module_output 341 | 342 | 343 | class TracedModel(nn.Module): 344 | 345 | def __init__(self, model=None, device=None, img_size=(640,640)): 346 | super(TracedModel, self).__init__() 347 | 348 | print(" Convert model to Traced-model... ") 349 | self.stride = model.stride 350 | self.names = model.names 351 | self.model = model 352 | 353 | self.model = revert_sync_batchnorm(self.model) 354 | self.model.to('cpu') 355 | self.model.eval() 356 | 357 | self.detect_layer = self.model.model[-1] 358 | self.model.traced = True 359 | 360 | rand_example = torch.rand(1, 3, img_size, img_size) 361 | 362 | traced_script_module = torch.jit.trace(self.model, rand_example, strict=False) 363 | #traced_script_module = torch.jit.script(self.model) 364 | traced_script_module.save("traced_model.pt") 365 | print(" traced_script_module saved! ") 366 | self.model = traced_script_module 367 | self.model.to(device) 368 | self.detect_layer.to(device) 369 | print(" model is traced! \n") 370 | 371 | def forward(self, x, augment=False, profile=False): 372 | out = self.model(x) 373 | out = self.detect_layer(out) 374 | return out --------------------------------------------------------------------------------