megadetector 10.0.15__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. megadetector/__init__.py +0 -0
  2. megadetector/api/__init__.py +0 -0
  3. megadetector/api/batch_processing/integration/digiKam/setup.py +6 -0
  4. megadetector/api/batch_processing/integration/digiKam/xmp_integration.py +465 -0
  5. megadetector/api/batch_processing/integration/eMammal/test_scripts/config_template.py +5 -0
  6. megadetector/api/batch_processing/integration/eMammal/test_scripts/push_annotations_to_emammal.py +125 -0
  7. megadetector/api/batch_processing/integration/eMammal/test_scripts/select_images_for_testing.py +55 -0
  8. megadetector/classification/__init__.py +0 -0
  9. megadetector/classification/aggregate_classifier_probs.py +108 -0
  10. megadetector/classification/analyze_failed_images.py +227 -0
  11. megadetector/classification/cache_batchapi_outputs.py +198 -0
  12. megadetector/classification/create_classification_dataset.py +626 -0
  13. megadetector/classification/crop_detections.py +516 -0
  14. megadetector/classification/csv_to_json.py +226 -0
  15. megadetector/classification/detect_and_crop.py +853 -0
  16. megadetector/classification/efficientnet/__init__.py +9 -0
  17. megadetector/classification/efficientnet/model.py +415 -0
  18. megadetector/classification/efficientnet/utils.py +608 -0
  19. megadetector/classification/evaluate_model.py +520 -0
  20. megadetector/classification/identify_mislabeled_candidates.py +152 -0
  21. megadetector/classification/json_to_azcopy_list.py +63 -0
  22. megadetector/classification/json_validator.py +696 -0
  23. megadetector/classification/map_classification_categories.py +276 -0
  24. megadetector/classification/merge_classification_detection_output.py +509 -0
  25. megadetector/classification/prepare_classification_script.py +194 -0
  26. megadetector/classification/prepare_classification_script_mc.py +228 -0
  27. megadetector/classification/run_classifier.py +287 -0
  28. megadetector/classification/save_mislabeled.py +110 -0
  29. megadetector/classification/train_classifier.py +827 -0
  30. megadetector/classification/train_classifier_tf.py +725 -0
  31. megadetector/classification/train_utils.py +323 -0
  32. megadetector/data_management/__init__.py +0 -0
  33. megadetector/data_management/animl_to_md.py +161 -0
  34. megadetector/data_management/annotations/__init__.py +0 -0
  35. megadetector/data_management/annotations/annotation_constants.py +33 -0
  36. megadetector/data_management/camtrap_dp_to_coco.py +270 -0
  37. megadetector/data_management/cct_json_utils.py +566 -0
  38. megadetector/data_management/cct_to_md.py +184 -0
  39. megadetector/data_management/cct_to_wi.py +293 -0
  40. megadetector/data_management/coco_to_labelme.py +284 -0
  41. megadetector/data_management/coco_to_yolo.py +701 -0
  42. megadetector/data_management/databases/__init__.py +0 -0
  43. megadetector/data_management/databases/add_width_and_height_to_db.py +107 -0
  44. megadetector/data_management/databases/combine_coco_camera_traps_files.py +210 -0
  45. megadetector/data_management/databases/integrity_check_json_db.py +563 -0
  46. megadetector/data_management/databases/subset_json_db.py +195 -0
  47. megadetector/data_management/generate_crops_from_cct.py +200 -0
  48. megadetector/data_management/get_image_sizes.py +164 -0
  49. megadetector/data_management/labelme_to_coco.py +559 -0
  50. megadetector/data_management/labelme_to_yolo.py +349 -0
  51. megadetector/data_management/lila/__init__.py +0 -0
  52. megadetector/data_management/lila/create_lila_blank_set.py +556 -0
  53. megadetector/data_management/lila/create_lila_test_set.py +192 -0
  54. megadetector/data_management/lila/create_links_to_md_results_files.py +106 -0
  55. megadetector/data_management/lila/download_lila_subset.py +182 -0
  56. megadetector/data_management/lila/generate_lila_per_image_labels.py +777 -0
  57. megadetector/data_management/lila/get_lila_annotation_counts.py +174 -0
  58. megadetector/data_management/lila/get_lila_image_counts.py +112 -0
  59. megadetector/data_management/lila/lila_common.py +319 -0
  60. megadetector/data_management/lila/test_lila_metadata_urls.py +164 -0
  61. megadetector/data_management/mewc_to_md.py +344 -0
  62. megadetector/data_management/ocr_tools.py +873 -0
  63. megadetector/data_management/read_exif.py +964 -0
  64. megadetector/data_management/remap_coco_categories.py +195 -0
  65. megadetector/data_management/remove_exif.py +156 -0
  66. megadetector/data_management/rename_images.py +194 -0
  67. megadetector/data_management/resize_coco_dataset.py +665 -0
  68. megadetector/data_management/speciesnet_to_md.py +41 -0
  69. megadetector/data_management/wi_download_csv_to_coco.py +247 -0
  70. megadetector/data_management/yolo_output_to_md_output.py +594 -0
  71. megadetector/data_management/yolo_to_coco.py +984 -0
  72. megadetector/data_management/zamba_to_md.py +188 -0
  73. megadetector/detection/__init__.py +0 -0
  74. megadetector/detection/change_detection.py +840 -0
  75. megadetector/detection/process_video.py +479 -0
  76. megadetector/detection/pytorch_detector.py +1451 -0
  77. megadetector/detection/run_detector.py +1267 -0
  78. megadetector/detection/run_detector_batch.py +2172 -0
  79. megadetector/detection/run_inference_with_yolov5_val.py +1314 -0
  80. megadetector/detection/run_md_and_speciesnet.py +1604 -0
  81. megadetector/detection/run_tiled_inference.py +1044 -0
  82. megadetector/detection/tf_detector.py +209 -0
  83. megadetector/detection/video_utils.py +1379 -0
  84. megadetector/postprocessing/__init__.py +0 -0
  85. megadetector/postprocessing/add_max_conf.py +72 -0
  86. megadetector/postprocessing/categorize_detections_by_size.py +166 -0
  87. megadetector/postprocessing/classification_postprocessing.py +1943 -0
  88. megadetector/postprocessing/combine_batch_outputs.py +249 -0
  89. megadetector/postprocessing/compare_batch_results.py +2110 -0
  90. megadetector/postprocessing/convert_output_format.py +403 -0
  91. megadetector/postprocessing/create_crop_folder.py +629 -0
  92. megadetector/postprocessing/detector_calibration.py +570 -0
  93. megadetector/postprocessing/generate_csv_report.py +522 -0
  94. megadetector/postprocessing/load_api_results.py +223 -0
  95. megadetector/postprocessing/md_to_coco.py +428 -0
  96. megadetector/postprocessing/md_to_labelme.py +351 -0
  97. megadetector/postprocessing/md_to_wi.py +41 -0
  98. megadetector/postprocessing/merge_detections.py +392 -0
  99. megadetector/postprocessing/postprocess_batch_results.py +2140 -0
  100. megadetector/postprocessing/remap_detection_categories.py +226 -0
  101. megadetector/postprocessing/render_detection_confusion_matrix.py +677 -0
  102. megadetector/postprocessing/repeat_detection_elimination/find_repeat_detections.py +206 -0
  103. megadetector/postprocessing/repeat_detection_elimination/remove_repeat_detections.py +82 -0
  104. megadetector/postprocessing/repeat_detection_elimination/repeat_detections_core.py +1665 -0
  105. megadetector/postprocessing/separate_detections_into_folders.py +795 -0
  106. megadetector/postprocessing/subset_json_detector_output.py +964 -0
  107. megadetector/postprocessing/top_folders_to_bottom.py +238 -0
  108. megadetector/postprocessing/validate_batch_results.py +332 -0
  109. megadetector/taxonomy_mapping/__init__.py +0 -0
  110. megadetector/taxonomy_mapping/map_lila_taxonomy_to_wi_taxonomy.py +491 -0
  111. megadetector/taxonomy_mapping/map_new_lila_datasets.py +211 -0
  112. megadetector/taxonomy_mapping/prepare_lila_taxonomy_release.py +165 -0
  113. megadetector/taxonomy_mapping/preview_lila_taxonomy.py +543 -0
  114. megadetector/taxonomy_mapping/retrieve_sample_image.py +71 -0
  115. megadetector/taxonomy_mapping/simple_image_download.py +231 -0
  116. megadetector/taxonomy_mapping/species_lookup.py +1008 -0
  117. megadetector/taxonomy_mapping/taxonomy_csv_checker.py +159 -0
  118. megadetector/taxonomy_mapping/taxonomy_graph.py +346 -0
  119. megadetector/taxonomy_mapping/validate_lila_category_mappings.py +83 -0
  120. megadetector/tests/__init__.py +0 -0
  121. megadetector/tests/test_nms_synthetic.py +335 -0
  122. megadetector/utils/__init__.py +0 -0
  123. megadetector/utils/ct_utils.py +1857 -0
  124. megadetector/utils/directory_listing.py +199 -0
  125. megadetector/utils/extract_frames_from_video.py +307 -0
  126. megadetector/utils/gpu_test.py +125 -0
  127. megadetector/utils/md_tests.py +2072 -0
  128. megadetector/utils/path_utils.py +2872 -0
  129. megadetector/utils/process_utils.py +172 -0
  130. megadetector/utils/split_locations_into_train_val.py +237 -0
  131. megadetector/utils/string_utils.py +234 -0
  132. megadetector/utils/url_utils.py +825 -0
  133. megadetector/utils/wi_platform_utils.py +968 -0
  134. megadetector/utils/wi_taxonomy_utils.py +1766 -0
  135. megadetector/utils/write_html_image_list.py +239 -0
  136. megadetector/visualization/__init__.py +0 -0
  137. megadetector/visualization/plot_utils.py +309 -0
  138. megadetector/visualization/render_images_with_thumbnails.py +243 -0
  139. megadetector/visualization/visualization_utils.py +1973 -0
  140. megadetector/visualization/visualize_db.py +630 -0
  141. megadetector/visualization/visualize_detector_output.py +498 -0
  142. megadetector/visualization/visualize_video_output.py +705 -0
  143. megadetector-10.0.15.dist-info/METADATA +115 -0
  144. megadetector-10.0.15.dist-info/RECORD +147 -0
  145. megadetector-10.0.15.dist-info/WHEEL +5 -0
  146. megadetector-10.0.15.dist-info/licenses/LICENSE +19 -0
  147. megadetector-10.0.15.dist-info/top_level.txt +1 -0
