├── .gitignore ├── CODE_OF_CONDUCT.md ├── Darknet53 implementation using Tensorflow 2.0.ipynb ├── LICENSE ├── README.md ├── convert_weights.py ├── demo.py ├── img_data ├── .DS_Store ├── boat.jpeg ├── out │ ├── boat.jpeg │ └── test.jpg └── test.jpg ├── model.py ├── tf2_demo.py ├── utils.py └── yolo_v3.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | 106 | # vim tmp file 107 | *~ 108 | 109 | # PyCharm 110 | .idea/ 111 | 112 | .DS_Store 113 | *.png 114 | coco.names 115 | *.weights 116 | 117 | # VSCode 118 | .vscode/ 119 | 120 | # Tensorflow 121 | checkpoint 122 | *.ckpt.* 123 | 124 | .DS_Store -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at pawel.kapica@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # YOLOv3 implementation in TensorFlow 2.0 2 | 3 | This implementation of YOLOv3 object detector in TensorFlow 2.0 (Keras). Referenced great resources below. Traning is on going. Tested on Python 3.6, TensorFlow 2.0 alpha on Ubuntu 16.04. 4 | 5 | ## Reference 6 | - [Darknet YOLO](https://pjreddie.com/darknet/yolo/) 7 | - models 8 | - weight converter 9 | - [YangYun](https://github.com/YunYang1994/tensorflow-yolov3) 10 | - weight onverter 11 | - [How to implement a YOLO(v3) Object detector from scratch in PyTorch](https://blog.paperspace.com/how-to-implement-a-yolo-object-detector-in-pytorch/) 12 | - weight converter 13 | - [Paweł Kapica](https://github.com/mystic123/tensorflow-yolo-v3) 14 | - models 15 | - [YoloV3 Implemented in TensorFlow 2.0](https://github.com/zzh8829/yolov3-tf2) 16 | - models for TensorFlow 2.0 17 | - [Densely Connected Convolutional Networks](https://github.com/tensorflow/examples/tree/master/tensorflow_examples/models/densenet) 18 | - model class for TensorFlow 2.0 19 | 20 | ## Todo list: 21 | - [x] Darknet53 architecture and Test 22 | - [x] YOLOv3 architecture 23 | - [x] Basic working demo 24 | - [x] Weights converter (util for exporting loaded COCO weights as TF checkpoint) 25 | - [ ] Training pipeline 26 | - [ ] More backends 27 | 28 | ## How to run the demo: 29 | To run demo type this in the command line: 30 | 31 | 1. Download COCO class names file: `wget https://raw.githubusercontent.com/pjreddie/darknet/master/data/coco.names` 32 | 2. Download and convert model weights: 33 | 1. Download binary file with desired weights: 34 | 1. Full weights: `wget https://pjreddie.com/media/files/yolov3.weights` 35 | 2. Run `python ./convert_weights.py` 36 | 3. Run `python ./demo.py --input_img --output_img ` 37 | 38 | ####Optional Flags 39 | 1. convert_weights.py: 40 | 1. `--class_names` 41 | 1. Path to the class names file 42 | 2. `--weights_file` 43 | 1. Path to the desired weights file 44 | 3. `--data_format` 45 | 1. `channels_first` or `channels_last` 46 | 4. `--tf2_weights` 47 | 1. Output weights file 48 | 2. demo.py 49 | 1. `--class_names` 50 | 1. Path to the class names file 51 | 2. `--input_img` 52 | 1. Path to the input image file 53 | 3. `--output_img` 54 | 1. Path to the output image file 55 | 4. `--data_format` 56 | 1. `channels_first` or `channels_last` 57 | 5. `--weights` 58 | 1. TensorFlow 2.0 Weights file. 59 | 6. `--score_threshold` 60 | 1. Desired Score Threshold 61 | 7. `--iou_threshold` 62 | 1. Desired IOU Threshold 63 | -------------------------------------------------------------------------------- /convert_weights.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import numpy as np 3 | from model import create_model 4 | import logging 5 | import argparse 6 | 7 | from utils import load_coco_names, load_weights 8 | 9 | 10 | IMG_H, IMG_W = 416, 416 11 | 12 | yolo_anchors = np.array([(10, 13), (16, 30), (33, 23), (30, 61), (62, 45), 13 | (59, 119), (116, 90), (156, 198), (373, 326)], 14 | np.float32) 15 | yolo_anchor_masks = np.array([[6, 7, 8], [3, 4, 5], [0, 1, 2]]) 16 | 17 | parser = argparse.ArgumentParser(description="YOLO-V3 weight convert") 18 | 19 | parser.add_argument("--class_names", type=str, default="coco.names", 20 | help="File with class names.") 21 | parser.add_argument("--weights_file", type=str, default="yolov3.weights", 22 | help="Binary file with detector weights.") 23 | parser.add_argument("--data_format", type=str, default="channels_last", 24 | help="Data format: channels_first / channels_last.") 25 | #parser.add_argument("--tiny", type=bool, default=False, 26 | # help="Use tiny version of YOLOv3.") 27 | parser.add_argument("--tf2_weights", type=str, default="./weights/yolov3.tf", 28 | help="Tensorflow 2.0 Weights file.") 29 | 30 | 31 | def main(argv=None): 32 | 33 | classes = load_coco_names(args.class_names) 34 | 35 | model = create_model(IMG_H, yolo_anchors, yolo_anchor_masks, len(classes)) 36 | load_ops = load_weights(model, args.weights_file) 37 | 38 | """ 39 | Saving Subclassed Models 40 | 41 | https://www.tensorflow.org/alpha/guide/keras/saving_and_serializing 42 | Sequential models and Functional models are datastructures that represent a DAG of layers. 43 | As such, they can be safely serialized and deserialized. 44 | 45 | https://medium.com/tensorflow/what-are-symbolic-and-imperative-apis-in-tensorflow-2-0-dfccecb01021 46 | """ 47 | model.save_weights(args.tf2_weights) 48 | 49 | 50 | if __name__ == '__main__': 51 | args = parser.parse_args() 52 | main(args) 53 | -------------------------------------------------------------------------------- /demo.py: -------------------------------------------------------------------------------- 1 | import time 2 | import numpy as np 3 | import tensorflow as tf 4 | import argparse 5 | from model import create_model 6 | from utils import load_coco_names, draw_boxes3, draw_boxes2, draw_boxes 7 | from PIL import Image 8 | from absl import app, flags, logging 9 | from absl.flags import FLAGS 10 | 11 | IMG_H, IMG_W = 416, 416 12 | 13 | yolo_anchors = np.array([(10, 13), (16, 30), (33, 23), (30, 61), (62, 45), 14 | (59, 119), (116, 90), (156, 198), (373, 326)], 15 | np.float32) 16 | yolo_anchor_masks = np.array([[6, 7, 8], [3, 4, 5], [0, 1, 2]]) 17 | 18 | 19 | flags.DEFINE_string("class_names", "coco.names", "File with class names.") 20 | flags.DEFINE_string("input_img", "./img_data/test_4.jpg", "Input image file name.") 21 | flags.DEFINE_string("output_img", "./img_data/out/test_4.jpg", "Output image file name.") 22 | flags.DEFINE_string("data_format", "channels_last", "Data format: channels_first (gpu only) / channels_last.") 23 | flags.DEFINE_string("weights", "./weights/yolov3.tf", "Tensorflow 2.0 Weights file.") 24 | flags.DEFINE_float("score_threshold", 0.5, "Desired Score Threshold") 25 | flags.DEFINE_float("iou_threshold", 0.5, "Desired IOU Threshold") 26 | 27 | def main(_argv): 28 | 29 | img = Image.open(FLAGS.input_img) 30 | img_resized = np.asarray(img.resize(size=(IMG_H, IMG_W)), dtype=np.float32) 31 | img_resized = img_resized/255.0 32 | 33 | classes = load_coco_names(FLAGS.class_names) 34 | model = create_model(IMG_H, yolo_anchors, yolo_anchor_masks, len(classes)) 35 | print("=> loading weights ...") 36 | model.load_weights(FLAGS.weights) 37 | print("=> sucessfully loaded weights ") 38 | 39 | start = time.time() 40 | boxes, scores, labels, nums = model(img_resized[np.newaxis, ...], training=False) 41 | boxes, scores, labels, nums = boxes.numpy(), scores.numpy(), labels.numpy(), nums.numpy() 42 | #boxes, scores, labels = model(img_resized[np.newaxis, ...]) 43 | print("=> nms on the number of boxes= %d time=%.2f ms" %(nums, 1000*(time.time()-start))) 44 | 45 | image = draw_boxes2(img, boxes[0], scores[0], labels[0], nums[0], classes, [IMG_H, IMG_W], show=True) 46 | #image = draw_boxes3(img, boxes, scores, labels, classes, [IMG_H, IMG_W], show=True) 47 | image.save(FLAGS.output_img) 48 | 49 | if __name__ == '__main__': 50 | try: 51 | app.run(main) 52 | except SystemExit: 53 | pass -------------------------------------------------------------------------------- /img_data/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theoseo/yolov3-tensorflow2/aed02579bb0e3cc29906b421dfd46e3396ba9b29/img_data/.DS_Store -------------------------------------------------------------------------------- /img_data/boat.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theoseo/yolov3-tensorflow2/aed02579bb0e3cc29906b421dfd46e3396ba9b29/img_data/boat.jpeg -------------------------------------------------------------------------------- /img_data/out/boat.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theoseo/yolov3-tensorflow2/aed02579bb0e3cc29906b421dfd46e3396ba9b29/img_data/out/boat.jpeg -------------------------------------------------------------------------------- /img_data/out/test.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theoseo/yolov3-tensorflow2/aed02579bb0e3cc29906b421dfd46e3396ba9b29/img_data/out/test.jpg -------------------------------------------------------------------------------- /img_data/test.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theoseo/yolov3-tensorflow2/aed02579bb0e3cc29906b421dfd46e3396ba9b29/img_data/test.jpg -------------------------------------------------------------------------------- /model.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import numpy as np 4 | import tensorflow as tf 5 | from tensorflow.keras import layers 6 | from tensorflow.keras.regularizers import l2 7 | import time 8 | from absl import app, flags, logging 9 | 10 | def create_model(size, yolo_anchors, yolo_anchor_masks, classes, training=False): 11 | 12 | inputs = tf.keras.Input(shape=(size, size, 3)) 13 | outputs = YoloV3(size, yolo_anchors, yolo_anchor_masks, classes)(inputs, training=training) 14 | return tf.keras.Model(inputs, outputs, name='yolov3') 15 | 16 | 17 | class DarknetConv(layers.Layer): 18 | 19 | def __init__(self, filters, size, strides=1, is_batch_norm=True): 20 | 21 | super(DarknetConv, self).__init__() 22 | self.filters = filters 23 | self.size = size 24 | self.is_batch_norm = is_batch_norm 25 | self.strides = strides 26 | 27 | self.zeropadding = layers.ZeroPadding2D(((1,0),(1,0))) 28 | self.conv2d = layers.Conv2D(filters, size, 29 | strides, padding = ('same' if strides == 1 else 'valid'), 30 | use_bias = not is_batch_norm, kernel_regularizer=l2(0.0005)) 31 | self.batchnorm = layers.BatchNormalization(momentum = 0.9, epsilon = 1e-05) 32 | self.leakyrelu = layers.LeakyReLU(alpha=0.1) 33 | 34 | def call(self, x, training=True): 35 | 36 | if self.strides > 1: 37 | x = self.zeropadding(x) 38 | 39 | x = self.conv2d(x) 40 | 41 | if self.is_batch_norm : 42 | x = self.batchnorm(x) 43 | x = self.leakyrelu(x) 44 | 45 | return x 46 | 47 | class DarknetResidual(layers.Layer): 48 | 49 | def __init__(self, filters): 50 | 51 | super(DarknetResidual, self).__init__() 52 | self.filters = filters 53 | 54 | self.darknetconv1 = DarknetConv(filters, 1) 55 | self.darknetconv2 = DarknetConv(filters * 2, 3) 56 | self.add = layers.Add() 57 | 58 | def call(self, x, training=True): 59 | 60 | shortcut = x 61 | x = self.darknetconv1(x, training=training) 62 | x = self.darknetconv2(x, training=training) 63 | x = self.add([shortcut, x]) 64 | 65 | return x 66 | 67 | class DarknetBlock(layers.Layer): 68 | 69 | def __init__(self, filters, blocks): 70 | 71 | super(DarknetBlock, self).__init__() 72 | self.filters = filters 73 | self.blocks = blocks 74 | 75 | self.darknetconv = DarknetConv(filters, 3, strides=2) 76 | self.darknetblocks = [DarknetResidual(filters//2) for _ in range(blocks)] 77 | 78 | def call(self, x, training=True): 79 | 80 | x = self.darknetconv(x, training=training) 81 | for i in range(self.blocks): 82 | x = self.darknetblocks[i](x, training=training) 83 | 84 | return x 85 | 86 | class Darknet(tf.keras.Model): 87 | 88 | def __init__(self, name, **kwargs): 89 | super(Darknet, self).__init__(name=name, **kwargs) 90 | #self.name = name 91 | 92 | self.conv1 = DarknetConv(32, 3) 93 | self.block1 = DarknetBlock(64, 1) 94 | self.block2 = DarknetBlock(128, 2) 95 | self.block3 = DarknetBlock(256, 8) 96 | self.block4 = DarknetBlock(512, 8) 97 | self.block5 = DarknetBlock(1024, 4) 98 | 99 | def call(self, x, training=True): 100 | 101 | x = self.conv1(x, training=training) 102 | x = self.block1(x, training=training) 103 | x = self.block2(x, training=training) 104 | x = route_1 = self.block3(x, training=training) 105 | x = route_2 = self.block4(x, training=training) 106 | x = self.block5(x, training=training) 107 | 108 | return route_1, route_2, x 109 | 110 | class YoloConv(layers.Layer): 111 | 112 | def __init__(self, filters, is_first=True): 113 | super(YoloConv, self).__init__() 114 | self.is_first = is_first 115 | 116 | if not self.is_first : 117 | 118 | self.conv1 = DarknetConv(filters, 1) 119 | self.upsampling = layers.UpSampling2D() 120 | self.concat = layers.Concatenate() 121 | 122 | 123 | self.conv2 = DarknetConv(filters, 1) 124 | self.conv3 = DarknetConv(filters * 2, 3) 125 | self.conv4 = DarknetConv(filters, 1) 126 | self.conv5 = DarknetConv(filters * 2, 3) 127 | self.conv6 = DarknetConv(filters, 1) 128 | 129 | def call(self, x, training=True): 130 | 131 | if not self.is_first : 132 | x, x_skip = x 133 | 134 | x = self.conv1(x, training=training) 135 | x = self.upsampling(x) 136 | x = self.concat([x, x_skip]) 137 | 138 | x = self.conv2(x, training=training) 139 | x = self.conv3(x, training=training) 140 | x = self.conv4(x, training=training) 141 | x = self.conv5(x, training=training) 142 | x = self.conv6(x, training=training) 143 | 144 | return x 145 | 146 | class YoloOutput(layers.Layer): 147 | 148 | def __init__(self, filters, anchors, classes ): 149 | super(YoloOutput, self).__init__() 150 | 151 | self.filters = filters 152 | self.anchors = anchors 153 | self.classes = classes 154 | 155 | self.darkconv = DarknetConv(filters*2, 3) 156 | self.biasconv = DarknetConv(anchors * (classes + 5), 1, is_batch_norm=False) 157 | 158 | def call(self, x, training=True): 159 | 160 | x = self.darkconv(x, training=training) 161 | x = self.biasconv(x, training=training) 162 | x = tf.reshape(x, (-1, tf.shape(x)[1], tf.shape(x)[2], self.anchors, self.classes+5)) 163 | 164 | return x 165 | 166 | 167 | class YoloV3(tf.keras.Model): 168 | 169 | def __init__(self, size, anchors, anchor_masks, classes ): 170 | super(YoloV3, self).__init__() 171 | self.size = size 172 | self.anchors = anchors / size 173 | self.anchor_masks = anchor_masks 174 | self.classes = classes 175 | 176 | self.darknet53 = Darknet(name='yolo_darknet') 177 | 178 | 179 | self.yoloconv1 = YoloConv(512) 180 | self.output1 = YoloOutput(512, len(self.anchor_masks[0]), classes) 181 | 182 | self.yoloconv2 = YoloConv(256, is_first=False) 183 | self.output2 = YoloOutput(256, len(self.anchor_masks[1]), classes) 184 | 185 | self.yoloconv3 = YoloConv(128, is_first=False) 186 | self.output3 = YoloOutput(128, len(self.anchor_masks[2]), classes) 187 | ''' 188 | 189 | self.yolo_blocks = [] 190 | self.yolo_outputs = [] 191 | self.yolo_num_layers = [512, 256, 128] 192 | 193 | for i in range(len(self.yolo_num_layers)): 194 | self.yolo_blocks.append(YoloConv(self.yolo_num_layers[i])) 195 | self.yolo_outputs.append(YoloOutput(self.yolo_num_layers[i], len(self.anchor_masks[i]), classes) 196 | 197 | ''' 198 | 199 | def call(self, x, training=True): 200 | 201 | route_1, route_2, x = self.darknet53(x, training=training) 202 | 203 | 204 | x = self.yoloconv1(x, training=training) 205 | output_0 = self.output1(x, training=training) 206 | 207 | x = self.yoloconv2((x, route_2), training=training) 208 | output_1 = self.output2(x, training=training) 209 | 210 | x = self.yoloconv3((x, route_1), training=training) 211 | output_2 = self.output3(x, training=training) 212 | ''' 213 | outputs = [] 214 | for i in range(len(self.yolo_num_layers)): 215 | x = yolo_blocks[i](x, training=training) 216 | outputs[i] = 217 | 218 | ''' 219 | 220 | boxes_0 = self.yolo_boxes(output_0, self.anchors[self.anchor_masks[0]], self.classes) 221 | boxes_1 = self.yolo_boxes(output_1, self.anchors[self.anchor_masks[1]], self.classes) 222 | boxes_2 = self.yolo_boxes(output_2, self.anchors[self.anchor_masks[2]], self.classes) 223 | 224 | if training : 225 | print('traing true') 226 | return (boxes_0, boxes_1, boxes_2) 227 | else: 228 | print('traing false') 229 | 230 | pred_0 = tf.reshape(boxes_0, (tf.shape(boxes_0)[0], len(self.anchor_masks[0]) * tf.shape(boxes_0)[1] * tf.shape(boxes_0)[2], 5 + self.classes)) 231 | pred_1 = tf.reshape(boxes_1, (tf.shape(boxes_1)[0], len(self.anchor_masks[1]) * tf.shape(boxes_1)[1] * tf.shape(boxes_1)[2], 5 + self.classes)) 232 | pred_2 = tf.reshape(boxes_2, (tf.shape(boxes_2)[0], len(self.anchor_masks[2]) * tf.shape(boxes_2)[1] * tf.shape(boxes_2)[2], 5 + self.classes)) 233 | 234 | boxes = tf.concat([pred_0, pred_1, pred_2], axis=1) 235 | 236 | return self.yolo_nms(boxes, self.anchors, self.anchor_masks, self.classes) 237 | 238 | 239 | 240 | def yolo_boxes(self, pred, anchors, classes): 241 | 242 | grid_size = tf.shape(pred)[1] 243 | 244 | #pred = tf.reshape(pred, (tf.shape(pred)[0], len(anchors) * grid_size * grid_size, 5 + classes)) 245 | 246 | box_centers, box_wh, confidence, class_probs = tf.split(pred, (2, 2, 1, classes), axis=-1) 247 | 248 | 249 | box_centers = tf.sigmoid(box_centers) 250 | confidence = tf.sigmoid(confidence) 251 | class_probs = tf.sigmoid(class_probs) 252 | 253 | pred_box = tf.concat((box_centers, box_wh), axis=-1) 254 | 255 | grid = tf.meshgrid(tf.range(grid_size), tf.range(grid_size)) 256 | grid = tf.expand_dims(tf.stack(grid, axis=-1), axis=2) 257 | 258 | box_centers = (box_centers + tf.cast(grid, tf.float32)) / tf.cast(grid_size, tf.float32) 259 | box_wh = tf.exp(box_wh) * anchors 260 | 261 | box_x1y1 = box_centers - box_wh /2 262 | box_x2y2 = box_centers + box_wh /2 263 | 264 | bbox = tf.concat([box_x1y1, box_x2y2], axis=-1) 265 | 266 | pred = tf.concat([bbox, confidence, class_probs], axis=-1) 267 | print(pred.shape) 268 | #logging.info(pred.shape) 269 | #pred = tf.reshape(pred, (tf.shape(pred)[0], len(anchors) * grid_size * grid_size, 5 + classes)) 270 | 271 | return pred 272 | 273 | def yolo_nms(self, boxes, anchors, masks, classes): 274 | 275 | bbox, confs, class_probs = tf.split(boxes, [4,1,-1], axis=-1) 276 | 277 | scores = confs * class_probs 278 | ''' 279 | logging.info(bbox.shape) 280 | bbox = tf.reshape(bbox, [-1, 4]) 281 | scores = tf.reshape(scores, [-1, classes]) 282 | 283 | mask = tf.greater_equal(scores, tf.constant(0.5)) 284 | 285 | boxes_list, label_list, score_list = [], [], [] 286 | 287 | for i in range(classes): 288 | 289 | filter_boxes = tf.boolean_mask(bbox, mask[:,i]) 290 | filter_scores = tf.boolean_mask(scores[:,i], mask[:,i]) 291 | nms_indices = tf.image.non_max_suppression(boxes=filter_boxes, 292 | scores=filter_scores, 293 | max_output_size=tf.constant(50), 294 | iou_threshold=tf.constant(0.5), name='nms_indices') 295 | 296 | label_list.append(tf.ones_like(tf.gather(filter_scores, nms_indices), 'int32')*i) 297 | boxes_list.append(tf.gather(filter_boxes, nms_indices)) 298 | score_list.append(tf.gather(filter_scores, nms_indices)) 299 | #print("=> nms time=%.2f ms" %(1000*(time.time()-start))) 300 | 301 | boxes = tf.concat(boxes_list, axis=0) 302 | scores = tf.concat(score_list, axis=0) 303 | label = tf.concat(label_list, axis=0) 304 | 305 | 306 | above 864ms 307 | 2000ms 308 | ''' 309 | start = time.time() 310 | boxes, scores, classes, valid_detections = tf.image.combined_non_max_suppression( 311 | boxes=tf.reshape(bbox, (tf.shape(bbox)[0], -1, 1, 4)), 312 | scores=tf.reshape(scores, (tf.shape(scores)[0], -1, tf.shape(scores)[-1])), 313 | max_output_size_per_class=10, 314 | max_total_size=50, 315 | iou_threshold=0.5, 316 | score_threshold=0.5 317 | ) 318 | logging.info("=> combined_non_max_suppression time=%.2f ms" %(1000*(time.time()-start))) 319 | 320 | return boxes, scores, classes, valid_detections 321 | 322 | 323 | #return boxes, scores, label 324 | -------------------------------------------------------------------------------- /tf2_demo.py: -------------------------------------------------------------------------------- 1 | import time 2 | import numpy as np 3 | import tensorflow as tf 4 | import argparse 5 | import yolo_v3 6 | from utils import load_coco_names, draw_boxes 7 | from PIL import Image 8 | 9 | IMG_H, IMG_W = 416, 416 10 | 11 | parser = argparse.ArgumentParser(description="YOLO-V3 weight convert") 12 | 13 | parser.add_argument("--class_names", type=str, default="coco.names", 14 | help="File with class names.") 15 | parser.add_argument("--input_img", type=str, default="./img_data/test.jpg", 16 | help="Input image file name.") 17 | parser.add_argument("--output_img", type=str, default="./img_data/out/test.jpg", 18 | help="Output image file name.") 19 | parser.add_argument("--data_format", type=str, default="channels_last", 20 | help="Data format: channels_first (gpu only) / channels_last.") 21 | parser.add_argument("--weights", type=str, default="./tf2_weights/yolov3", 22 | help="Tensorflow 2.0 Weights file.") 23 | parser.add_argument("--score_threshold", type=float, default=0.5, 24 | help="Desired Score Theshold") 25 | parser.add_argument("--iou_threshold", type=float, default=0.5, 26 | help="Desired IOU Theshold") 27 | 28 | def main(argv=None): 29 | 30 | img = Image.open(args.input_img) 31 | img_resized = np.asarray(img.resize(size=(IMG_H, IMG_W)), dtype=np.float32) 32 | img_resized = img_resized/255.0 33 | 34 | classes = load_coco_names(args.class_names) 35 | model = yolo_v3.YoloV3(len(classes), data_format=args.data_format) 36 | inputs = tf.keras.Input(shape=(IMG_H, IMG_W, 3)) 37 | output = model(inputs, training=False) 38 | print("=> loading weights ...") 39 | model.load_weights(args.weights) 40 | print("=> sucessfully loaded weights ") 41 | 42 | start = time.time() 43 | boxes, scores, labels = model.detector(img_resized[np.newaxis, ...], score_thresh=args.score_threshold, iou_thresh=args.iou_threshold) 44 | print("=> nms on the number of boxes= %d time=%.2f ms" %(len(boxes), 1000*(time.time()-start))) 45 | 46 | image = draw_boxes(img, boxes, scores, labels, classes, [IMG_H, IMG_W], show=True) 47 | image.save(args.output_img) 48 | 49 | if __name__ == '__main__': 50 | args = parser.parse_args() 51 | main(args) -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import numpy as np 4 | import tensorflow as tf 5 | from PIL import ImageDraw, Image 6 | import colorsys 7 | 8 | def load_weights(model, weights_file): 9 | """ 10 | Loads and converts pre-trained weights. 11 | :param model: Keras model 12 | :param weights_file: name of the binary file. 13 | :return total_params: if load successfully end else -1 14 | """ 15 | 16 | with open(weights_file, "rb") as fp: 17 | _ = np.fromfile(fp, dtype=np.int32, count=5) 18 | 19 | weights = np.fromfile(fp, dtype=np.float32) 20 | 21 | ptr = 0 22 | i = 0 23 | total_params = 0 24 | 25 | var_list = model.variables 26 | 27 | var_name_list = ['/'.join(x.name.split('/')[:-1]) for x in var_list] 28 | 29 | print(weights.shape) 30 | print(len(model.variables)) 31 | print(len(model.trainable_variables)) 32 | 33 | while i < len(model.trainable_variables): 34 | var1 = var_list[i] 35 | var2 = var_list[i + 1] 36 | 37 | print("%d - var1 : %s (%s)" %(i, var1.name.split('/')[-2], var1.name.split('/')[-1])) 38 | print("%d - var2 : %s (%s)" %(i, var2.name.split('/')[-2], var2.name.split('/')[-1])) 39 | 40 | # do something only if we process conv layer 41 | if 'conv2' in var1.name.split('/')[-2]: 42 | # check type of next layer 43 | if 'batch_normalization' in var2.name.split('/')[-2]: 44 | 45 | # load batch norm's gamma and beta params 46 | # beta bias 47 | # gamma kernel 48 | gamma, beta = var_list[i + 1:i + 3] 49 | 50 | # Find mean and variance of the same name 51 | layer_name = '/'.join(gamma.name.split('/')[:-1]) 52 | mean_index = i + 3 53 | mean_index += var_name_list[i+3:].index(layer_name) 54 | mean, var = var_list[mean_index:mean_index+2] 55 | 56 | batch_norm_vars = [beta, gamma, mean, var] 57 | 58 | for batch_norm_var in batch_norm_vars: 59 | shape = batch_norm_var.shape.as_list() 60 | num_params = np.prod(shape) 61 | batch_norm_var_weights = weights[ptr:ptr + num_params].reshape(shape) 62 | ptr += num_params 63 | 64 | batch_norm_var.assign(batch_norm_var_weights, name=batch_norm_var.name) 65 | 66 | # we move the pointer by 4, because we loaded 4 variables 67 | i += 2 68 | elif 'conv2' in var2.name.split('/')[-2]: 69 | # load biases 70 | print("%d - var2 : %s" %(i, var2.name.split('/')[-2])) 71 | bias = var2 72 | bias_shape = bias.shape.as_list() 73 | bias_params = np.prod(bias_shape) 74 | bias_weights = weights[ptr:ptr + 75 | bias_params].reshape(bias_shape) 76 | ptr += bias_params 77 | 78 | bias.assign(bias_weights, name=bias.name) 79 | 80 | # we loaded 1 variable 81 | i += 1 82 | # we can load weights of conv layer 83 | shape = var1.shape.as_list() 84 | num_params = np.prod(shape) 85 | var_weights = weights[ptr:ptr + num_params].reshape( 86 | (shape[3], shape[2], shape[0], shape[1])) 87 | 88 | # remember to transpose to column-major 89 | var_weights = np.transpose(var_weights, (2, 3, 1, 0)) 90 | ptr += num_params 91 | var1.assign(var_weights, name=var1.name) 92 | i += 1 93 | 94 | total_params = ptr 95 | 96 | return total_params if total_params == weights.shape else -1 97 | 98 | 99 | 100 | def load_coco_names(file_name): 101 | names = {} 102 | with open(file_name) as f: 103 | for id, name in enumerate(f): 104 | names[id] = name 105 | return names 106 | 107 | 108 | 109 | def letter_box_image(image: Image.Image, output_height: int, output_width: int, fill_value)-> np.ndarray: 110 | """ 111 | Fit image with final image with output_width and output_height. 112 | :param image: PILLOW Image object. 113 | :param output_height: width of the final image. 114 | :param output_width: height of the final image. 115 | :param fill_value: fill value for empty area. Can be uint8 or np.ndarray 116 | :return: numpy image fit within letterbox. dtype=uint8, shape=(output_height, output_width) 117 | """ 118 | 119 | height_ratio = float(output_height)/image.size[1] 120 | width_ratio = float(output_width)/image.size[0] 121 | fit_ratio = min(width_ratio, height_ratio) 122 | fit_height = int(image.size[1] * fit_ratio) 123 | fit_width = int(image.size[0] * fit_ratio) 124 | fit_image = np.asarray(image.resize((fit_width, fit_height), resample=Image.BILINEAR)) 125 | 126 | if isinstance(fill_value, int): 127 | fill_value = np.full(fit_image.shape[2], fill_value, fit_image.dtype) 128 | 129 | to_return = np.tile(fill_value, (output_height, output_width, 1)) 130 | pad_top = int(0.5 * (output_height - fit_height)) 131 | pad_left = int(0.5 * (output_width - fit_width)) 132 | to_return[pad_top:pad_top+fit_height, pad_left:pad_left+fit_width] = fit_image 133 | return to_return 134 | 135 | 136 | def letter_box_pos_to_original_pos(letter_pos, current_size, ori_image_size)-> np.ndarray: 137 | """ 138 | Parameters should have same shape and dimension space. (Width, Height) or (Height, Width) 139 | :param letter_pos: The current position within letterbox image including fill value area. 140 | :param current_size: The size of whole image including fill value area. 141 | :param ori_image_size: The size of image before being letter boxed. 142 | :return: 143 | """ 144 | letter_pos = np.asarray(letter_pos, dtype=np.float) 145 | current_size = np.asarray(current_size, dtype=np.float) 146 | ori_image_size = np.asarray(ori_image_size, dtype=np.float) 147 | final_ratio = min(current_size[0]/ori_image_size[0], current_size[1]/ori_image_size[1]) 148 | pad = 0.5 * (current_size - final_ratio * ori_image_size) 149 | pad = pad.astype(np.int32) 150 | to_return_pos = (letter_pos - pad) / final_ratio 151 | return to_return_pos 152 | 153 | 154 | def draw_boxes(image, boxes, scores, labels, classes, detection_size, 155 | font='./data/font/FiraMono-Medium.otf', show=True): 156 | """ 157 | :param boxes, shape of [num, 4] 158 | :param scores, shape of [num, ] 159 | :param labels, shape of [num, ] 160 | :param image, 161 | :param classes, the return list from the function `read_coco_names` 162 | """ 163 | if boxes is None: return image 164 | draw = ImageDraw.Draw(image) 165 | # draw settings 166 | hsv_tuples = [( x / len(classes), 0.9, 1.0) for x in range(len(classes))] 167 | colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples)) 168 | colors = list(map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), colors)) 169 | for i in range(len(labels)): # for each bounding box, do: 170 | bbox, score, label = boxes.numpy()[i], scores.numpy()[i], classes[labels.numpy()[i]] 171 | bbox_text = "%s %.2f" %(label, score) 172 | print(bbox_text) 173 | text_size = draw.textsize(bbox_text) 174 | # convert_to_original_size 175 | detection_size, original_size = np.array(detection_size), np.array(image.size) 176 | ratio = original_size / detection_size 177 | bbox = list((bbox.reshape(2,2) * ratio).reshape(-1)) 178 | 179 | #draw.rectangle(bbox, outline=colors[labels[i]], width=3) 180 | draw.rectangle(bbox, outline=colors[labels[i]]) 181 | text_origin = bbox[:2]-np.array([0, text_size[1]]) 182 | draw.rectangle([tuple(text_origin), tuple(text_origin+text_size)], fill=colors[labels[i]]) 183 | # # draw bbox 184 | draw.text(tuple(text_origin), bbox_text, fill=(0,0,0)) 185 | 186 | image.show() if show else None 187 | return image 188 | 189 | 190 | def draw_boxes2(image, boxes, scores, labels, nums, classes, detection_size, 191 | font='./data/font/FiraMono-Medium.otf', show=True): 192 | """ 193 | :param boxes, shape of [num, 4] 194 | :param scores, shape of [num, ] 195 | :param labels, shape of [num, ] 196 | :param image, 197 | :param classes, the return list from the function `read_coco_names` 198 | """ 199 | if boxes is None: return image 200 | draw = ImageDraw.Draw(image) 201 | # draw settings 202 | hsv_tuples = [( x / len(classes), 0.9, 1.0) for x in range(len(classes))] 203 | colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples)) 204 | colors = list(map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), colors)) 205 | for i in range(nums): # for each bounding box, do: 206 | bbox, score, label = boxes[i], scores[i], classes[labels[i]] 207 | bbox_text = "%s %.2f" %(label, score) 208 | print(bbox_text) 209 | text_size = draw.textsize(bbox_text) 210 | # convert_to_original_size 211 | detection_size, original_size = np.array(detection_size), np.array(image.size) 212 | ratio = original_size / detection_size 213 | bbox = list((bbox.reshape(2,2) * original_size).reshape(-1)) 214 | 215 | #draw.rectangle(bbox, outline=colors[labels[i]], width=3) 216 | draw.rectangle(bbox, outline=colors[int(labels[i])]) 217 | text_origin = bbox[:2]-np.array([0, text_size[1]]) 218 | draw.rectangle([tuple(text_origin), tuple(text_origin+text_size)], fill=colors[int(labels[i])]) 219 | # # draw bbox 220 | draw.text(tuple(text_origin), bbox_text, fill=(0,0,0)) 221 | 222 | image.show() if show else None 223 | return image 224 | 225 | 226 | def draw_boxes3(image, boxes, scores, labels, classes, detection_size, 227 | font='./data/font/FiraMono-Medium.otf', show=True): 228 | """ 229 | :param boxes, shape of [num, 4] 230 | :param scores, shape of [num, ] 231 | :param labels, shape of [num, ] 232 | :param image, 233 | :param classes, the return list from the function `read_coco_names` 234 | """ 235 | if boxes is None: return image 236 | draw = ImageDraw.Draw(image) 237 | # draw settings 238 | hsv_tuples = [( x / len(classes), 0.9, 1.0) for x in range(len(classes))] 239 | colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples)) 240 | colors = list(map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), colors)) 241 | for i in range(len(labels)): # for each bounding box, do: 242 | bbox, score, label = boxes.numpy()[i], scores.numpy()[i], classes[labels.numpy()[i]] 243 | bbox_text = "%s %.2f" %(label, score) 244 | print(bbox_text) 245 | text_size = draw.textsize(bbox_text) 246 | # convert_to_original_size 247 | detection_size, original_size = np.array(detection_size), np.array(image.size) 248 | ratio = original_size / detection_size 249 | bbox = list((bbox.reshape(2,2) * original_size).reshape(-1)) 250 | 251 | #draw.rectangle(bbox, outline=colors[labels[i]], width=3) 252 | draw.rectangle(bbox, outline=colors[labels[i]]) 253 | text_origin = bbox[:2]-np.array([0, text_size[1]]) 254 | draw.rectangle([tuple(text_origin), tuple(text_origin+text_size)], fill=colors[labels[i]]) 255 | # # draw bbox 256 | draw.text(tuple(text_origin), bbox_text, fill=(0,0,0)) 257 | 258 | image.show() if show else None 259 | return image 260 | 261 | # https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/using_your_own_dataset.md#conversion-script-outline-conversion-script-outline 262 | IMAGE_FEATURE_MAP = { 263 | 'image/width': tf.io.FixedLenFeature([], tf.int64), 264 | 'image/height': tf.io.FixedLenFeature([], tf.int64), 265 | 'image/filename': tf.io.FixedLenFeature([], tf.string), 266 | 'image/source_id': tf.io.FixedLenFeature([], tf.string), 267 | 'image/key/sha256': tf.io.FixedLenFeature([], tf.string), 268 | 'image/encoded': tf.io.FixedLenFeature([], tf.string), 269 | 'image/format': tf.io.FixedLenFeature([], tf.string), 270 | 'image/object/bbox/xmin': tf.io.VarLenFeature(tf.float32), 271 | 'image/object/bbox/ymin': tf.io.VarLenFeature(tf.float32), 272 | 'image/object/bbox/xmax': tf.io.VarLenFeature(tf.float32), 273 | 'image/object/bbox/ymax': tf.io.VarLenFeature(tf.float32), 274 | 'image/object/class/text': tf.io.VarLenFeature(tf.string), 275 | 'image/object/class/label': tf.io.VarLenFeature(tf.int64), 276 | 'image/object/difficult': tf.io.VarLenFeature(tf.int64), 277 | 'image/object/truncated': tf.io.VarLenFeature(tf.int64), 278 | 'image/object/view': tf.io.VarLenFeature(tf.string), 279 | } 280 | 281 | class Preprocess(object): 282 | 283 | def __init__(self, anchors, anchor_masks, train): 284 | #self.classes = classes 285 | self.train = train 286 | self.anchors = anchors / 416. 287 | self.anchor_masks = anchor_masks 288 | self.class_table = tf.lookup.StaticHashTable( 289 | tf.lookup.TextFileInitializer('./coco.names', tf.string, 0, tf.int64, -1, delimiter="\n"), -1) 290 | 291 | 292 | def __call__(self, tfrecord): 293 | 294 | 295 | x = tf.io.parse_single_example(tfrecord, IMAGE_FEATURE_MAP) 296 | x_train = tf.image.decode_jpeg(x['image/encoded'], channels=3) 297 | x_train = tf.image.resize(x_train, (416, 416)) 298 | x_train = x_train / 255. 299 | 300 | class_text = tf.sparse.to_dense(x['image/object/class/text'], default_value='') 301 | labels = tf.cast(self.class_table.lookup(class_text), tf.float32) 302 | y_train = tf.stack([tf.sparse.to_dense(x['image/object/bbox/xmin']), 303 | tf.sparse.to_dense(x['image/object/bbox/ymin']), 304 | tf.sparse.to_dense(x['image/object/bbox/xmax']), 305 | tf.sparse.to_dense(x['image/object/bbox/ymax']), 306 | labels], axis=1) 307 | 308 | # calculate anchor index for true boxes 309 | anchors = tf.cast(self.anchors, tf.float32) 310 | anchor_area = anchors[..., 0] * anchors[..., 1] 311 | box_wh = y_train[..., 2:4] - y_train[..., 0:2] 312 | box_wh = tf.tile(tf.expand_dims(box_wh, -2), 313 | (1, tf.shape(anchors)[0], 1)) 314 | box_area = box_wh[..., 0] * box_wh[..., 1] 315 | intersection = tf.minimum(box_wh[..., 0], anchors[..., 0]) * \ 316 | tf.minimum(box_wh[..., 1], anchors[..., 1]) 317 | iou = intersection / (box_area + anchor_area - intersection) 318 | anchor_idx = tf.cast(tf.argmax(iou, axis=-1), tf.float32) 319 | anchor_idx = tf.expand_dims(anchor_idx, axis=-1) 320 | 321 | y_train = tf.concat([y_train, anchor_idx], axis=-1) 322 | 323 | y_outs = [] 324 | grid_size = 13 325 | for anchor_idxs in anchor_masks: 326 | y_outs.append(self.transform_targets_for_output( 327 | y_train, grid_size, anchor_idxs, 80)) 328 | grid_size *= 2 329 | 330 | return x_train, tuple(y_outs) 331 | 332 | @tf.function 333 | def transform_targets_for_output(self, y_true, grid_size, anchor_idxs, classes): 334 | # y_true: (boxes, (x1, y1, x2, y2, class, best_anchor)) 335 | 336 | y_true_out = tf.zeros( 337 | (grid_size, grid_size, tf.shape(anchor_idxs)[0], 6)) 338 | 339 | anchor_idxs = tf.cast(anchor_idxs, tf.int32) 340 | 341 | indexes = tf.TensorArray(tf.int32, 0, dynamic_size=True) 342 | updates = tf.TensorArray(tf.float32, 0, dynamic_size=True) 343 | idx = 0 344 | 345 | y_true_shape = y_true.get_shape().as_list() 346 | for j in tf.range(tf.shape(y_true)[0]): 347 | #if tf.equal(y_true[j][2], 0): 348 | # continue 349 | 350 | anchor_eq = tf.equal(anchor_idxs, tf.cast(y_true[j][5], tf.int32)) 351 | 352 | if tf.reduce_any(anchor_eq): 353 | 354 | box = y_true[j][0:4] 355 | box_xy = (y_true[j][0:2] + y_true[j][2:4]) / 2 356 | 357 | anchor_idx = tf.cast(tf.where(anchor_eq), tf.int32) 358 | grid_xy = tf.cast(box_xy // (1/grid_size), tf.int32) 359 | 360 | # grid[y][x][anchor] = (tx, ty, bw, bh, obj, class) 361 | indexes = indexes.write( 362 | idx, [grid_xy[1], grid_xy[0], anchor_idx[0][0]]) 363 | updates = updates.write( 364 | idx, [box[0], box[1], box[2], box[3], 1, y_true[j][4]]) 365 | 366 | idx += 1 367 | 368 | return tf.tensor_scatter_nd_update( 369 | y_true_out, indexes.stack(), updates.stack()) 370 | 371 | def create_dataset(buffer_size, batch_size, data_format, anchors, anchor_mask, data_dir=None): 372 | 373 | train_file_pattern = '../models/research/object_detection/urban/coco/coco_train.record-?????-of-?????' 374 | val_file_pattern = '../models/research/object_detection/urban/coco/coco_val.record-?????-of-?????' 375 | 376 | train_files = tf.data.Dataset.list_files(train_file_pattern) 377 | val_files = tf.data.Dataset.list_files(val_file_pattern) 378 | 379 | train_dataset = tf.data.TFRecordDataset(train_files) 380 | val_dataset = tf.data.TFRecordDataset(val_files) 381 | 382 | # https://www.tensorflow.org/alpha/guide/data_performance 383 | #raw_dataset = files.interleave(tf.data.TFRecordDataset, cycle_length=2, 384 | # num_parallel_calls=tf.data.experimental.AUTOTUNE) 385 | #raw_dataset = files.interleave(tf.data.TFRecordDataset, cycle_length=2, 386 | # num_parallel_calls=tf.data.experimental.AUTOTUNE) 387 | 388 | preprocess_train = Preprocess(anchors, anchor_masks, train=True) 389 | preprocess_val = Preprocess(anchors, anchor_masks, train=False) 390 | 391 | train_dataset = train_dataset.map(preprocess_train) 392 | val_dataset = val_dataset.map(preprocess_train) 393 | 394 | return train_dataset, val_dataset -------------------------------------------------------------------------------- /yolo_v3.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import numpy as np 4 | import tensorflow as tf 5 | from tensorflow.keras import layers 6 | 7 | class ConvBlock(layers.Layer): 8 | 9 | def __init__(self, num_filters, kernel_size, strides=1, data_format='channels_last'): 10 | 11 | super(ConvBlock, self).__init__() 12 | self.kernel_size = kernel_size 13 | self.strides = strides 14 | self.data_format = data_format 15 | 16 | self.conv = layers.Conv2D(num_filters, 17 | kernel_size, 18 | strides, 19 | padding = ('same' if strides == 1 else 'valid'), 20 | data_format=data_format, 21 | use_bias=False) 22 | self.batchnorm = layers.BatchNormalization( 23 | axis = -1 if data_format == "channels_last" else 1, 24 | #momentum=0.99, 25 | momentum=0.9, 26 | #epsilon=0.01) 27 | epsilon=1e-05) 28 | self.leaky_relu = layers.LeakyReLU(alpha=0.1) 29 | 30 | def call(self, x, training=False): 31 | 32 | if self.strides > 1: 33 | x = self._fixed_padding(x, self.kernel_size) 34 | 35 | output = self.conv(x) 36 | output = self.batchnorm(output, training=training) 37 | output = self.leaky_relu(output) 38 | 39 | return output 40 | 41 | def _fixed_padding(self, inputs, kernel_size, mode='CONSTANT'): 42 | pad_total = kernel_size - 1 43 | pad_beg = pad_total // 2 44 | pad_end = pad_total - pad_beg 45 | 46 | if self.data_format == 'channels_first': 47 | padded_inputs = tf.pad(tensor=inputs, paddings=[[0, 0], [0, 0], [pad_beg, pad_end], [pad_beg, pad_end]], mode=mode) 48 | else: 49 | padded_inputs = tf.pad(tensor=inputs, paddings=[[0, 0], [pad_beg, pad_end], [pad_beg, pad_end], [0, 0]], mode=mode) 50 | 51 | return padded_inputs 52 | 53 | class DarknetBlock(layers.Layer): 54 | 55 | def __init__(self, num_filters, data_format='channels_last'): 56 | 57 | super(DarknetBlock, self).__init__() 58 | 59 | self.conv1 = ConvBlock(num_filters, 1, data_format=data_format) 60 | self.conv2 = ConvBlock(num_filters*2, 3, data_format=data_format) 61 | self.add = layers.Add() 62 | 63 | def call(self, x, training=False): 64 | 65 | shortcut = x 66 | output = self.conv1(x,training=training) 67 | output = self.conv2(output,training=training) 68 | output = self.add([output, shortcut]) 69 | 70 | return output 71 | 72 | class Darknet53(tf.keras.Model): 73 | 74 | def __init__(self, data_format='channels_last'): 75 | super(Darknet53, self).__init__() 76 | self.data_format = data_format 77 | self.num_blocks = [1, 2, 8, 8, 4] 78 | 79 | self.conv1 = ConvBlock(32, 3, 1, data_format) 80 | self.conv2 = ConvBlock(64, 3, 2, data_format) 81 | self.darkblock1 = DarknetBlock(32, data_format) 82 | self.conv3 = ConvBlock(128, 3, 2, data_format) 83 | 84 | self.darkblock2 = [DarknetBlock(64, data_format) for _ in range(self.num_blocks[1])] 85 | 86 | self.conv4 = ConvBlock(256, 3, 2, data_format) 87 | 88 | self.darkblock3 = [DarknetBlock(128, data_format) for _ in range(self.num_blocks[2])] 89 | 90 | self.conv5 = ConvBlock(512, 3, 2, data_format) 91 | 92 | self.darkblock4 = [DarknetBlock(256, data_format) for _ in range(self.num_blocks[3])] 93 | 94 | 95 | self.conv6 = ConvBlock(1024, 3, 2, data_format) 96 | 97 | self.darkblock5 = [DarknetBlock(512, data_format) for _ in range(self.num_blocks[4])] 98 | 99 | def call(self, x, training=True): 100 | 101 | output = self.conv1(x, training=training) 102 | output = self.conv2(output, training=training) 103 | output = self.darkblock1(output, training=training) 104 | output = self.conv3(output, training=training) 105 | 106 | for i in range(self.num_blocks[1]): 107 | output = self.darkblock2[i](output, training=training) 108 | 109 | output = self.conv4(output, training=training) 110 | 111 | for i in range(self.num_blocks[2]): 112 | output = self.darkblock3[i](output, training=training) 113 | 114 | route_1 = output 115 | output = self.conv5(output, training=training) 116 | 117 | for i in range(self.num_blocks[3]): 118 | output = self.darkblock4[i](output, training=training) 119 | 120 | route_2 = output 121 | 122 | output = self.conv6(output, training=training) 123 | 124 | for i in range(self.num_blocks[4]): 125 | output = self.darkblock5[i](output, training=training) 126 | 127 | return route_1, route_2, output 128 | 129 | class YoloBlock(tf.keras.Model): 130 | 131 | def __init__(self, num_filters, data_format='channels_last'): 132 | super(YoloBlock, self).__init__() 133 | self.num_filters = num_filters 134 | self.data_format = data_format 135 | 136 | self.conv1 = ConvBlock(num_filters, 1, data_format=data_format) 137 | self.conv2 = ConvBlock(num_filters*2, 3, data_format=data_format) 138 | self.conv3 = ConvBlock(num_filters, 1, data_format=data_format) 139 | self.conv4 = ConvBlock(num_filters*2, 3, data_format=data_format) 140 | self.conv5 = ConvBlock(num_filters, 1, data_format=data_format) 141 | 142 | self.conv6 = ConvBlock(num_filters*2, 3, data_format=data_format) 143 | 144 | def call(self, x, training=True): 145 | 146 | output = self.conv1(x, training=training) 147 | output = self.conv2(output, training=training) 148 | output = self.conv3(output, training=training) 149 | output = self.conv4(output, training=training) 150 | output = self.conv5(output, training=training) 151 | 152 | route = output 153 | 154 | output = self.conv6(output, training=training) 155 | 156 | return route, output 157 | 158 | class DetectionLayer(layers.Layer): 159 | 160 | def __init__(self, img_size, num_classes, anchors, data_format='channels_last'): 161 | 162 | super(DetectionLayer, self).__init__() 163 | 164 | self.num_anchors = len(anchors) 165 | self.img_size = img_size 166 | self.anchors = anchors 167 | self.data_format = data_format 168 | self.num_classes = num_classes 169 | 170 | self.conv1 = layers.Conv2D(self.num_anchors * (5 + self.num_classes), 1, strides=1, data_format=data_format, use_bias=True) 171 | 172 | 173 | def call(self, x): 174 | 175 | predictions = self.conv1(x) 176 | 177 | shape = predictions.get_shape().as_list() 178 | grid_size = self._get_size(shape) 179 | dim = grid_size[0] * grid_size[1] 180 | bbox_attrs = 5 + self.num_classes 181 | 182 | predictions = tf.reshape(predictions, [-1, self.num_anchors * dim, bbox_attrs]) 183 | 184 | stride = (self.img_size[0]//grid_size[0], self.img_size[1]//grid_size[1]) 185 | anchors = [(a[0] / stride[0], a[1] / stride[1]) for a in self.anchors] 186 | 187 | box_centers, box_sizes, confidence, classes = tf.split( 188 | predictions, [2, 2, 1, self.num_classes], axis=-1) 189 | 190 | box_centers = tf.nn.sigmoid(box_centers) 191 | #confidence = tf.nn.sigmoid(confidence) 192 | 193 | grid_x = tf.range(grid_size[0], dtype=tf.float32) 194 | grid_y = tf.range(grid_size[1], dtype=tf.float32) 195 | a, b = tf.meshgrid(grid_x, grid_y) 196 | 197 | x_offset = tf.reshape(a, (-1, 1)) 198 | y_offset = tf.reshape(b, (-1, 1)) 199 | 200 | x_y_offset = tf.concat([x_offset, y_offset], axis=-1) 201 | x_y_offset = tf.reshape(tf.tile(x_y_offset, [1, self.num_anchors]), [1, -1, 2]) 202 | 203 | box_centers = box_centers + x_y_offset 204 | 205 | anchors = tf.tile(anchors, [dim, 1]) 206 | box_sizes = tf.exp(box_sizes) * anchors 207 | 208 | """ 209 | https://blog.paperspace.com/how-to-implement-a-yolo-v3-object-detector-from-scratch-in-pytorch-part-3/ 210 | 211 | The last thing we want to do here, is to resize the detections map to the size of the input image. 212 | The bounding box attributes here are sized according to the feature map (say, 13 x 13). 213 | If the input image was 416 x 416, we multiply the attributes by 32, or the stride variable. 214 | """ 215 | box_centers = box_centers * stride 216 | box_sizes = box_sizes * stride 217 | 218 | detections = tf.concat([box_centers, box_sizes, confidence], axis=-1) 219 | 220 | #classes = tf.nn.sigmoid(classes) 221 | predictions = tf.concat([detections, classes], axis=-1) 222 | 223 | return predictions 224 | 225 | 226 | def _get_size(self, shape): 227 | if len(shape) == 4: 228 | shape = shape[1:] 229 | return shape[1:3] if self.data_format == 'channels_first' else shape[0:2] 230 | 231 | 232 | class YoloV3(tf.keras.Model): 233 | 234 | def __init__(self, num_classes, data_format): 235 | 236 | super(YoloV3, self).__init__() 237 | self.num_classes = num_classes 238 | self.data_format = data_format 239 | self.img_size = (416,416) 240 | 241 | self._ANCHORS = [(10, 13), (16, 30), (33, 23), 242 | (30, 61), (62, 45), (59, 119), 243 | (116, 90), (156, 198), (373, 326)] 244 | 245 | self.darket = Darknet53(data_format=self.data_format) 246 | 247 | self.yolo_block_512 = YoloBlock(512, data_format=self.data_format) 248 | self.detection1 = DetectionLayer(self.img_size, self.num_classes, self._ANCHORS[6:9], self.data_format) 249 | self.conv1 = ConvBlock(256, 1, data_format=self.data_format) 250 | self.upsampling1 = layers.UpSampling2D(data_format=self.data_format) 251 | 252 | self.yolo_block_256 = YoloBlock(256, data_format=self.data_format) 253 | self.detection2 = DetectionLayer(self.img_size, self.num_classes, self._ANCHORS[3:6], self.data_format) 254 | self.conv2 = ConvBlock(128, 1, data_format=self.data_format) 255 | self.upsampling2 = layers.UpSampling2D(data_format=self.data_format) 256 | 257 | self.yolo_block_128 = YoloBlock(128, data_format=self.data_format) 258 | self.detection3 = DetectionLayer(self.img_size, self.num_classes, self._ANCHORS[0:3], self.data_format) 259 | 260 | def call(self, x, training=True): 261 | 262 | self.img_size = x.get_shape().as_list()[1:3] 263 | 264 | axis = 1 265 | 266 | if self.data_format == 'channels_first': 267 | x = tf.transpose(x, [0, 3, 1, 2]) 268 | axis = -1 269 | 270 | route_1, route_2, inputs = self.darket(x, training=training) 271 | 272 | 273 | route, inputs = self.yolo_block_512(inputs, training=training) 274 | feature_map_1 = self.detection1(inputs) 275 | feature_map_1 = tf.identity(feature_map_1, name='feature_map_1') 276 | 277 | """ 278 | Authors take the feature map from 2 layers previous and upsample it by 2× 279 | They take a feature map from earlier in the network and merge it with 280 | our upsampled features using concatenation. 281 | 282 | This method allows us to get more meaningful semantic information 283 | from the upsampled features and finer-grained information 284 | from the earlier feature map. 285 | 286 | We then add a few more convolutional layers to process this combined feature map, 287 | and eventually predict a similar tensor, although now twice the size. 288 | 289 | We perform the same design one more time to predict boxes for the final scale. 290 | Thus our predictions for the 3rd scale benefit from all the prior computation 291 | as well as fine-grained features from early on in the network. 292 | """ 293 | 294 | inputs = self.conv1(route, training=training) 295 | inputs = self.upsampling1(inputs) 296 | 297 | inputs = tf.concat([inputs, route_2], axis=1 if self.data_format == 'channels_first' else 3) 298 | 299 | route, inputs = self.yolo_block_256(inputs, training=training) 300 | feature_map_2 = self.detection2(inputs) 301 | feature_map_2 = tf.identity(feature_map_2, name='feature_map_2') 302 | 303 | inputs = self.conv2(route, training=training) 304 | upsample_size = route_1.get_shape().as_list() 305 | inputs = self.upsampling2(inputs) 306 | inputs = tf.concat([inputs, route_1], axis=1 if self.data_format == 'channels_first' else 3) 307 | 308 | _, inputs = self.yolo_block_128(inputs, training=training) 309 | feature_map_3 = self.detection3(inputs) 310 | feature_map_3 = tf.identity(feature_map_3, name='feature_map_3') 311 | 312 | detections = tf.concat([feature_map_1, feature_map_2, feature_map_3], axis=1) 313 | detections = tf.identity(detections, name='detections') 314 | 315 | return detections 316 | 317 | def detector(self, x, max_boxes=50, score_thresh=0.3, iou_thresh=0.5): 318 | """ 319 | Note: given by predicted, compute the receptive field 320 | and get boxes, confs and class_probs 321 | input_argument: x -> [None, 1, 10647, 85], 322 | max_boxes 323 | score_thresh 324 | iou_thresh 325 | return : boxes, scores, label 326 | """ 327 | detections = self.predict(x) 328 | 329 | center_x, center_y, width, height, conf_logits, prob_logits = tf.split(detections, [1, 1, 1, 1, 1, -1], axis=-1) 330 | 331 | x0 = center_x - width / 2. 332 | y0 = center_y - height / 2. 333 | x1 = center_x + width / 2. 334 | y1 = center_y + height / 2. 335 | 336 | boxes = tf.concat([x0, y0, x1, y1], axis=-1) 337 | 338 | confs = tf.sigmoid(conf_logits) 339 | probs = tf.sigmoid(prob_logits) 340 | 341 | scores = confs * probs 342 | 343 | boxes = tf.reshape(boxes, [-1, 4]) 344 | scores = tf.reshape(scores, [-1, self.num_classes]) 345 | 346 | mask = tf.greater_equal(scores, tf.constant(score_thresh)) 347 | 348 | boxes_list, label_list, score_list = [], [], [] 349 | 350 | for i in range(self.num_classes): 351 | filter_boxes = tf.boolean_mask(boxes, mask[:,i]) 352 | filter_scores = tf.boolean_mask(scores[:,i], mask[:,i]) 353 | nms_indices = tf.image.non_max_suppression(boxes=filter_boxes, 354 | scores=filter_scores, 355 | max_output_size=max_boxes, 356 | iou_threshold=iou_thresh, name='nms_indices') 357 | label_list.append(tf.ones_like(tf.gather(filter_scores, nms_indices), 'int32')*i) 358 | boxes_list.append(tf.gather(filter_boxes, nms_indices)) 359 | score_list.append(tf.gather(filter_scores, nms_indices)) 360 | 361 | boxes = tf.concat(boxes_list, axis=0) 362 | scores = tf.concat(score_list, axis=0) 363 | label = tf.concat(label_list, axis=0) 364 | 365 | return boxes, scores, label 366 | --------------------------------------------------------------------------------