├── requirements.txt ├── class_list.txt ├── images ├── img_1.jpg ├── img_2.jpg ├── img_3.jpg ├── img_4.jpg ├── img_5.jpg ├── img_6.jpg ├── img_7.jpg ├── img_8.jpg ├── img_9.jpg ├── img_10.jpg ├── img_11.jpg └── img_12.jpg ├── bbox_txt ├── img_12.txt ├── img_10.txt ├── img_3.txt ├── img_4.txt ├── img_1.txt ├── img_2.txt └── img_11.txt ├── README.md ├── train_test_split.py ├── LICENSE └── run.py /requirements.txt: -------------------------------------------------------------------------------- 1 | opencv-python 2 | numpy -------------------------------------------------------------------------------- /class_list.txt: -------------------------------------------------------------------------------- 1 | closed_door 2 | opened_door 3 | bus 4 | number -------------------------------------------------------------------------------- /images/img_1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ivangrov/ModifiedOpenLabelling/HEAD/images/img_1.jpg -------------------------------------------------------------------------------- /images/img_2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ivangrov/ModifiedOpenLabelling/HEAD/images/img_2.jpg -------------------------------------------------------------------------------- /images/img_3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ivangrov/ModifiedOpenLabelling/HEAD/images/img_3.jpg -------------------------------------------------------------------------------- /images/img_4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ivangrov/ModifiedOpenLabelling/HEAD/images/img_4.jpg -------------------------------------------------------------------------------- /images/img_5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ivangrov/ModifiedOpenLabelling/HEAD/images/img_5.jpg -------------------------------------------------------------------------------- /images/img_6.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ivangrov/ModifiedOpenLabelling/HEAD/images/img_6.jpg -------------------------------------------------------------------------------- /images/img_7.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ivangrov/ModifiedOpenLabelling/HEAD/images/img_7.jpg -------------------------------------------------------------------------------- /images/img_8.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ivangrov/ModifiedOpenLabelling/HEAD/images/img_8.jpg -------------------------------------------------------------------------------- /images/img_9.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ivangrov/ModifiedOpenLabelling/HEAD/images/img_9.jpg -------------------------------------------------------------------------------- /images/img_10.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ivangrov/ModifiedOpenLabelling/HEAD/images/img_10.jpg -------------------------------------------------------------------------------- /images/img_11.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ivangrov/ModifiedOpenLabelling/HEAD/images/img_11.jpg -------------------------------------------------------------------------------- /images/img_12.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ivangrov/ModifiedOpenLabelling/HEAD/images/img_12.jpg -------------------------------------------------------------------------------- /bbox_txt/img_12.txt: -------------------------------------------------------------------------------- 1 | 2 0.56953125 0.5304449648711944 0.7578125 0.47540983606557374 2 | 3 0.24375 0.3805620608899297 0.03125 0.07259953161592506 3 | -------------------------------------------------------------------------------- /bbox_txt/img_10.txt: -------------------------------------------------------------------------------- 1 | 2 0.5453125 0.5176470588235295 0.853125 0.7294117647058823 2 | 0 0.51875 0.5329411764705883 0.159375 0.5858823529411765 3 | 2 0.07421875 0.5035294117647059 0.1453125 0.6211764705882353 4 | -------------------------------------------------------------------------------- /bbox_txt/img_3.txt: -------------------------------------------------------------------------------- 1 | 3 0.2828125 0.23055555555555557 0.0390625 0.06388888888888888 2 | 2 0.265625 0.40555555555555556 0.4203125 0.525 3 | 0 0.16796875 0.3972222222222222 0.034375 0.3111111111111111 4 | 0 0.085546875 0.38958333333333334 0.02734375 0.25972222222222224 5 | -------------------------------------------------------------------------------- /bbox_txt/img_4.txt: -------------------------------------------------------------------------------- 1 | 3 0.371875 0.5637651821862348 0.034375 0.0708502024291498 2 | 0 0.4609375 0.7773279352226721 0.0625 0.3076923076923077 3 | 0 0.6421875 0.7975708502024291 0.05625 0.2874493927125506 4 | 2 0.51640625 0.6194331983805668 0.7046875 0.6558704453441295 5 | -------------------------------------------------------------------------------- /bbox_txt/img_1.txt: -------------------------------------------------------------------------------- 1 | 2 0.49765625 0.46200607902735563 0.9640625 0.8693009118541033 2 | 3 0.2890625 0.1656534954407295 0.071875 0.13677811550151975 3 | 0 0.43125 0.5319148936170213 0.121875 0.7051671732522796 4 | 0 0.790625 0.5030395136778115 0.090625 0.5866261398176292 5 | -------------------------------------------------------------------------------- /bbox_txt/img_2.txt: -------------------------------------------------------------------------------- 1 | 2 0.54921875 0.5761124121779859 0.7078125 0.585480093676815 2 | 3 0.59609375 0.33840749414519905 0.0390625 0.11943793911007025 3 | 0 0.503125 0.5971896955503513 0.05625 0.4309133489461358 4 | 0 0.303125 0.607728337236534 0.034375 0.3442622950819672 5 | -------------------------------------------------------------------------------- /bbox_txt/img_11.txt: -------------------------------------------------------------------------------- 1 | 0 0.1765625 0.5354166666666667 0.209375 0.5763888888888888 2 | 1 0.831640625 0.5319444444444444 0.19453125 0.5472222222222223 3 | 2 0.499609375 0.5076388888888889 0.99140625 0.7736111111111111 4 | 3 0.325390625 0.4076388888888889 0.03671875 0.06805555555555555 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ModifiedOpenLabelling 2 | A modified version of https://github.com/Cartucho/OpenLabeling OpenLabelling tool. 3 | 4 | This repo is used as an example labelling tool in the [YOLOv5 Series](https://www.youtube.com/playlist?list=PLD80i8An1OEHEpJVjtujEb0lQWc0GhX_4). 5 | 6 | ![](https://user-images.githubusercontent.com/41416855/122698979-26331d00-d251-11eb-8d02-f4b479e8c0df.png) 7 | 8 | 9 | -------------------------------------------------------------------------------- /train_test_split.py: -------------------------------------------------------------------------------- 1 | import os 2 | import random 3 | import shutil 4 | 5 | imgList = os.listdir('images') 6 | 7 | 8 | #shuffling images 9 | random.shuffle(imgList) 10 | 11 | split = 0.2 12 | 13 | train_path = 'custom_dataset/train' 14 | val_path = 'custom_dataset/val' 15 | 16 | if os.path.isdir(train_path) == False: 17 | os.makedirs(train_path) 18 | if os.path.isdir(val_path) == False: 19 | os.makedirs(val_path) 20 | 21 | imgLen = len(imgList) 22 | print("Images in total: ", imgLen) 23 | 24 | train_images = imgList[: int(imgLen - (imgLen*split))] 25 | val_images = imgList[int(imgLen - (imgLen*split)):] 26 | print("Training images: ", len(train_images)) 27 | print("Validation images: ", len(val_images)) 28 | 29 | for imgName in train_images: 30 | og_path = os.path.join('images', imgName) 31 | target_path = os.path.join(train_path, imgName) 32 | 33 | shutil.copyfile(og_path, target_path) 34 | 35 | og_txt_path = os.path.join('bbox_txt', imgName.replace('.jpg', '.txt')) 36 | target_txt_path = os.path.join(train_path, imgName.replace('.jpg', '.txt')) 37 | 38 | shutil.copyfile(og_txt_path, target_txt_path) 39 | 40 | for imgName in val_images: 41 | og_path = os.path.join('images', imgName) 42 | target_path = os.path.join(val_path, imgName) 43 | 44 | shutil.copyfile(og_path, target_path) 45 | 46 | og_txt_path = os.path.join('bbox_txt', imgName.replace('.jpg', '.txt')) 47 | target_txt_path = os.path.join(val_path, imgName.replace('.jpg', '.txt')) 48 | 49 | shutil.copyfile(og_txt_path, target_txt_path) 50 | 51 | 52 | print("Done! ") 53 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /run.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import textwrap 3 | import glob 4 | import os 5 | 6 | import numpy as np 7 | import cv2 8 | 9 | bin_bbox_path = 'bin/bbox_txt' 10 | bin_images_path = 'bin/images' 11 | 12 | if os.path.isdir(bin_bbox_path) == False: 13 | os.makedirs(bin_bbox_path) 14 | if os.path.isdir(bin_images_path) == False: 15 | os.makedirs(bin_images_path) 16 | 17 | 18 | WITH_QT = True 19 | try: 20 | cv2.namedWindow("Test") 21 | cv2.displayOverlay("Test", "Test QT", 1000) 22 | except: 23 | WITH_QT = False 24 | cv2.destroyAllWindows() 25 | 26 | bbox_thickness = 2 27 | 28 | parser = argparse.ArgumentParser(description='YOLO v2 Bounding Box Tool') 29 | parser.add_argument('--format', default='yolo', type=str, choices=['yolo', 'voc'], help="Bounding box format") 30 | parser.add_argument('--sort', action='store_true', help="If true, shows images in order.") 31 | parser.add_argument('--cross-thickness', default='1', type=int, help="Cross thickness") 32 | parser.add_argument('--bbox-thickness', default=bbox_thickness, type=int, help="Bounding box thickness") 33 | args = parser.parse_args() 34 | 35 | class_index = 0 36 | img_index = 0 37 | img = None 38 | img_objects = [] 39 | bb_dir = "bbox_txt/" 40 | 41 | # selected bounding box 42 | prev_was_double_click = False 43 | is_bbox_selected = False 44 | selected_bbox = -1 45 | 46 | mouse_x = 0 47 | mouse_y = 0 48 | point_1 = (-1, -1) 49 | point_2 = (-1, -1) 50 | 51 | def change_img_index(x): 52 | global img_index, img 53 | img_index = x 54 | img_path = image_list[img_index] 55 | img = cv2.imread(img_path) 56 | if WITH_QT: 57 | cv2.displayOverlay(WINDOW_NAME, "Showing image " 58 | "" + str(img_index) + "/" 59 | "" + str(last_img_index), 1000) 60 | else: 61 | print("Showing image " 62 | "" + str(img_index) + "/" 63 | "" + str(last_img_index) + " path:" + img_path) 64 | 65 | def change_class_index(x): 66 | global class_index 67 | class_index = x 68 | if WITH_QT: 69 | cv2.displayOverlay(WINDOW_NAME, "Selected class " 70 | "" + str(class_index) + "/" 71 | "" + str(last_class_index) + "" 72 | "\n " + class_list[class_index],3000) 73 | else: 74 | print("Selected class :" + class_list[class_index]) 75 | 76 | 77 | def draw_edges(tmp_img): 78 | blur = cv2.bilateralFilter(tmp_img, 3, 75, 75) 79 | edges = cv2.Canny(blur, 150, 250, 3) 80 | edges = cv2.cvtColor(edges, cv2.COLOR_GRAY2RGB) 81 | # Overlap image and edges together 82 | tmp_img = np.bitwise_or(tmp_img, edges) 83 | #tmp_img = cv2.addWeighted(tmp_img, 1 - edges_val, edges, edges_val, 0) 84 | return tmp_img 85 | 86 | 87 | def decrease_index(current_index, last_index): 88 | current_index -= 1 89 | if current_index < 0: 90 | current_index = last_index 91 | return current_index 92 | 93 | 94 | def increase_index(current_index, last_index): 95 | current_index += 1 96 | if current_index > last_index: 97 | current_index = 0 98 | return current_index 99 | 100 | 101 | def draw_line(img, x, y, height, width, color): 102 | cv2.line(img, (x, 0), (x, height), color, thickness=args.cross_thickness) 103 | cv2.line(img, (0, y), (width, y), color, thickness=args.cross_thickness) 104 | 105 | 106 | def yolo_format(class_index, point_1, point_2, width, height): 107 | # YOLO wants everything normalized 108 | # Order: class x_center y_center x_width y_height 109 | x_center = (point_1[0] + point_2[0]) / float(2.0 * width) 110 | y_center = (point_1[1] + point_2[1]) / float(2.0 * height) 111 | x_width = float(abs(point_2[0] - point_1[0])) / width 112 | y_height = float(abs(point_2[1] - point_1[1])) / height 113 | return str(class_index) + " " + str(x_center) \ 114 | + " " + str(y_center) + " " + str(x_width) + " " + str(y_height) 115 | 116 | 117 | def voc_format(class_index, point_1, point_2): 118 | # Order: xmin ymin xmax ymax class 119 | # Top left pixel is (1, 1) in VOC 120 | xmin, ymin = min(point_1[0], point_2[0]) + 1, min(point_1[1], point_2[1]) + 1 121 | xmax, ymax = max(point_1[0], point_2[0]) + 1, max(point_1[1], point_2[1]) + 1 122 | items = map(str, [xmin, ymin, xmax, ymax, class_index]) 123 | return ' '.join(items) 124 | 125 | 126 | def get_txt_path(img_path): 127 | img_name = os.path.basename(os.path.normpath(img_path)) 128 | img_type = img_path.split('.')[-1] 129 | return bb_dir + img_name.replace(img_type, 'txt') 130 | 131 | 132 | def save_bb(txt_path, line): 133 | with open(txt_path, 'a') as myfile: 134 | myfile.write(line + "\n") # append line 135 | 136 | 137 | def delete_bb(txt_path, line_index): 138 | with open(txt_path, "r") as old_file: 139 | lines = old_file.readlines() 140 | 141 | with open(txt_path, "w") as new_file: 142 | counter = 0 143 | for line in lines: 144 | if counter is not line_index: 145 | new_file.write(line) 146 | counter += 1 147 | 148 | 149 | def yolo_to_x_y(x_center, y_center, x_width, y_height, width, height): 150 | x_center *= width 151 | y_center *= height 152 | x_width *= width 153 | y_height *= height 154 | x_width /= 2.0 155 | y_height /= 2.0 156 | return int(x_center - x_width), int(y_center - y_height), int(x_center + x_width), int(y_center + y_height) 157 | 158 | 159 | def draw_text(tmp_img, text, center, color, size): 160 | font = cv2.FONT_HERSHEY_SIMPLEX 161 | cv2.putText(tmp_img, text, center, font, 0.7, color, size, cv2.FONT_HERSHEY_COMPLEX_SMALL) 162 | return tmp_img 163 | 164 | def draw_bboxes_from_file(tmp_img, txt_path, width, height): 165 | global img_objects 166 | img_objects = [] 167 | if os.path.isfile(txt_path): 168 | with open(txt_path) as f: 169 | content = f.readlines() 170 | for line in content: 171 | values_str = line.split() 172 | if args.format == 'yolo': 173 | class_index, x_center, y_center, x_width, y_height = map(float, values_str) 174 | class_index = int(class_index) 175 | # convert yolo to points 176 | x1, y1, x2, y2 = yolo_to_x_y(x_center, y_center, x_width, y_height, width, height) 177 | if x_center == int(x_center): 178 | error = ("You selected the 'yolo' format but your labels " 179 | "seem to be in a different format. Consider " 180 | "removing your old label files.") 181 | raise Exception(textwrap.fill(error, 70)) 182 | elif args.format == 'voc': 183 | try: 184 | x1, y1, x2, y2, class_index = map(int, values_str) 185 | except ValueError: 186 | error = ("You selected the 'voc' format but your labels " 187 | "seem to be in a different format. Consider " 188 | "removing your old label files.") 189 | raise Exception(textwrap.fill(error, 70)) 190 | x1, y1, x2, y2 = x1-1, y1-1, x2-1, y2-1 191 | img_objects.append([class_index, x1, y1, x2, y2]) 192 | color = class_rgb[class_index].tolist() 193 | cv2.rectangle(tmp_img, (x1, y1), (x2, y2), color, thickness=args.bbox_thickness) 194 | tmp_img = draw_text(tmp_img, class_list[class_index], (x1, y1 - 5), color, args.bbox_thickness) 195 | return tmp_img 196 | 197 | 198 | def get_bbox_area(x1, y1, x2, y2): 199 | width = abs(x2 - x1) 200 | height = abs(y2 - y1) 201 | return width*height 202 | 203 | 204 | def set_selected_bbox(): 205 | global is_bbox_selected, selected_bbox 206 | smallest_area = -1 207 | # if clicked inside multiple bboxes selects the smallest one 208 | for idx, obj in enumerate(img_objects): 209 | ind, x1, y1, x2, y2 = obj 210 | if is_mouse_inside_points(x1, y1, x2, y2): 211 | is_bbox_selected = True 212 | tmp_area = get_bbox_area(x1, y1, x2, y2) 213 | if tmp_area < smallest_area or smallest_area == -1: 214 | smallest_area = tmp_area 215 | selected_bbox = idx 216 | 217 | 218 | def mouse_inside_delete_button(): 219 | for idx, obj in enumerate(img_objects): 220 | if idx == selected_bbox: 221 | ind, x1, y1, x2, y2 = obj 222 | x1_c, y1_c, x2_c, y2_c = get_close_icon(x1, y1, x2, y2) 223 | if is_mouse_inside_points(x1_c, y1_c, x2_c, y2_c): 224 | return True 225 | return False 226 | 227 | def delete_selected_bbox(): 228 | img_path = image_list[img_index] 229 | txt_path = get_txt_path(img_path) 230 | is_bbox_selected = False 231 | 232 | with open(txt_path, "r") as old_file: 233 | lines = old_file.readlines() 234 | 235 | with open(txt_path, "w") as new_file: 236 | counter = 0 237 | for line in lines: 238 | if counter is not selected_bbox: 239 | new_file.write(line) 240 | counter += 1 241 | 242 | # mouse callback function 243 | def mouse_listener(event, x, y, flags, param): 244 | global is_bbox_selected, prev_was_double_click, mouse_x, mouse_y, point_1, point_2 245 | 246 | if event == cv2.EVENT_MOUSEMOVE: 247 | mouse_x = x 248 | mouse_y = y 249 | elif event == cv2.EVENT_LBUTTONDBLCLK: 250 | prev_was_double_click = True 251 | #print("Double click") 252 | point_1 = (-1, -1) 253 | # if clicked inside a bounding box 254 | set_selected_bbox() 255 | # AlexeyGy change: delete via right-click 256 | elif event == cv2.EVENT_RBUTTONDOWN: 257 | set_selected_bbox() 258 | if is_bbox_selected: 259 | delete_selected_bbox() 260 | elif event == cv2.EVENT_LBUTTONDOWN: 261 | if prev_was_double_click: 262 | #print("Finish double click") 263 | prev_was_double_click = False 264 | 265 | #print("Normal left click") 266 | is_mouse_inside_delete_button = mouse_inside_delete_button() 267 | if point_1[0] == -1: 268 | if is_bbox_selected and is_mouse_inside_delete_button: 269 | # the user wants to delete the bbox 270 | #print("Delete bbox") 271 | delete_selected_bbox() 272 | else: 273 | is_bbox_selected = False 274 | # first click (start drawing a bounding box or delete an item) 275 | point_1 = (x, y) 276 | else: 277 | # minimal size for bounding box to avoid errors 278 | #!!!!!!!!!!!!!!!!!!!! 279 | threshold = 5 280 | if abs(x - point_1[0]) > threshold or abs(y - point_1[1]) > threshold: 281 | # second click 282 | point_2 = (x, y) 283 | 284 | 285 | def is_mouse_inside_points(x1, y1, x2, y2): 286 | return mouse_x > x1 and mouse_x < x2 and mouse_y > y1 and mouse_y < y2 287 | 288 | 289 | def get_close_icon(x1, y1, x2, y2): 290 | percentage = 0.05 291 | height = -1 292 | while height < 15 and percentage < 1.0: 293 | height = int((y2 - y1) * percentage) 294 | percentage += 0.1 295 | return (x2 - height), y1, x2, (y1 + height) 296 | 297 | 298 | def draw_close_icon(tmp_img, x1_c, y1_c, x2_c, y2_c): 299 | red = (0,0,255) 300 | cv2.rectangle(tmp_img, (x1_c + 1, y1_c - 1), (x2_c, y2_c), red, -1) 301 | white = (255, 255, 255) 302 | cv2.line(tmp_img, (x1_c, y1_c), (x2_c, y2_c), white, 2) 303 | cv2.line(tmp_img, (x1_c, y2_c), (x2_c, y1_c), white, 2) 304 | return tmp_img 305 | 306 | 307 | def draw_info_bb_selected(tmp_img): 308 | for idx, obj in enumerate(img_objects): 309 | ind, x1, y1, x2, y2 = obj 310 | if idx == selected_bbox: 311 | x1_c, y1_c, x2_c, y2_c = get_close_icon(x1, y1, x2, y2) 312 | draw_close_icon(tmp_img, x1_c, y1_c, x2_c, y2_c) 313 | return tmp_img 314 | 315 | def remove_bad_data(img_path, img_path_txt): 316 | img_name = img_path.split('/')[-1] 317 | txt_name = img_path_txt.split('/')[-1] 318 | 319 | os.rename(img_path,os.path.join('bin/images', img_name)) 320 | os.rename(img_path_txt,os.path.join('bin/bbox_txt', txt_name)) 321 | 322 | 323 | # load all images (with multiple extensions) from a directory using OpenCV 324 | img_dir = "images/" 325 | image_list = [] 326 | for f in os.listdir(img_dir): 327 | f_path = os.path.join(img_dir, f) 328 | test_img = cv2.imread(f_path) 329 | if test_img is not None: 330 | image_list.append(f_path) 331 | 332 | #print(image_list) 333 | 334 | #SORT OR NOT? 335 | #image_list.sort() 336 | #if not args.sort: 337 | #np.random.seed(123) # Keep random img order consistent 338 | #np.random.shuffle(image_list) 339 | 340 | last_img_index = len(image_list) - 1 341 | print(image_list) 342 | 343 | if not os.path.exists(bb_dir): 344 | os.makedirs(bb_dir) 345 | 346 | # create empty .txt file for each of the images if it doesn't exist already 347 | for img_path in image_list: 348 | txt_path = get_txt_path(img_path) 349 | if not os.path.isfile(txt_path): 350 | open(txt_path, 'a').close() 351 | 352 | # load class list 353 | with open('class_list.txt') as f: 354 | class_list = f.read().splitlines() 355 | #print(class_list) 356 | last_class_index = len(class_list) - 1 357 | 358 | # Make the class colors the same each session 359 | # The colors are in BGR order because we're using OpenCV 360 | class_rgb = [ 361 | (0, 0, 255), (255, 0, 0), (0, 255, 0), (255, 255, 0), (0, 255, 255), 362 | (255, 0, 255), (192, 192, 192), (128, 128, 128), (128, 0, 0), 363 | (128, 128, 0), (0, 128, 0), (128, 0, 128), (0, 128, 128), (0, 0, 128)] 364 | class_rgb = np.array(class_rgb) 365 | # If there are still more classes, add new colors randomly 366 | num_colors_missing = len(class_list) - len(class_rgb) 367 | if num_colors_missing > 0: 368 | more_colors = np.random.randint(0, 255+1, size=(num_colors_missing, 3)) 369 | class_rgb = np.vstack([class_rgb, more_colors]) 370 | 371 | # create window 372 | WINDOW_NAME = 'Bounding Box Labeler' 373 | cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_KEEPRATIO) 374 | #cv2.resizeWindow(WINDOW_NAME, 1000, 700) 375 | cv2.resizeWindow(WINDOW_NAME,500, 500) 376 | cv2.setMouseCallback(WINDOW_NAME, mouse_listener) 377 | 378 | # selected image 379 | TRACKBAR_IMG = 'Image' 380 | cv2.createTrackbar(TRACKBAR_IMG, WINDOW_NAME, 0, last_img_index, change_img_index) 381 | 382 | # selected class 383 | TRACKBAR_CLASS = 'Class' 384 | if last_class_index != 0: 385 | cv2.createTrackbar(TRACKBAR_CLASS, WINDOW_NAME, 0, last_class_index, change_class_index) 386 | 387 | # initialize 388 | change_img_index(0) 389 | edges_on = False 390 | 391 | if WITH_QT: 392 | cv2.displayOverlay(WINDOW_NAME, "Welcome!\n Press [h] for help.", 4000) 393 | print(" Welcome!\n Select the window and press [h] for help.") 394 | 395 | color = class_rgb[class_index].tolist() 396 | # loop 397 | while True: 398 | # clone the img 399 | tmp_img = img.copy() 400 | height, width = tmp_img.shape[:2] 401 | if edges_on == True: 402 | # draw edges 403 | tmp_img = draw_edges(tmp_img) 404 | 405 | 406 | #print('MOUSE',mouse_x, mouse_y) 407 | #print('POINTS', point_1, point_2) 408 | 409 | 410 | img_path = image_list[img_index] 411 | txt_path = get_txt_path(img_path) 412 | 413 | # draw already done bounding boxes 414 | tmp_img = draw_bboxes_from_file(tmp_img, txt_path, width, height) 415 | # if bounding box is selected add extra info 416 | if is_bbox_selected: 417 | tmp_img = draw_info_bb_selected(tmp_img) 418 | # if first click 419 | if point_1[0] != -1: 420 | color = class_rgb[class_index].tolist() 421 | # draw partial bbox 422 | cv2.rectangle(tmp_img, point_1, (mouse_x, mouse_y), color, thickness=args.bbox_thickness) 423 | # if second click 424 | if point_2[0] != -1: 425 | # save the bounding box 426 | if args.format == 'yolo': 427 | line = yolo_format(class_index, point_1, point_2, width, height) 428 | elif args.format == 'voc': 429 | line = voc_format(class_index, point_1, point_2) 430 | save_bb(txt_path, line) 431 | # reset the points 432 | point_1 = (-1, -1) 433 | point_2 = (-1, -1) 434 | else: 435 | if WITH_QT: 436 | cv2.displayOverlay(WINDOW_NAME, "Selected label: " + class_list[class_index] + "" 437 | "\nPress [w] or [s] to change.", 120) 438 | 439 | cv2.imshow(WINDOW_NAME, tmp_img) 440 | pressed_key = cv2.waitKey(50) 441 | 442 | """ Key Listeners START """ 443 | if pressed_key == ord('a') or pressed_key == ord('d'): 444 | # show previous image key listener 445 | if pressed_key == ord('a'): 446 | img_index = decrease_index(img_index, last_img_index) 447 | # show next image key listener 448 | elif pressed_key == ord('d'): 449 | img_index = increase_index(img_index, last_img_index) 450 | cv2.setTrackbarPos(TRACKBAR_IMG, WINDOW_NAME, img_index) 451 | 452 | elif pressed_key == ord('s') or pressed_key == ord('w'): 453 | # change down current class key listener 454 | if pressed_key == ord('s'): 455 | class_index = decrease_index(class_index, last_class_index) 456 | # change up current class key listener 457 | elif pressed_key == ord('w'): 458 | class_index = increase_index(class_index, last_class_index) 459 | color = class_rgb[class_index].tolist() 460 | draw_line(tmp_img, mouse_x, mouse_y, height, width, color) 461 | cv2.setTrackbarPos(TRACKBAR_CLASS, WINDOW_NAME, class_index) 462 | 463 | #REMOVING BAD DATA 464 | elif pressed_key == ord('r'): 465 | 466 | bad_path=img_path 467 | bad_text=txt_path 468 | 469 | 470 | img_index = increase_index(img_index, last_img_index) 471 | cv2.setTrackbarPos(TRACKBAR_IMG, WINDOW_NAME, img_index) 472 | 473 | 474 | 475 | if img_index == 0: 476 | del image_list[last_img_index] 477 | last_img_index = len(image_list) - 1 478 | 479 | remove_bad_data(bad_path, bad_text) 480 | 481 | img_index -= 0 482 | 483 | else: 484 | del image_list[img_index - 1] 485 | last_img_index = len(image_list)-1 486 | 487 | remove_bad_data(bad_path, bad_text) 488 | 489 | img_index -= 1 490 | 491 | cv2.setTrackbarPos(TRACKBAR_IMG, WINDOW_NAME, img_index) 492 | 493 | 494 | #Num class-switchin' 495 | elif pressed_key == ord('1'): 496 | 497 | if len(class_list)>=1: 498 | class_index=0 499 | color = class_rgb[class_index].tolist() 500 | draw_line(tmp_img, mouse_x, mouse_y, height, width, color) 501 | cv2.setTrackbarPos(TRACKBAR_CLASS, WINDOW_NAME, class_index) 502 | 503 | elif pressed_key == ord('2'): 504 | 505 | if len(class_list) >= 2: 506 | class_index=1 507 | color = class_rgb[class_index].tolist() 508 | draw_line(tmp_img, mouse_x, mouse_y, height, width, color) 509 | cv2.setTrackbarPos(TRACKBAR_CLASS, WINDOW_NAME, class_index) 510 | 511 | elif pressed_key == ord('3'): 512 | 513 | if len(class_list) >= 3: 514 | class_index=2 515 | color = class_rgb[class_index].tolist() 516 | draw_line(tmp_img, mouse_x, mouse_y, height, width, color) 517 | cv2.setTrackbarPos(TRACKBAR_CLASS, WINDOW_NAME, class_index) 518 | 519 | elif pressed_key == ord('4'): 520 | if len(class_list) >= 4: 521 | class_index=3 522 | color = class_rgb[class_index].tolist() 523 | draw_line(tmp_img, mouse_x, mouse_y, height, width, color) 524 | cv2.setTrackbarPos(TRACKBAR_CLASS, WINDOW_NAME, class_index) 525 | 526 | elif pressed_key == ord('5'): 527 | if len(class_list) >= 5: 528 | class_index=4 529 | color = class_rgb[class_index].tolist() 530 | draw_line(tmp_img, mouse_x, mouse_y, height, width, color) 531 | cv2.setTrackbarPos(TRACKBAR_CLASS, WINDOW_NAME, class_index) 532 | 533 | elif pressed_key == ord('6'): 534 | if len(class_list) >= 6: 535 | class_index=5 536 | color = class_rgb[class_index].tolist() 537 | draw_line(tmp_img, mouse_x, mouse_y, height, width, color) 538 | cv2.setTrackbarPos(TRACKBAR_CLASS, WINDOW_NAME, class_index) 539 | 540 | elif pressed_key == ord('7'): 541 | if len(class_list) >= 7: 542 | class_index=6 543 | color = class_rgb[class_index].tolist() 544 | draw_line(tmp_img, mouse_x, mouse_y, height, width, color) 545 | cv2.setTrackbarPos(TRACKBAR_CLASS, WINDOW_NAME, class_index) 546 | 547 | elif pressed_key == ord('8'): 548 | if len(class_list) >= 8: 549 | class_index=7 550 | color = class_rgb[class_index].tolist() 551 | draw_line(tmp_img, mouse_x, mouse_y, height, width, color) 552 | cv2.setTrackbarPos(TRACKBAR_CLASS, WINDOW_NAME, class_index) 553 | 554 | elif pressed_key == ord('9'): 555 | if len(class_list) >= 9: 556 | class_index=8 557 | color = class_rgb[class_index].tolist() 558 | draw_line(tmp_img, mouse_x, mouse_y, height, width, color) 559 | cv2.setTrackbarPos(TRACKBAR_CLASS, WINDOW_NAME, class_index) 560 | 561 | 562 | 563 | # help key listener 564 | elif pressed_key == ord('h'): 565 | if WITH_QT: 566 | cv2.displayOverlay(WINDOW_NAME, "[e] to show edges;\n" 567 | "[q] to quit;\n" 568 | "[a] or [d] to change Image;\n" 569 | "[w] or [s] to change Class.\n" 570 | "%s" % img_path, 6000) 571 | else: 572 | print("[e] to show edges;\n" 573 | "[q] to quit;\n" 574 | "[a] or [d] to change Image;\n" 575 | "[w] or [s] to change Class.\n" 576 | "%s" % img_path) 577 | # show edges key listener 578 | elif pressed_key == ord('e'): 579 | if edges_on == True: 580 | edges_on = False 581 | if WITH_QT: 582 | cv2.displayOverlay(WINDOW_NAME, "Edges turned OFF!", 1000) 583 | else: 584 | print("Edges turned OFF!") 585 | else: 586 | edges_on = True 587 | if WITH_QT: 588 | cv2.displayOverlay(WINDOW_NAME, "Edges turned ON!", 1000) 589 | else: 590 | print("Edges turned ON!") 591 | 592 | # quit key listener 593 | elif pressed_key == ord('q'): 594 | break 595 | """ Key Listeners END """ 596 | 597 | if WITH_QT: 598 | # if window gets closed then quit 599 | if cv2.getWindowProperty(WINDOW_NAME,cv2.WND_PROP_VISIBLE) < 1: 600 | break 601 | 602 | cv2.destroyAllWindows() 603 | --------------------------------------------------------------------------------