File without changes
File without changes
@@ -0,0 +1,6 @@
1
+ from cx_Freeze import setup, Executable
2
+
3
+ setup(name = "XMP Integration" ,
4
+ version = "3.0" ,
5
+ description = "XMP metadata writer" ,
6
+ executables = [Executable("xmp_integration.py")])
@@ -0,0 +1,465 @@
1
+ #
2
+ # xmp_integration.py
3
+ #
4
+ # Tools for loading MegaDetector batch API results into XMP metadata, specifically
5
+ # for consumption in digiKam:
6
+ #
7
+ # https://cran.r-project.org/web/packages/camtrapR/vignettes/camtrapr2.html
8
+ #
9
+
10
+ #%% Imports and constants
11
+
12
+ import argparse
13
+ import tkinter
14
+ from tkinter import ttk, messagebox, filedialog
15
+
16
+ import inspect
17
+ import os
18
+ import sys
19
+ import json
20
+ import pyexiv2 # type: ignore
21
+ import ntpath
22
+ import threading
23
+ import traceback
24
+
25
+ from tqdm import tqdm
26
+ from multiprocessing import Pool
27
+ from multiprocessing.pool import ThreadPool
28
+ from functools import partial
29
+
30
+ category_mapping = {'person': 'Human', 'animal': 'Animal', 'vehicle': 'Vehicle'}
31
+
32
+
33
+ #%% Class definitions
34
+
35
+ class xmp_gui:
36
+
37
+ root = None
38
+ textarea_min_threshold = None
39
+ textarea_status = None
40
+ textarea_remove_path = None
41
+ textarea_rename_conf = None
42
+ textarea_rename_cats = None
43
+ num_threads = 1
44
+
45
+ class xmp_integration_options:
46
+
47
+ # Folder where images are stored
48
+ image_folder = None
49
+
50
+ # .json file containing MegaDetector output
51
+ input_file = None
52
+
53
+ # String to remove from all path names, typically representing a
54
+ # prefix that was added during MegaDetector processing
55
+ remove_path = None
56
+
57
+ # Optionally *rename* (not copy) all images that have no detections
58
+ # above [rename_conf] for the categories in rename_cats from x.jpg to
59
+ # x.check.jpg
60
+ rename_conf = None
61
+
62
+ # Comma-deleted list of category names (or "all") to apply the rename_conf
63
+ # behavior to.
64
+ rename_cats = None
65
+
66
+ # Minimum detection threshold (applies to all classes, defaults to None,
67
+ # i.e. 0.0
68
+ min_threshold = None
69
+ num_threads = 1
70
+ xmp_gui = None
71
+
72
+
73
+ #%% Functions
74
+
75
+ def write_status(options,s):
76
+
77
+ if options.xmp_gui is None:
78
+ return
79
+ options.xmp_gui.textarea_status.configure(state="normal")
80
+ options.xmp_gui.textarea_status.insert(tkinter.END, s + '\n')
81
+ options.xmp_gui.textarea_status.configure(state="disabled")
82
+
83
+
84
+ n_images_processed = 0
85
+
86
+ def update_xmp_metadata(categories, options, rename_cats, n_images, image):
87
+ """
88
+ Update the XMP metadata for a single image
89
+ """
90
+
91
+ # Relative image path
92
+ filename = ''
93
+
94
+ # Absolute image path
95
+ img_path = ''
96
+
97
+ global n_images_processed
98
+
99
+ try:
100
+
101
+ filename = image['file']
102
+ if options.remove_path != None and len(options.remove_path) > 0:
103
+ filename = filename.replace(options.remove_path, '')
104
+ img_path = os.path.join(options.image_folder, filename)
105
+ assert os.path.isfile(img_path), 'Image {} not found'.format(img_path)
106
+
107
+ # List of categories to write to XMP metadata
108
+ image_categories = []
109
+
110
+ # Categories with above-threshold detections present for
111
+ # this image
112
+ original_image_cats = []
113
+
114
+ # Maximum confidence for each category
115
+ original_image_cats_conf = {}
116
+
117
+ for detection in image['detections']:
118
+
119
+ cat = category_mapping[categories[detection['category']]]
120
+
121
+ # Have we already added this to the list of categories to
122
+ # write out to this image?
123
+ if cat not in image_categories:
124
+
125
+ # If we're supposed to compare to a threshold...
126
+ if len(options.min_threshold) > 0 and \
127
+ options.min_threshold != None:
128
+ if float(detection['conf']) > float(options.min_threshold):
129
+ image_categories.append(cat)
130
+ original_image_cats.append(
131
+ categories[detection['category']])
132
+
133
+ # Else we treat *any* detection as valid...
134
+ else:
135
+ image_categories.append(cat)
136
+ original_image_cats.append(categories[detection['category']])
137
+
138
+ # Keep track of the highest-confidence detection for this class
139
+ if options.min_threshold != None and \
140
+ len(options.min_threshold) > 0 and \
141
+ detection['conf'] > \
142
+ original_image_cats_conf.get(
143
+ categories[detection['category']], 0):
144
+
145
+ original_image_cats_conf[categories[detection['category']]] = \
146
+ detection['conf']
147
+
148
+ img = pyexiv2.Image(r'{0}'.format(img_path))
149
+ img.modify_xmp({'Xmp.lr.hierarchicalSubject': image_categories})
150
+
151
+ # If we're doing the rename/.check behavior...
152
+ if not (options.rename_conf is None and options.rename_cats is None):
153
+
154
+ matching_cats = set(rename_cats).intersection(set(original_image_cats))
155
+ is_conf_low = False
156
+ if options.min_threshold != None and len(options.min_threshold) > 0:
157
+ for matching_cat in matching_cats:
158
+ if original_image_cats_conf[matching_cat] < float(options.rename_conf):
159
+ is_conf_low = True
160
+ if options.min_threshold != None and \
161
+ len(options.min_threshold) > 0 and \
162
+ len(image['detections']) == 0 or \
163
+ (len(options.rename_conf) > 0 and \
164
+ is_conf_low is True and \
165
+ len(matching_cats) > 0):
166
+
167
+ parent_folder = os.path.dirname(img_path)
168
+ file_name = ntpath.basename(img_path)
169
+ manual_file_name = file_name.split('.')[0]+'_check' + '.' + file_name.split('.')[1]
170
+ os.rename(img_path, os.path.join(parent_folder, manual_file_name))
171
+
172
+ if options.xmp_gui is not None:
173
+
174
+ n_images_processed += 1
175
+ percentage = round((n_images_processed)/n_images*100)
176
+ options.xmp_gui.progress_bar['value'] = percentage
177
+ options.xmp_gui.root.update_idletasks()
178
+ options.xmp_gui.style.configure('text.Horizontal.Tprogress_bar',
179
+ text='{:g} %'.format(percentage))
180
+
181
+ except Exception as e:
182
+
183
+ s = 'Error processing image {}: {}'.format(filename,str(e))
184
+ print(s)
185
+ traceback.print_exc()
186
+ write_status(options,s)
187
+
188
+ if False:
189
+
190
+ # Legacy code to rename files where XMP writing failed
191
+ parent_folder = os.path.dirname(img_path)
192
+ file_name = ntpath.basename(img_path)
193
+ failed_file_name = file_name.split('.')[0]+'_failed' + '.' + file_name.split('.')[1]
194
+ os.rename(img_path, os.path.join(
195
+ parent_folder, failed_file_name))
196
+
197
+
198
+ def process_input_data(options):
199
+ """
200
+ Main function to loop over images and modify XMP data
201
+ """
202
+
203
+ if options.xmp_gui is not None:
204
+
205
+ if (options.image_folder is None) or (len(options.image_folder) == 0):
206
+ tkinter.messagebox.showerror(title='Error', message='Image folder is not selected')
207
+ sys.exit()
208
+ if (options.input_file is None) or (len(options.input_file) == 0):
209
+ tkinter.messagebox.showerror(
210
+ title='Error', message='No MegaDetector .json file selected')
211
+ sys.exit()
212
+ options.remove_path = options.xmp_gui.textarea_remove_path.get()
213
+ options.rename_conf = options.xmp_gui.textarea_rename_conf.get()
214
+ options.rename_cats = options.xmp_gui.textarea_rename_cats.get()
215
+ options.num_threads = options.xmp_gui.textarea_num_threads.get()
216
+ options.min_threshold = options.xmp_gui.textarea_min_threshold.get()
217
+
218
+ try:
219
+
220
+ with open(options.input_file, 'r') as f:
221
+ data = f.read()
222
+
223
+ data = json.loads(data)
224
+ categories = data['detection_categories']
225
+
226
+ images = data['images']
227
+ n_images = len(images)
228
+ if not (options.rename_conf is None and options.rename_cats is None):
229
+ rename_cats = options.rename_cats.split(",")
230
+ if rename_cats[0] == 'all':
231
+ rename_cats = list(category_mapping.keys())
232
+ else:
233
+ rename_cats = []
234
+ if len(options.num_threads) > 0:
235
+ num_threads = int(options.num_threads)
236
+ else:
237
+ num_threads = 1
238
+ print(num_threads)
239
+ if options.xmp_gui is None:
240
+ func = partial(update_xmp_metadata, categories, options, rename_cats, n_images)
241
+ with Pool(num_threads) as p:
242
+ with tqdm(total=n_images) as pbar:
243
+ for i, _ in enumerate(p.imap_unordered(func, images)):
244
+ pbar.update()
245
+ else:
246
+ func = partial(update_xmp_metadata, categories, options, rename_cats, n_images)
247
+ with ThreadPool(num_threads) as p:
248
+ p.map(func, images)
249
+ s = 'Successfully processed {} images'.format(n_images)
250
+ print(s)
251
+ write_status(options,s)
252
+
253
+ except Exception as e:
254
+
255
+ print('Error processing input data: {}'.format(str(e)))
256
+ traceback.print_exc()
257
+ if options.xmp_gui is not None:
258
+ tkinter.messagebox.showerror(title='Error',
259
+ message='Make Sure you selected the proper image folder and JSON files')
260
+ sys.exit()
261
+
262
+
263
+ def start_input_processing(options):
264
+
265
+ t = threading.Thread(target=lambda: process_input_data(options))
266
+ t.start()
267
+
268
+
269
+ def browse_folder(options,folder_path_var):
270
+
271
+ filename = tkinter.filedialog.askdirectory()
272
+ options.image_folder = r'{0}'.format(filename)
273
+ folder_path_var.set(filename)
274
+
275
+
276
+ def browse_file(options,file_path_var):
277
+
278
+ filename = tkinter.filedialog.askopenfilename()
279
+ options.input_file = r'{0}'.format(filename)
280
+ file_path_var.set(filename)
281
+
282
+
283
+ def create_gui(options):
284
+
285
+ root = tkinter.Tk()
286
+ root.resizable(False, False)
287
+ root.configure(background='white')
288
+ root.title('DigiKam Integration')
289
+
290
+ group = tkinter.LabelFrame(root, padx=5, pady=5)
291
+ group.configure(background = 'white')
292
+ group.pack(padx=10, pady=10, fill='both', expand='yes')
293
+
294
+ canvas = tkinter.Canvas(group, width = 800, height = 150)
295
+ canvas.configure(background = 'white')
296
+ canvas.pack()
297
+ img1 = tkinter.PhotoImage(file='images/aiforearth.png')
298
+ canvas.create_image(0,0, anchor=tkinter.NW, image=img1)
299
+ img2 = tkinter.PhotoImage(file='images/bg.png')
300
+ canvas.create_image(0,20, anchor=tkinter.NW, image=img2)
301
+
302
+ frame = tkinter.Frame(root)
303
+ frame.configure(background='white')
304
+ frame.pack()
305
+
306
+ l1 = tkinter.Label(frame, text='Folder containing images')
307
+ l1.configure(background='white')
308
+ l1.grid(row=0, column=0)
309
+
310
+ folder_path_var = tkinter.StringVar()
311
+
312
+ e1 = tkinter.Entry(frame, width=50, textvariable=folder_path_var, highlightthickness=1)
313
+ e1.configure(highlightbackground='grey', highlightcolor='grey')
314
+ e1.grid(row=0, column=2)
315
+
316
+ b1 = tkinter.Button(frame, text='Browse', fg='blue', command=lambda: browse_folder(options,folder_path_var))
317
+ b1.grid(row=0, column=5, padx=10)
318
+
319
+ l2 = tkinter.Label(frame, text='Path to MegaDetector output .json file')
320
+ l2.configure(background='white')
321
+ l2.grid(row=1, column=0)
322
+
323
+ file_path_var = tkinter.StringVar()
324
+
325
+ e2 = tkinter.Entry(frame, width=50, textvariable=file_path_var, highlightthickness=1)
326
+ e2.configure(highlightbackground='grey', highlightcolor='grey')
327
+ e2.grid(row=1, column=2)
328
+
329
+ b2 = tkinter.Button(frame, text='Browse', fg='blue', command=lambda: browse_file(options,file_path_var))
330
+ b2.grid(row=1, column=5, padx=10)
331
+
332
+ l6 = tkinter.Label(frame, text='Minimum confidence to consider a category')
333
+ l6.configure(background='white')
334
+ l6.grid(row=2, column=0)
335
+
336
+ textarea_min_threshold = tkinter.Entry(frame, width=50, highlightthickness=1)
337
+ textarea_min_threshold.configure(highlightbackground='grey', highlightcolor='grey')
338
+ textarea_min_threshold.grid(row=2, column=2)
339
+
340
+ l3 = tkinter.Label(frame, text='Prefix to remove from image paths (optional)')
341
+ l3.configure(background='white')
342
+ l3.grid(row=3, column=0)
343
+
344
+ textarea_remove_path = tkinter.Entry(frame, width=50, highlightthickness=1)
345
+ textarea_remove_path.configure(highlightbackground='grey', highlightcolor='grey')
346
+ textarea_remove_path.grid(row=3, column=2)
347
+
348
+ l4 = tkinter.Label(frame, text='Confidence level to move images requires manual check (optional)')
349
+ l4.configure(background='white')
350
+ l4.grid(row=4, column=0)
351
+
352
+ textarea_rename_conf = tkinter.Entry(frame, width=50, highlightthickness=1)
353
+ textarea_rename_conf.configure(highlightbackground='grey', highlightcolor='grey')
354
+ textarea_rename_conf.grid(row=4, column=2)
355
+
356
+
357
+ l5 = tkinter.Label(frame, text='Categories to check for the confidence (optional)')
358
+ l5.configure(background='white')
359
+ l5.grid(row=5, column=0)
360
+
361
+ textarea_rename_cats = tkinter.Entry(frame, width=50, highlightthickness=1)
362
+ textarea_rename_cats.configure(highlightbackground='grey', highlightcolor='grey')
363
+ textarea_rename_cats.grid(row=5, column=2)
364
+
365
+ l6 = tkinter.Label(frame, text='Number of threads to run (optional)')
366
+ l6.configure(background='white')
367
+ l6.grid(row=6, column=0)
368
+
369
+ textarea_num_threads = tkinter.Entry(frame, width=50, highlightthickness=1)
370
+ textarea_num_threads.configure(highlightbackground='grey', highlightcolor='grey')
371
+ textarea_num_threads.grid(row=6, column=2)
372
+
373
+ sb = tkinter.Button(frame, text='Submit', fg='black',
374
+ command=lambda: start_input_processing(options), padx=10)
375
+ sb.grid(row=7, column=2, padx=10, pady=10)
376
+
377
+ style = tkinter.ttk.Style(root)
378
+ style.layout('text.Horizontal.Tprogress_bar',
379
+ [('Horizontal.progress_bar.trough',
380
+ {'children': [('Horizontal.progress_bar.pbar',
381
+ {'side': 'left', 'sticky': 'ns'})],
382
+ 'sticky': 'nswe'}),
383
+ ('Horizontal.progress_bar.label', {'sticky': ''})])
384
+ style.configure('text.Horizontal.Tprogress_bar', text='0 %')
385
+
386
+ progress_bar = tkinter.ttk.Progressbar(root, style='text.Horizontal.Tprogress_bar', length=700,
387
+ maximum=100, value=0, mode='determinate')
388
+ progress_bar.pack(pady=10)
389
+
390
+ group2 = tkinter.LabelFrame(root, text='Status', padx=5, pady=5)
391
+ group2.pack(padx=10, pady=10, fill='both', expand='yes')
392
+
393
+ textarea_status = tkinter.Text(group2, height=10, width=100)
394
+ textarea_status.configure(state="disabled")
395
+ textarea_status.pack()
396
+
397
+ options.xmp_gui = xmp_gui()
398
+ options.xmp_gui.root = root
399
+ options.xmp_gui.textarea_min_threshold = textarea_min_threshold
400
+ options.xmp_gui.textarea_remove_path = textarea_remove_path
401
+ options.xmp_gui.textarea_rename_conf = textarea_rename_conf
402
+ options.xmp_gui.textarea_rename_cats = textarea_rename_cats
403
+ options.xmp_gui.textarea_num_threads = textarea_num_threads
404
+ options.xmp_gui.textarea_status = textarea_status
405
+ options.xmp_gui.progress_bar = progress_bar
406
+ options.xmp_gui.style = style
407
+
408
+ root.mainloop()
409
+
410
+
411
+ #%% Interactive/test driver
412
+
413
+ if False:
414
+
415
+ #%%
416
+
417
+ options = xmp_integration_options()
418
+ options.input_file = r"C:\temp\demo_images\ssmini_xmp_test_orig\ssmini.mdv4.json"
419
+ options.image_folder = r"C:\temp\demo_images\ssmini_xmp_test"
420
+ options.remove_path = 'my_images/'
421
+ process_input_data(options)
422
+
423
+
424
+ #%% Command-line driver
425
+
426
+ def args_to_object(args,obj):
427
+ """
428
+ Copy all fields from the argparse table "args" to the object "obj"
429
+ """
430
+ for n, v in inspect.getmembers(args):
431
+ if not n.startswith('_'):
432
+ setattr(obj, n, v)
433
+
434
+
435
+ def main(): # noqa
436
+
437
+ parser = argparse.ArgumentParser()
438
+ parser.add_argument('--input_file', help = 'Path to the MegaDetector .json file', default=None)
439
+ parser.add_argument('--image_folder', help = 'Path to the folder containing images', default=None)
440
+ parser.add_argument('--min_threshold', help = 'Minimum detection confidence that will be treated as a detection event', default=None)
441
+ parser.add_argument('--remove_path', help = 'Prefix to remove from image paths in the .json file', default=None)
442
+ parser.add_argument('--rename_conf', help = 'Below this confidence level, images will be renamed for manual check', default=None)
443
+ parser.add_argument('--rename_cat', help = 'Category (or comma-delimited categories) to apply renaming behavior to', default=None)
444
+ parser.add_argument('--num_threads', help = 'Number of threads to use for image processing', default=1)
445
+ parser.add_argument('--gui', help = 'Run in GUI mode', action='store_true')
446
+
447
+ options = xmp_integration_options()
448
+ args = parser.parse_args()
449
+ args_to_object(args,options)
450
+
451
+ if options.gui:
452
+ assert options.input_file is None, 'Command-line argument specified in GUI mode'
453
+ assert options.image_folder is None, 'Command-line argument specified in GUI mode'
454
+ assert options.min_threshold is None, 'Command-line argument specified in GUI mode'
455
+ assert options.remove_path is None, 'Command-line argument specified in GUI mode'
456
+ assert options.rename_conf is None, 'Command-line argument specified in GUI mode'
457
+ assert options.rename_cat is None, 'Command-line argument specified in GUI mode'
458
+ assert options.num_threads == 1, 'Command-line argument specified in GUI mode'
459
+ create_gui(options)
460
+ else:
461
+ process_input_data(options)
462
+
463
+ if __name__ == '__main__':
464
+
465
+ main()
@@ -0,0 +1,5 @@
1
+ host="localhost"
2
+ username="root"
3
+ password=""
4
+ port=3307
5
+ database="wild_id"
@@ -0,0 +1,125 @@
1
+ #
2
+ # Test script for pushing annotations to the eMammal db
3
+ #
4
+
5
+ #%% Imports
6
+
7
+ import sys
8
+ import json
9
+ import argparse
10
+ import pymysql
11
+ import config as cfg
12
+
13
+ from tqdm import tqdm
14
+ from enum import Enum
15
+
16
+
17
+ #%% Database functions
18
+
19
+ class Categories(Enum):
20
+ animal = 1
21
+ person = 2
22
+ vehicle = 3
23
+
24
+ mysql_connection = pymysql.connect( host=cfg.host,
25
+ user=cfg.username,
26
+ passwd=cfg.password,
27
+ db=cfg.database,
28
+ port=cfg.port)
29
+
30
+ def update_data(sql):
31
+ with mysql_connection.cursor() as cursor:
32
+ cursor.execute(sql)
33
+
34
+ def get_records_all(sql):
35
+ with mysql_connection.cursor() as cursor:
36
+ sql = sql
37
+ cursor.execute(sql)
38
+ rows = cursor.fetchall()
39
+ return rows
40
+
41
+ def format_data_print_deployments(rows):
42
+ count = 0
43
+ result = []
44
+ for row in rows:
45
+ count += 1
46
+ print("{}. {}-{}".format(str(count), row[0],row[1]))
47
+ result.append((count, row[0], row[1]))
48
+
49
+ return result
50
+
51
+
52
+ #%% Command-line driver
53
+
54
+ def main(): # noqa
55
+
56
+ parser = argparse.ArgumentParser()
57
+ parser.add_argument('input_file', type=str, help='Input .json filename')
58
+
59
+ if len(sys.argv[1:]) == 0:
60
+ parser.print_help()
61
+ parser.exit()
62
+
63
+ args = parser.parse_args()
64
+
65
+ print("Enter the number of the deployment:")
66
+
67
+ rows = get_records_all(''' select * from deployment ''')
68
+ deployments = format_data_print_deployments(rows)
69
+ print("\n")
70
+ deployment_choice = input()
71
+ deployment_id = deployments[int(deployment_choice)][1]
72
+
73
+ print(deployment_id)
74
+
75
+ sql = ''' SELECT emammal_project_taxa_id FROM wild_id.emammal_project_taxa
76
+ where species in ("No Animal", "Unknown Animal", "Homo sapiens", "Vehicle") '''
77
+
78
+
79
+ emammal_categories = get_records_all(sql)
80
+
81
+ with open(args.input_file) as f:
82
+ data = json.load(f)
83
+
84
+ images = data['images']
85
+ emammal_category = 0
86
+ for index, im in tqdm(enumerate(images), total=len(images)):
87
+ fn = im['file']
88
+
89
+ if len(im['detections']) <= 0:
90
+ image_type_id = 2
91
+
92
+ # No-animal category
93
+ emammal_categories = emammal_categories[0]
94
+ else:
95
+ max_conf = im['max_detection_conf']
96
+ detection = [k for k in im['detections'] if k['conf'] == max_conf]
97
+ category= int(detection[0]['category'])
98
+
99
+ if category == Categories.animal:
100
+ image_type_id = 1
101
+ emammal_category = emammal_categories[1]
102
+ else:
103
+ image_type_id = 5
104
+ if category == Categories.person:
105
+ emammal_category = emammal_categories[2]
106
+ elif category == Categories.vehicle:
107
+ emammal_category = emammal_categories[3]
108
+
109
+ sql = """ UPDATE wild_id.emammal_sequence_annotation,
110
+ wild_id.image,
111
+ wild_id.image_sequence,
112
+ wild_id.deployment
113
+ SET wild_id.emammal_sequence_annotation.project_taxa_id = 4
114
+ WHERE wild_id.image.image_sequence_id = wild_id.emammal_sequence_annotation.sequence_id
115
+ AND wild_id.image_sequence.deployment_id = wild_id.deployment.deployment_id
116
+ AND wild_id.image.raw_name = '{}' """.format(fn)
117
+
118
+
119
+ print(sql)
120
+ update_data(sql)
121
+ mysql_connection.commit()
122
+
123
+ if __name__ == '__main__':
124
+ main()
125
+
@@ -0,0 +1,55 @@
1
+ #%% Imports
2
+
3
+ import os
4
+ import sys
5
+ import argparse
6
+ import json
7
+ import shutil
8
+
9
+ from tqdm import tqdm
10
+
11
+ #%% Main function
12
+
13
+ def main(): # noqa
14
+
15
+ parser = argparse.ArgumentParser()
16
+ parser.add_argument('input_file', type=str, help='Input .json filename')
17
+
18
+ if len(sys.argv[1:]) == 0:
19
+ parser.print_help()
20
+ parser.exit()
21
+
22
+ args = parser.parse_args()
23
+
24
+ with open(args.input_file) as f:
25
+ data = json.load(f)
26
+
27
+ images = data['images'][:1000]
28
+ data['images'] = images
29
+ with open('output.json', 'w') as f:
30
+ json.dump(data, f, indent=1)
31
+
32
+ select_images_folder = "select_images_folder"
33
+
34
+ if os.path.exists(select_images_folder):
35
+ shutil.rmtree(select_images_folder, ignore_errors=True)
36
+
37
+ os.mkdir(select_images_folder)
38
+
39
+ source = os.getcwd() + "\\SWWLF2019_R1_GMU1_F_9\\"
40
+ destination = os.getcwd() + "\\" + select_images_folder + "\\"
41
+
42
+ # if not os.path.exists(directory):
43
+ # os.makedirs(directory)
44
+
45
+ for index, im in tqdm(enumerate(images), total=len(images)):
46
+ fn=im['file']
47
+ fn = fn.replace('/', '\\')
48
+ print(os.path.dirname(fn))
49
+ directory = destination + os.path.dirname(fn)
50
+ if not os.path.exists(directory):
51
+ os.makedirs(directory)
52
+ dest = shutil.copyfile(source + fn, destination + fn)
53
+
54
+ if __name__ == '__main__':
55
+ main()
File without changes