├── LICENSE ├── Object_Detection_Yolo.ipynb ├── detection.py ├── images ├── cover.jpg ├── kangaroo.png ├── traffic.jpg ├── zebra.jpg └── zebra_horse.jpg ├── model ├── yolov3.h5 └── yolov3.weights ├── readme.md ├── requirements.txt ├── samples └── result.png └── src ├── loadweights.py ├── nmsupress.py ├── process.py ├── setting.py └── utili.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 | -------------------------------------------------------------------------------- /detection.py: -------------------------------------------------------------------------------- 1 | 2 | import tensorflow as tf 3 | from tensorflow.keras.preprocessing.image import load_img 4 | from numpy import expand_dims 5 | from src.process import * 6 | from src.utili import draw_boxes 7 | from src.utili import encoder_dic 8 | from src.nmsupress import do_nms 9 | 10 | class Detector(): 11 | def __init__(self, 12 | model_path='./model/yolov3.h5'): 13 | self.model=tf.keras.models.load_model(model_path) 14 | # print(self.model.summary()) 15 | 16 | def _load_and_preprocess_image(self, image_path): 17 | image = tf.io.read_file(image_path) 18 | image_width, image_height = load_img(image_path).size 19 | image = tf.image.decode_jpeg(image, channels=3) 20 | image = tf.image.resize(image, [IMAGE_WIDTH,IMAGE_HEIGHT]) 21 | image /= 255 22 | 23 | return image, image_width, image_height 24 | 25 | def _predict(self, image): 26 | image_x = expand_dims(image, 0) 27 | yhat = self.model.predict(image_x) 28 | return yhat 29 | 30 | def _conver_to_boxes(self,yhat, image_width,image_height): 31 | boxes = list() 32 | for i in range(len(yhat)): 33 | boxes += decode_netout(yhat[i][0], ANCHORS[i], net_h=IMAGE_HEIGHT, net_w=IMAGE_WIDTH) 34 | 35 | for i in range(len(boxes)): 36 | x_offset, x_scale = (IMAGE_WIDTH - IMAGE_WIDTH) / 2. / IMAGE_HEIGHT, float(IMAGE_WIDTH) / IMAGE_WIDTH 37 | y_offset, y_scale = (IMAGE_HEIGHT - IMAGE_HEIGHT) / 2. / IMAGE_HEIGHT, float(IMAGE_HEIGHT) / IMAGE_HEIGHT 38 | boxes[i].xmin = int((boxes[i].xmin - x_offset) / x_scale * image_width) 39 | boxes[i].xmax = int((boxes[i].xmax - x_offset) / x_scale * image_width) 40 | boxes[i].ymin = int((boxes[i].ymin - y_offset) / y_scale * image_height) 41 | boxes[i].ymax = int((boxes[i].ymax - y_offset) / y_scale * image_height) 42 | 43 | return boxes 44 | 45 | def do_detect(self,image_path): 46 | image, image_width, image_height=self._load_and_preprocess_image(image_path) 47 | yhat=self._predict(image) 48 | boxes=self._conver_to_boxes(yhat,image_width,image_height) 49 | dic = encoder_dic(box_filter(boxes)) 50 | valid_data=do_nms(dic,NMS_SCORE) 51 | draw_boxes(image_path,valid_data) 52 | 53 | if __name__=="__main__": 54 | path = input("Where is your image path? \n") 55 | D=Detector() 56 | D.do_detect(image_path=path) -------------------------------------------------------------------------------- /images/cover.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/patrick013/Object-Detection---Yolov3/1adade1efeb2f9b386a1f3c7366e28efac0d5cbf/images/cover.jpg -------------------------------------------------------------------------------- /images/kangaroo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/patrick013/Object-Detection---Yolov3/1adade1efeb2f9b386a1f3c7366e28efac0d5cbf/images/kangaroo.png -------------------------------------------------------------------------------- /images/traffic.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/patrick013/Object-Detection---Yolov3/1adade1efeb2f9b386a1f3c7366e28efac0d5cbf/images/traffic.jpg -------------------------------------------------------------------------------- /images/zebra.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/patrick013/Object-Detection---Yolov3/1adade1efeb2f9b386a1f3c7366e28efac0d5cbf/images/zebra.jpg -------------------------------------------------------------------------------- /images/zebra_horse.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/patrick013/Object-Detection---Yolov3/1adade1efeb2f9b386a1f3c7366e28efac0d5cbf/images/zebra_horse.jpg -------------------------------------------------------------------------------- /model/yolov3.h5: -------------------------------------------------------------------------------- 1 | version https://git-lfs.github.com/spec/v1 2 | oid sha256:d3580711bc8dc6d2fa80df2ff4fdac78b45eab249467076e70d74258d34a586d 3 | size 248671752 4 | -------------------------------------------------------------------------------- /model/yolov3.weights: -------------------------------------------------------------------------------- 1 | version https://git-lfs.github.com/spec/v1 2 | oid sha256:523e4e69e1d015393a1b0a441cef1d9c7659e3eb2d7e15f793f060a21b32f297 3 | size 248007048 4 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Object Detection with Yolov3 2 | 3 | 4 | ![cover](https://bitmovin.com/wp-content/uploads/2019/08/Object_detection_Blog_Image_Q3_19.jpg) 5 | 6 | Object detection is a computer vision task that involves both localizing one or more objects within an image and classifying each object in the image. 7 | 8 | It is a challenging computer vision task that requires both successful object localization in order to locate and draw a bounding box around each object in an image, and object classification to predict the correct class of object that was localized. 9 | Yolo is a faster object detection algorithm in computer vision and first described by Joseph Redmon, Santosh Divvala, Ross Girshick and Ali Farhadi in ['You Only Look Once: Unified, Real-Time Object Detection'](https://arxiv.org/abs/1506.02640) 10 | 11 | This notebook implements an object detection based on a pre-trained model - [YOLOv3 Pre-trained Weights (yolov3.weights) (237 MB)](https://pjreddie.com/media/files/yolov3.weights). The model architecture is called a “DarkNet” and was originally loosely based on the VGG-16 model. 12 | 13 | ## Predition 14 | ``` 15 | python detection.py 16 | >>> Where is your image path? 17 | >>> images/traffic.jpg 18 | ``` 19 | ![result](https://raw.githubusercontent.com/patrick013/Object-Detection---Yolov3/master/samples/result.png) 20 | 21 | ## Details 22 | For details of this project please check [notebook](https://github.com/patrick013/Object-Detection---Yolov3/blob/master/Object_Detection_Yolo.ipynb) 23 | 24 | ## Reference 25 | > - Redmon, J., Divvala, S., Girshick, R., & Farhadi, A. (2016). You only look once: Unified, real-time object detection. In Proceedings of the IEEE conference on computer vision and pattern recognition (pp. 779-788). 26 | > - Darknet, https://github.com/pjreddie/darknet 27 | > - YOLO3 (Detection, Training, and Evaluation), https://github.com/experiencor/keras-yolo3 28 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | tensorflow 2 | numpy 3 | matplotlib -------------------------------------------------------------------------------- /samples/result.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/patrick013/Object-Detection---Yolov3/1adade1efeb2f9b386a1f3c7366e28efac0d5cbf/samples/result.png -------------------------------------------------------------------------------- /src/loadweights.py: -------------------------------------------------------------------------------- 1 | 2 | import struct 3 | import numpy as np 4 | from tensorflow.keras.layers import Conv2D 5 | from tensorflow.keras.layers import Input 6 | from tensorflow.keras.layers import BatchNormalization 7 | from tensorflow.keras.layers import LeakyReLU 8 | from tensorflow.keras.layers import ZeroPadding2D 9 | from tensorflow.keras.layers import UpSampling2D 10 | from tensorflow.keras.layers import add, concatenate 11 | from tensorflow.keras.models import Model 12 | 13 | """ 14 | # This cell aims to build a yolo model and load a pre-trained weights into the mode. 15 | # based on https://github.com/experiencor/keras-yolo3 16 | """ 17 | 18 | 19 | def _conv_block(inp, convs, skip=True): 20 | x = inp 21 | count = 0 22 | for conv in convs: 23 | if count == (len(convs) - 2) and skip: 24 | skip_connection = x 25 | count += 1 26 | if conv['stride'] > 1: x = ZeroPadding2D(((1, 0), (1, 0)))(x) # peculiar padding as darknet prefer left and top 27 | x = Conv2D(conv['filter'], 28 | conv['kernel'], 29 | strides=conv['stride'], 30 | padding='valid' if conv['stride'] > 1 else 'same', # peculiar padding as darknet prefer left and top 31 | name='conv_' + str(conv['layer_idx']), 32 | use_bias=False if conv['bnorm'] else True)(x) 33 | if conv['bnorm']: x = BatchNormalization(epsilon=0.001, name='bnorm_' + str(conv['layer_idx']))(x) 34 | if conv['leaky']: x = LeakyReLU(alpha=0.1, name='leaky_' + str(conv['layer_idx']))(x) 35 | return add([skip_connection, x]) if skip else x 36 | 37 | 38 | def make_yolov3_model(): 39 | input_image = Input(shape=(None, None, 3)) 40 | # Layer 0 => 4 41 | x = _conv_block(input_image, 42 | [{'filter': 32, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 0}, 43 | {'filter': 64, 'kernel': 3, 'stride': 2, 'bnorm': True, 'leaky': True, 'layer_idx': 1}, 44 | {'filter': 32, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 2}, 45 | {'filter': 64, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 3}]) 46 | # Layer 5 => 8 47 | x = _conv_block(x, [{'filter': 128, 'kernel': 3, 'stride': 2, 'bnorm': True, 'leaky': True, 'layer_idx': 5}, 48 | {'filter': 64, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 6}, 49 | {'filter': 128, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 7}]) 50 | # Layer 9 => 11 51 | x = _conv_block(x, [{'filter': 64, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 9}, 52 | {'filter': 128, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 10}]) 53 | # Layer 12 => 15 54 | x = _conv_block(x, [{'filter': 256, 'kernel': 3, 'stride': 2, 'bnorm': True, 'leaky': True, 'layer_idx': 12}, 55 | {'filter': 128, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 13}, 56 | {'filter': 256, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 14}]) 57 | # Layer 16 => 36 58 | for i in range(7): 59 | x = _conv_block(x, [ 60 | {'filter': 128, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 16 + i * 3}, 61 | {'filter': 256, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 17 + i * 3}]) 62 | skip_36 = x 63 | # Layer 37 => 40 64 | x = _conv_block(x, [{'filter': 512, 'kernel': 3, 'stride': 2, 'bnorm': True, 'leaky': True, 'layer_idx': 37}, 65 | {'filter': 256, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 38}, 66 | {'filter': 512, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 39}]) 67 | # Layer 41 => 61 68 | for i in range(7): 69 | x = _conv_block(x, [ 70 | {'filter': 256, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 41 + i * 3}, 71 | {'filter': 512, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 42 + i * 3}]) 72 | skip_61 = x 73 | # Layer 62 => 65 74 | x = _conv_block(x, [{'filter': 1024, 'kernel': 3, 'stride': 2, 'bnorm': True, 'leaky': True, 'layer_idx': 62}, 75 | {'filter': 512, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 63}, 76 | {'filter': 1024, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 64}]) 77 | # Layer 66 => 74 78 | for i in range(3): 79 | x = _conv_block(x, [ 80 | {'filter': 512, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 66 + i * 3}, 81 | {'filter': 1024, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 67 + i * 3}]) 82 | # Layer 75 => 79 83 | x = _conv_block(x, [{'filter': 512, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 75}, 84 | {'filter': 1024, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 76}, 85 | {'filter': 512, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 77}, 86 | {'filter': 1024, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 78}, 87 | {'filter': 512, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 79}], 88 | skip=False) 89 | # Layer 80 => 82 90 | yolo_82 = _conv_block(x, [{'filter': 1024, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 80}, 91 | {'filter': 255, 'kernel': 1, 'stride': 1, 'bnorm': False, 'leaky': False, 92 | 'layer_idx': 81}], skip=False) 93 | # Layer 83 => 86 94 | x = _conv_block(x, [{'filter': 256, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 84}], 95 | skip=False) 96 | x = UpSampling2D(2)(x) 97 | x = concatenate([x, skip_61]) 98 | # Layer 87 => 91 99 | x = _conv_block(x, [{'filter': 256, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 87}, 100 | {'filter': 512, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 88}, 101 | {'filter': 256, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 89}, 102 | {'filter': 512, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 90}, 103 | {'filter': 256, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 91}], 104 | skip=False) 105 | # Layer 92 => 94 106 | yolo_94 = _conv_block(x, [{'filter': 512, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 92}, 107 | {'filter': 255, 'kernel': 1, 'stride': 1, 'bnorm': False, 'leaky': False, 108 | 'layer_idx': 93}], skip=False) 109 | # Layer 95 => 98 110 | x = _conv_block(x, [{'filter': 128, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 96}], 111 | skip=False) 112 | x = UpSampling2D(2)(x) 113 | x = concatenate([x, skip_36]) 114 | # Layer 99 => 106 115 | yolo_106 = _conv_block(x, [{'filter': 128, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 99}, 116 | {'filter': 256, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 117 | 'layer_idx': 100}, 118 | {'filter': 128, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 119 | 'layer_idx': 101}, 120 | {'filter': 256, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 121 | 'layer_idx': 102}, 122 | {'filter': 128, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 123 | 'layer_idx': 103}, 124 | {'filter': 256, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 125 | 'layer_idx': 104}, 126 | {'filter': 255, 'kernel': 1, 'stride': 1, 'bnorm': False, 'leaky': False, 127 | 'layer_idx': 105}], skip=False) 128 | model = Model(input_image, [yolo_82, yolo_94, yolo_106]) 129 | return model 130 | 131 | 132 | class WeightReader: 133 | def __init__(self, weight_file): 134 | with open(weight_file, 'rb') as w_f: 135 | major, = struct.unpack('i', w_f.read(4)) 136 | minor, = struct.unpack('i', w_f.read(4)) 137 | revision, = struct.unpack('i', w_f.read(4)) 138 | if (major * 10 + minor) >= 2 and major < 1000 and minor < 1000: 139 | w_f.read(8) 140 | else: 141 | w_f.read(4) 142 | transpose = (major > 1000) or (minor > 1000) 143 | binary = w_f.read() 144 | self.offset = 0 145 | self.all_weights = np.frombuffer(binary, dtype='float32') 146 | 147 | def read_bytes(self, size): 148 | self.offset = self.offset + size 149 | return self.all_weights[self.offset - size:self.offset] 150 | 151 | def load_weights(self, model): 152 | for i in range(106): 153 | try: 154 | conv_layer = model.get_layer('conv_' + str(i)) 155 | print("loading weights of convolution #" + str(i)) 156 | if i not in [81, 93, 105]: 157 | norm_layer = model.get_layer('bnorm_' + str(i)) 158 | size = np.prod(norm_layer.get_weights()[0].shape) 159 | beta = self.read_bytes(size) # bias 160 | gamma = self.read_bytes(size) # scale 161 | mean = self.read_bytes(size) # mean 162 | var = self.read_bytes(size) # variance 163 | weights = norm_layer.set_weights([gamma, beta, mean, var]) 164 | if len(conv_layer.get_weights()) > 1: 165 | bias = self.read_bytes(np.prod(conv_layer.get_weights()[1].shape)) 166 | kernel = self.read_bytes(np.prod(conv_layer.get_weights()[0].shape)) 167 | kernel = kernel.reshape(list(reversed(conv_layer.get_weights()[0].shape))) 168 | kernel = kernel.transpose([2, 3, 1, 0]) 169 | conv_layer.set_weights([kernel, bias]) 170 | else: 171 | kernel = self.read_bytes(np.prod(conv_layer.get_weights()[0].shape)) 172 | kernel = kernel.reshape(list(reversed(conv_layer.get_weights()[0].shape))) 173 | kernel = kernel.transpose([2, 3, 1, 0]) 174 | conv_layer.set_weights([kernel]) 175 | except ValueError: 176 | print("no convolution #" + str(i)) 177 | 178 | def reset(self): 179 | self.offset = 0 -------------------------------------------------------------------------------- /src/nmsupress.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | def _decode_box_coor(box): 4 | return (box.xmin, box.ymin, box.xmax, box.ymax) 5 | 6 | 7 | def _iou(box1, box2): 8 | (box1_x1, box1_y1, box1_x2, box1_y2) = _decode_box_coor(box1) 9 | (box2_x1, box2_y1, box2_x2, box2_y2) = _decode_box_coor(box2) 10 | 11 | xi1 = max(box1_x1, box2_x1) 12 | yi1 = max(box1_y1, box2_y1) 13 | xi2 = min(box1_x2, box2_x2) 14 | yi2 = min(box1_y2, box2_y2) 15 | inter_width = xi2 - xi1 16 | inter_height = yi2 - yi1 17 | inter_area = max(inter_height, 0) * max(inter_width, 0) 18 | 19 | box1_area = (box1_x2 - box1_x1) * (box1_y2 - box1_y1) 20 | box2_area = (box2_x2 - box2_x1) * (box2_y2 - box2_y1) 21 | union_area = box1_area + box2_area - inter_area 22 | 23 | iou = inter_area / union_area 24 | 25 | return iou 26 | 27 | def do_nms(data_dic, nms_thresh): 28 | final_boxes, final_scores, final_labels = list(), list(), list() 29 | for label in data_dic: 30 | scores_boxes = sorted(data_dic[label], reverse=True) 31 | for i in range(len(scores_boxes)): 32 | if scores_boxes[i][2] == 'removed': continue 33 | for j in range(i + 1, len(scores_boxes)): 34 | if _iou(scores_boxes[i][1], scores_boxes[j][1]) >= nms_thresh: 35 | scores_boxes[j][2] = "removed" 36 | 37 | for e in scores_boxes: 38 | print(label + ' ' + str(e[0]) + " status: " + e[2]) 39 | if e[2] == 'kept': 40 | final_boxes.append(e[1]) 41 | final_labels.append(label) 42 | final_scores.append(e[0]) 43 | 44 | return (final_boxes, final_labels, final_scores) 45 | 46 | 47 | -------------------------------------------------------------------------------- /src/process.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from .setting import * 3 | class BoundBox: 4 | ''' 5 | Objects of boxes. (xmin,ymin) represents the upleft coordinate of the box while (xmax,ymax) means downright one. 6 | ''' 7 | 8 | def __init__(self, xmin, ymin, xmax, ymax, objness=None, classes=None): 9 | self.xmin = xmin 10 | self.ymin = ymin 11 | self.xmax = xmax 12 | self.ymax = ymax 13 | self.objness = objness 14 | self.classes = classes 15 | self.label = -1 16 | self.score = -1 17 | 18 | def get_label(self): 19 | if self.label == -1: 20 | self.label = np.argmax(self.classes) 21 | 22 | return self.label 23 | 24 | def get_score(self): 25 | if self.score == -1: 26 | self.score = self.classes[self.get_label()] 27 | 28 | return self.score 29 | 30 | def _sigmoid(x): 31 | return 1. / (1. + np.exp(-x)) 32 | 33 | 34 | def decode_netout(netout, anchors, net_h, net_w): 35 | grid_h, grid_w = netout.shape[:2] 36 | nb_box = 3 37 | netout = netout.reshape((grid_h, grid_w, nb_box, -1)) 38 | nb_class = netout.shape[-1] - 5 39 | boxes = [] 40 | netout[..., :2] = _sigmoid(netout[..., :2]) 41 | netout[..., 4:] = _sigmoid(netout[..., 4:]) 42 | netout[..., 5:] = netout[..., 4][..., np.newaxis] * netout[..., 5:] 43 | 44 | for i in range(grid_h * grid_w): 45 | row = i / grid_w 46 | col = i % grid_w 47 | for b in range(nb_box): 48 | # 4th element is objectness score 49 | objectness = netout[int(row)][int(col)][b][4] 50 | # if(objectness.all() <= obj_thresh): continue 51 | # first 4 elements are x, y, w, and h 52 | x, y, w, h = netout[int(row)][int(col)][b][:4] 53 | x = (col + x) / grid_w # center position, unit: image width 54 | y = (row + y) / grid_h # center position, unit: image height 55 | w = anchors[2 * b + 0] * np.exp(w) / net_w # unit: image width 56 | h = anchors[2 * b + 1] * np.exp(h) / net_h # unit: image height 57 | # last elements are class probabilities 58 | classes = netout[int(row)][col][b][5:] 59 | box = BoundBox(x - w / 2, y - h / 2, x + w / 2, y + h / 2, objectness, classes) 60 | boxes.append(box) 61 | return boxes 62 | 63 | 64 | def box_filter(boxes, labels=LABELS, threshold_socre=THRED_SOCRE): 65 | valid_boxes = [] 66 | valid_labels = [] 67 | valid_scores = [] 68 | for box in boxes: 69 | for i in range(len(labels)): 70 | if box.classes[i] > threshold_socre: 71 | valid_boxes.append(box) 72 | valid_labels.append(labels[i]) 73 | valid_scores.append(box.classes[i]) 74 | 75 | return (valid_boxes, valid_labels, valid_scores) -------------------------------------------------------------------------------- /src/setting.py: -------------------------------------------------------------------------------- 1 | 2 | LABELS = ["person", "bicycle", "car", "motorbike", "aeroplane", "bus", "train", "truck", 3 | "boat", "traffic light", "fire hydrant", "stop sign", "parking meter", "bench", 4 | "bird", "cat", "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", 5 | "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", 6 | "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard", 7 | "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", 8 | "apple", "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", 9 | "chair", "sofa", "pottedplant", "bed", "diningtable", "toilet", "tvmonitor", "laptop", "mouse", 10 | "remote", "keyboard", "cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", 11 | "book", "clock", "vase", "scissors", "teddy bear", "hair drier", "toothbrush"] 12 | ANCHORS = [[116,90, 156,198, 373,326], [30,61, 62,45, 59,119], [10,13, 16,30, 33,23]] 13 | IMAGE_WIDTH=416 14 | IMAGE_HEIGHT=416 15 | THRED_SOCRE=0.6 16 | NMS_SCORE=0.7 17 | 18 | -------------------------------------------------------------------------------- /src/utili.py: -------------------------------------------------------------------------------- 1 | 2 | from matplotlib import pyplot 3 | from matplotlib.patches import Rectangle 4 | 5 | def encoder_dic(valid_data): 6 | data_dic = {} 7 | (valid_boxes, valid_labels, valid_scores) = valid_data 8 | for box, label, score in zip(valid_boxes, valid_labels, valid_scores): 9 | if label not in data_dic: 10 | data_dic[label] = [[score, box, 'kept']] 11 | else: 12 | data_dic[label].append([score, box, 'kept']) 13 | 14 | return data_dic 15 | 16 | def draw_boxes(filename, valid_data): 17 | 18 | data = pyplot.imread(filename) 19 | pyplot.imshow(data) 20 | ax = pyplot.gca() 21 | for i in range(len(valid_data[0])): 22 | box = valid_data[0][i] 23 | y1, x1, y2, x2 = box.ymin, box.xmin, box.ymax, box.xmax 24 | width, height = x2 - x1, y2 - y1 25 | rect = Rectangle((x1, y1), width, height, fill=False, color='white') 26 | ax.add_patch(rect) 27 | print(valid_data[1][i], valid_data[2][i]) 28 | label = "%s (%.3f)" % (valid_data[1][i], valid_data[2][i]) 29 | pyplot.text(x1, y1, label, color='white') 30 | pyplot.show() --------------------------------------------------------------------------------