samannot 0.6.0__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.

Potentially problematic release.


This version of samannot might be problematic. Click here for more details.

samannot/annotator.py ADDED
@@ -0,0 +1,1019 @@
1
+ import os
2
+ from PIL import Image
3
+ import cv2
4
+ import time
5
+ import numpy as np
6
+ from .label import Label, Label_Handler
7
+ from .sam_annotator import SAM_Annotator
8
+ from openpyxl import Workbook
9
+ import shutil
10
+ import re
11
+ from skimage.measure import label, regionprops
12
+ from skimage.morphology import skeletonize
13
+ from scipy import ndimage as ndi
14
+ import gc
15
+ class Annotator:
16
+ def __init__(self):
17
+ self.base_checkpoint_path = "./checkpoints/"
18
+ self.init_sam2()
19
+ self.sam_extract_dir = "sam_temp_dir"
20
+
21
+ self.media_files = []
22
+ self.curr_img_idx = -1
23
+ self.current_block = 0
24
+ self.block_size = 100
25
+ self.num_blocks = 1
26
+ self.idx_to_path = {}
27
+ self.temp_dir = None
28
+ self.video_name = ""
29
+ self.media_path = "."
30
+
31
+ self.overlay_img = None
32
+ self.composite_mask = None
33
+ self.masks = {}
34
+ self.overlay_imgs = {}
35
+ self.combined_masks = {}
36
+ self.cache_images = True
37
+ self.alpha = 0.6
38
+ self.current_img_width = 0
39
+ self.current_img_height = 0
40
+
41
+ self.label_handler = Label_Handler()
42
+ self.curr_label_idx = -1
43
+ self.image_file_types=["jpg","JPG","jpeg","JPEG","png"]
44
+ self.video_file_types=["mp4","avi","mov","mkv"]
45
+
46
+ self.mode = "prompts"
47
+ self.fn_modes = ["prompts","tracking","correction","export"]
48
+ self.view_mode = "prompts"
49
+ self.view_modes = ["original","prompts","overlay","masks"]
50
+ self.session_name = "Session"
51
+
52
+ self.tracking_results = {}
53
+ self.extra_frame_path = {}
54
+ self.extra_frame = {}
55
+ self.extra_frame_masks = {}
56
+ self.original_img = None
57
+ self.curr_img_shape = None
58
+
59
+ self.read_frames = -1
60
+ self.cap = None
61
+ # SESSION HANDLING
62
+
63
+ def reset(self):
64
+ self.media_files = []
65
+ self.curr_img_idx = -1
66
+ self.overlay_img = None
67
+ self.composite_mask = None
68
+ self.original_img = None
69
+ self.overlay_imgs = {}
70
+ self.combined_masks = {}
71
+ self.alpha = 0.6
72
+ self.masks = {}
73
+ self.tracking_results = {}
74
+ self.label_handler = Label_Handler()
75
+ self.curr_label_idx = -1
76
+ self.mode = "prompts"
77
+ self.view_mode = "prompts"
78
+ self.session_name = "Session"
79
+ self.video_name = ""
80
+ self.media_path = "."
81
+ self.tracking_results = {}
82
+ self.sam_handler.labels = []
83
+ self.sam_handler.object_id_to_label_name = {}
84
+ self.sam_handler.media_files = []
85
+ self.sam_handler.propagation_blocks = {}
86
+ self.current_block = 0
87
+ self.extra_frame_path = {}
88
+ self.extra_frame = {}
89
+ self.extra_frame_masks = {}
90
+ if self.cap is not None:
91
+ self.cap.release()
92
+ self.read_frames = -1
93
+ if self.sam_handler.inference_state:
94
+ self.sam_handler.predictor.reset_state(self.sam_handler.inference_state)
95
+ def load_from_dict(self,dict_representation):
96
+ self.session_name = dict_representation["session_name"]
97
+ self.view_mode = dict_representation["view_mode"]
98
+ self.mode = dict_representation["mode"]
99
+ self.media_files = dict_representation["media_files"]
100
+ self.curr_img_idx = dict_representation["curr_img_idx"]
101
+ self.overlay_img = dict_representation["overlay_img"]
102
+ self.overlay_imgs = dict_representation["overlay_imgs"]
103
+ self.combined_masks = dict_representation["combined_masks"]
104
+ self.original_img = dict_representation["original_img"]
105
+ self.composite_mask = dict_representation["composite_mask"]
106
+ self.masks = dict_representation["masks"]
107
+ self.idx_to_path = dict_representation["idx_to_path"]
108
+ self.temp_dir = dict_representation["temp_dir"]
109
+ self.current_img_width = dict_representation["current_img_width"]
110
+ self.current_img_height = dict_representation["current_img_height"]
111
+ self.label_handler = dict_representation["label_handler"]
112
+ self.curr_label_idx = dict_representation["curr_label_idx"]
113
+ self.tracking_results = dict_representation["tracking_results"]
114
+ self.cache_images = dict_representation["cache_images"]
115
+ self.media_path = dict_representation["media_path"]
116
+ self.video_name = dict_representation["video_name"]
117
+ self.sam_handler.labels = dict_representation["sam_handler_labels"]
118
+ self.sam_handler.object_id_to_label_name = dict_representation["sam_handler_object_id_to_label_name"]
119
+ self.sam_handler.media_files = dict_representation["sam_handler_media_files"]
120
+ self.sam_handler.curr_img_idx = dict_representation["sam_handler_curr_img_idx"]
121
+ self.sam_handler.current_stage = dict_representation["sam_handler_current_stage"]
122
+ self.sam_handler.model_loaded = dict_representation["sam_handler_model_loaded"]
123
+ self.sam_handler.model_loading = dict_representation["sam_handler_model_loading"]
124
+ self.sam_handler.propagation_blocks = dict_representation["sam_handler_propagation_blocks"]
125
+ self.block_size = dict_representation["block_size"]
126
+ self.current_block = dict_representation["current_block"]
127
+ self.num_blocks = dict_representation["num_blocks"]
128
+ self.curr_img_shape = dict_representation["curr_img_shape"]
129
+ self.extra_frame_path = dict_representation["extra_frame_path"]
130
+ self.extra_frame = dict_representation["extra_frame"]
131
+ self.extra_frame_masks = dict_representation["extra_frame_masks"]
132
+ self.alpha = dict_representation.get("alpha", 0.6)
133
+ def compress_to_dict(self):
134
+ dict_representation = {
135
+ "alpha": getattr(self, "alpha", 0.6),
136
+ "session_name": self.session_name,
137
+ "view_mode": self.view_mode,
138
+ "mode": self.mode,
139
+ "media_files": self.media_files,
140
+ "curr_img_idx": self.curr_img_idx,
141
+ "overlay_img": self.overlay_img,
142
+ "overlay_imgs": self.overlay_imgs,
143
+ "combined_masks": self.combined_masks,
144
+ "original_img": self.original_img,
145
+ "composite_mask": self.composite_mask,
146
+ "masks": self.masks,
147
+ "idx_to_path": self.idx_to_path,
148
+ "temp_dir": self.temp_dir,
149
+ "current_img_width": self.current_img_width,
150
+ "current_img_height": self.current_img_height,
151
+ "label_handler": self.label_handler,
152
+ "curr_label_idx": self.curr_label_idx,
153
+ "tracking_results": self.tracking_results,
154
+ "cache_images": self.cache_images,
155
+ "media_path": self.media_path,
156
+ "video_name": self.video_name,
157
+ "block_size": self.block_size,
158
+ "current_block": self.current_block,
159
+ "num_blocks": self.num_blocks,
160
+ "curr_img_shape": self.curr_img_shape,
161
+ "extra_frame_path": self.extra_frame_path,
162
+ "extra_frame": self.extra_frame,
163
+ "extra_frame_masks": self.extra_frame_masks,
164
+ "sam_handler_labels": self.sam_handler.labels,
165
+ "sam_handler_object_id_to_label_name": self.sam_handler.object_id_to_label_name,
166
+ "sam_handler_media_files": self.sam_handler.media_files,
167
+ "sam_handler_curr_img_idx": self.sam_handler.curr_img_idx,
168
+ "sam_handler_current_stage": self.sam_handler.current_stage,
169
+ "sam_handler_model_loaded": self.sam_handler.model_loaded,
170
+ "sam_handler_model_loading": self.sam_handler.model_loading,
171
+ "sam_handler_propagation_blocks": self.sam_handler.propagation_blocks,
172
+ }
173
+ return dict_representation
174
+
175
+ # OTHERS
176
+
177
+ def set_session_name(self,session_name):
178
+ self.session_name = session_name
179
+ def get_session_name(self):
180
+ return self.session_name
181
+ def set_cache_images(self,value):
182
+ if value == False:
183
+ self.overlay_imgs = {}
184
+ self.combined_masks = {}
185
+ gc.collect()
186
+ self.cache_images = value
187
+ def check_label_existence(self, label_name):
188
+ for label in self.sam_handler.labels:
189
+ if label.name == label_name:
190
+ return True
191
+ return False
192
+ def get_current_block(self):
193
+ return self.current_block
194
+ def set_num_blocks(self,num_blocks):
195
+ self.num_blocks = num_blocks
196
+ for i in range(self.num_blocks):
197
+ self.sam_handler.propagation_blocks[i] = {}
198
+ for label in self.sam_handler.labels:
199
+ for i in range(self.num_blocks):
200
+ if i not in label.pts:
201
+ label.pts[i] = []
202
+ if i not in label.boxes:
203
+ label.boxes[i] = []
204
+ if i not in label.prop_frames:
205
+ label.prop_frames[i] = set()
206
+ def set_current_block(self,block):
207
+ if block < 0:
208
+ block = 0
209
+ self.current_block = block
210
+ self.sam_handler.current_block = self.current_block
211
+ def has_labels(self):
212
+ return len(self.sam_handler.labels) > 0
213
+ def has_frames(self):
214
+ return len(self.media_files) > 0
215
+ def has_prompts(self, block_idx):
216
+ for label in self.get_labels():
217
+ if len(label.pts[block_idx]) > 0 or len(label.boxes[block_idx]):
218
+ return True
219
+ return False
220
+ def get_label_idx(self, label_name):
221
+ for idx in range(len(self.sam_handler.labels)):
222
+ if self.sam_handler.labels[idx].name == label_name:
223
+ return idx
224
+ return -1
225
+ def get_current_label(self):
226
+ if self.curr_label_idx < 0:
227
+ return None
228
+ return self.sam_handler.labels[self.curr_label_idx]
229
+ def set_current_label(self,idx):
230
+ self.curr_label_idx = idx
231
+ def set_label_name(self, idx, name):
232
+ old_name = self.sam_handler.labels[idx].name
233
+ new_name = name
234
+ for masks in self.masks.values():
235
+ if old_name in masks:
236
+ masks[new_name] = masks.pop(old_name)
237
+ self.sam_handler.labels[idx].name = name
238
+ def get_labels(self):
239
+ return self.sam_handler.labels
240
+ def get_current_label_idx(self):
241
+ return self.curr_label_idx
242
+ def get_current_img_idx(self):
243
+ return self.curr_img_idx
244
+ def get_number_of_images(self):
245
+ return len(self.media_files)
246
+
247
+ # LABEL AND PROMPT HANDLING
248
+
249
+ def add_label(self,label_name):
250
+ new_label = self.label_handler.create_new_label(label_name)
251
+ for i in range(self.num_blocks):
252
+ new_label.pts[i] = []
253
+ for i in range(self.num_blocks):
254
+ new_label.boxes[i] = []
255
+ for i in range(self.num_blocks):
256
+ new_label.prop_frames[i] = set()
257
+ self.sam_handler.labels.append(new_label)
258
+ self.curr_label_idx = len(self.sam_handler.labels) - 1
259
+ return new_label.col
260
+ def add_feature_to_current_label(self,feature_name):
261
+ current_label = self.sam_handler.labels[self.curr_label_idx]
262
+ current_label.features.append([(feature_name, 0)])
263
+ def delete_feature_from_current_label(self,feature_idx):
264
+ current_label = self.sam_handler.labels[self.curr_label_idx]
265
+ current_label.features.pop(feature_idx)
266
+ def delete_selected_point(self,point_idx):
267
+ current_label = self.sam_handler.labels[self.curr_label_idx]
268
+ if point_idx < len(current_label.pts[self.current_block]):
269
+ current_label.remove_pt(point_idx,self.current_block)
270
+ def delete_selected_box(self,box_idx):
271
+ current_label = self.sam_handler.labels[self.curr_label_idx]
272
+ if box_idx < len(current_label.boxes[self.current_block]):
273
+ current_label.remove_box(box_idx,self.current_block)
274
+
275
+ # MODEL HANDLING
276
+
277
+ def init_sam2(self):
278
+ pkg_dir = os.path.dirname(os.path.abspath(__file__))
279
+ candidates = [
280
+ os.path.join(os.getcwd(), "checkpoints", "sam2.1_hiera_large.pt"),
281
+ os.path.join(os.path.dirname(pkg_dir), "checkpoints", "sam2.1_hiera_large.pt"),
282
+ os.path.join(os.path.expanduser("~"), ".cache", "samannot", "checkpoints", "sam2.1_hiera_large.pt"),
283
+ os.path.join(pkg_dir, "checkpoints", "sam2.1_hiera_large.pt"),
284
+ ]
285
+ ckpt_path = candidates[0]
286
+ for c in candidates:
287
+ if os.path.exists(c):
288
+ ckpt_path = c
289
+ break
290
+ self.sam_handler = SAM_Annotator(model_type="vit_h", model_cfg_path="sam2.1_hiera_l.yaml", ckpt_path=ckpt_path)
291
+ def can_initialize_model(self):
292
+ return os.path.exists(self.sam_handler.ckpt_path)
293
+ def get_model_type(self):
294
+ return self.sam_handler.model_type
295
+ def model_status(self):
296
+ return self.sam_handler.is_model_loaded()
297
+ def load_model(self,status_callback):
298
+ if not self.can_initialize_model():
299
+ return False
300
+ return self.sam_handler.load_model(status_callback)
301
+
302
+ # PROPAGATION
303
+
304
+ def initialize_tracking(self,update_progress_callback):
305
+ self.sam_handler.media_files = self.media_files
306
+ self.sam_handler.curr_img_idx = self.curr_img_idx
307
+ self.mode = "tracking"
308
+ success = self.sam_handler.init_inference_state(self.sam_extract_dir, status_callback=update_progress_callback)
309
+ if not success:
310
+ self.mode = "prompts"
311
+ return success
312
+ def apply_masks(self,update_progress_callback):
313
+ total_steps = len(list(self.tracking_results.keys()))
314
+ current_step = 0
315
+ for frame_idx, frame_masks in self.tracking_results.items():
316
+ if frame_idx < len(self.media_files):
317
+ frame_path = self.media_files[frame_idx]
318
+ self.idx_to_path[frame_idx] = frame_path
319
+ self.masks[frame_path] = {}
320
+ try:
321
+ for label_name, mask in frame_masks.items():
322
+ label_color = None
323
+ for label in self.sam_handler.labels:
324
+ if label.name == label_name:
325
+ label_color = self.hex_to_rgb(label.col)
326
+ break
327
+ if label_color is None:
328
+ label_color = (255, 255, 255)
329
+ self.masks[frame_path][label_name]=PackedMasks(mask.squeeze().astype(bool))
330
+ progress_percent = (current_step / total_steps) * 100
331
+ update_progress_callback(f"Applying masks: {current_step + 1}/{total_steps}", progress_percent)
332
+ current_step += 1
333
+ if self.cache_images:
334
+ self.combined_masks[frame_path] = self.create_combined_mask(frame_path,overwrite=True)
335
+ self.overlay_imgs[frame_path] = self.create_overlay_img(frame_path,overwrite=True)
336
+ except Exception as e:
337
+ print(f"Error generating mask for frame {frame_idx}: {str(e)}")
338
+ self.tracking_results = {}
339
+ self.composite_mask = self.create_combined_mask(overwrite=True)
340
+ self.overlay_img = self.create_overlay_img(overwrite=True)
341
+ if self.cache_images:
342
+ self.combined_masks[self.media_files[self.curr_img_idx]] = self.composite_mask
343
+ self.overlay_imgs[self.media_files[self.curr_img_idx]] = self.overlay_img
344
+ self.mode = "correction"
345
+ self.view_mode = "overlay"
346
+ def has_propagation_block(self,idx):
347
+ return (idx in self.sam_handler.propagation_blocks[self.current_block])
348
+ def add_propagation_block(self,idx):
349
+ self.sam_handler.propagation_blocks[self.current_block][idx] = 1
350
+ def remove_propagation_block(self,idx):
351
+ del self.sam_handler.propagation_blocks[self.current_block][idx]
352
+ def generate_mask(self):
353
+ if not self.sam_handler.is_model_loaded():
354
+ return False, []
355
+ if self.curr_label_idx < 0 or len(self.media_files) < 0:
356
+ return False, []
357
+ labels_with_points = [label for label in self.sam_handler.labels if len(label.pts[self.current_block]) > 0]
358
+ if not labels_with_points:
359
+ return False, []
360
+ self.sam_handler.media_files = self.media_files
361
+ self.sam_handler.curr_img_idx = self.curr_img_idx
362
+ self.tracking_results = self.sam_handler.generate_mask_for_frame(self.curr_img_idx,0)
363
+ if self.tracking_results is None:
364
+ self.mode = "prompts"
365
+ return False, []
366
+ else:
367
+ for k, v in self.tracking_results.items():
368
+ for label,_ in v.items():
369
+ self.sam_handler.labels[self.get_label_idx(label)].prop_frames[self.current_block].add(k)
370
+ return True, list(self.tracking_results.keys())
371
+ def propagate(self,flag,update_progress_callback):
372
+ if flag == 0:
373
+ self.tracking_results = self.sam_handler.propagate_to_all(
374
+ current_frame_idx=self.curr_img_idx,
375
+ start_frame_idx=None,
376
+ end_frame_idx=None,
377
+ progress_callback=update_progress_callback)
378
+ elif flag == 1:
379
+ self.tracking_results = self.sam_handler.propagate(1,
380
+ start_frame_idx=self.curr_img_idx,
381
+ end_frame_idx=None,
382
+ progress_callback=update_progress_callback)
383
+ else:
384
+ self.tracking_results = self.sam_handler.propagate(-1,
385
+ start_frame_idx=self.curr_img_idx,
386
+ end_frame_idx=None,
387
+ progress_callback=update_progress_callback)
388
+ if self.tracking_results is None:
389
+ self.mode = "prompts"
390
+ return False, []
391
+ else:
392
+ if self.block_size in self.tracking_results:
393
+ self.extra_frame[self.current_block] = self.tracking_results[self.block_size]
394
+ self.tracking_results.pop(self.block_size)
395
+ self.extra_frame_masks[self.current_block] = {}
396
+ for label_name, mask in self.extra_frame[self.current_block].items():
397
+ label_color = None
398
+ for label in self.sam_handler.labels:
399
+ if label.name == label_name:
400
+ label_color = self.hex_to_rgb(label.col)
401
+ break
402
+ if label_color is None:
403
+ label_color = (255, 255, 255)
404
+ self.extra_frame_masks[self.current_block][label_name]=PackedMasks(mask.squeeze().astype(bool))
405
+ for k, v in self.tracking_results.items():
406
+ for label,_ in v.items():
407
+ self.sam_handler.labels[self.get_label_idx(label)].prop_frames[self.current_block].add(k)
408
+ return True, list(self.tracking_results.keys())
409
+
410
+ # AUTO-PROMPTING ~ DONE
411
+
412
+ def keep_largest_connected_region(self,mask):
413
+ labeled = label(mask > 0)
414
+ if labeled.max() == 0:
415
+ return np.zeros_like(mask)
416
+ largest_region = max(regionprops(labeled), key=lambda r: r.area)
417
+ return (labeled == largest_region.label).astype(np.uint8) * 255
418
+ def skeletonize_single_mask(self,mask):
419
+ if mask is None:
420
+ return None
421
+ mask = self.keep_largest_connected_region(mask)
422
+ mask = mask.astype(np.uint8)
423
+ skeleton = skeletonize(mask).astype(np.uint8)
424
+ return skeleton
425
+ def generate_point_prompts(self,mask):
426
+ skeleton = self.skeletonize_single_mask(mask)
427
+ neighbourhood_kernel = np.array([[1, 1, 1],
428
+ [1, 0, 1],
429
+ [1, 1, 1]], dtype=np.uint8)
430
+ neighbor_count = ndi.convolve(skeleton.astype(np.uint8),neighbourhood_kernel,mode='constant', cval=0)
431
+ endpoints = skeleton & (neighbor_count == 1)
432
+ endpoints = np.vstack(np.nonzero(endpoints)).T
433
+ junctions = skeleton & (neighbor_count >= 3)
434
+ structure = np.ones((3, 3), dtype=np.uint8)
435
+ labels, n_labels = ndi.label(junctions, structure=structure)
436
+ if n_labels > 0:
437
+ junctions = np.asarray(ndi.center_of_mass(junctions, labels, index=range(1, n_labels + 1)),dtype=np.int32)
438
+ return np.vstack([endpoints,junctions])
439
+ else:
440
+ junctions = np.asarray([])
441
+ return endpoints
442
+
443
+ # VIEW MODE
444
+
445
+ def get_next_view_mode(self):
446
+ if self.view_mode == "original":
447
+ return "prompts"
448
+ elif self.view_mode == "prompts":
449
+ if hasattr(self, 'overlay_img') and self.media_files[self.curr_img_idx] in self.masks:
450
+ return "overlay"
451
+ elif hasattr(self, 'masks') and self.media_files[self.curr_img_idx] in self.masks:
452
+ return "masks"
453
+ else:
454
+ return "original"
455
+ elif self.view_mode == "overlay":
456
+ if hasattr(self, 'masks') and self.media_files[self.curr_img_idx] in self.masks:
457
+ return "masks"
458
+ else:
459
+ return "original"
460
+ else:
461
+ return "original"
462
+ def allowed_view_mode(self,new_view_mode):
463
+ if new_view_mode == "original":
464
+ return True
465
+ elif new_view_mode == "prompts":
466
+ return True
467
+ elif new_view_mode == "overlay":
468
+ return (hasattr(self, 'overlay_img') and self.media_files[self.curr_img_idx] in self.masks)
469
+ else:
470
+ return (hasattr(self, 'masks') and self.media_files[self.curr_img_idx] in self.masks)
471
+ def set_view_mode(self, vm_idx):
472
+ if vm_idx < 0 or vm_idx > 3:
473
+ return
474
+ new_view_mode = self.view_modes[vm_idx]
475
+ if self.allowed_view_mode(new_view_mode):
476
+ self.view_mode = new_view_mode
477
+ def toggle_view_mode(self):
478
+ self.view_mode = self.get_next_view_mode()
479
+ def reset_view_mode(self):
480
+ self.mode = "prompts"
481
+ self.view_mode = "original"
482
+ def get_view_mode(self):
483
+ return self.view_mode
484
+ def get_mode(self):
485
+ return self.mode
486
+
487
+ # ANNOTATION EXPORT
488
+
489
+ def bbox_from_mask(self,mask):
490
+ if not np.any(mask):
491
+ return None, None
492
+ r = np.any(mask, axis=1)
493
+ c = np.any(mask, axis=0)
494
+ rmin,rmax = np.where(r)[0][[0,-1]]
495
+ cmin,cmax = np.where(c)[0][[0,-1]]
496
+ center = np.argwhere(mask).mean(axis=0)
497
+ return [rmin,rmax,cmin,cmax],tuple(center)
498
+ def export_manual_data(self):
499
+ wb = Workbook()
500
+ ws = wb.active
501
+ session_id = self.session_name.split("_")
502
+ frame_indices = list(self.idx_to_path.keys())
503
+ frame_indices.sort()
504
+ row = 1
505
+ col = ord("A")
506
+ ws[chr(col)+str(row)] = "frame_id"
507
+ col = col+1
508
+ for section in session_id:
509
+ ws[chr(col)+str(row)] = "session_id"
510
+ col = col+1
511
+ ws[chr(col)+str(row)] = "label"
512
+ col = col+1
513
+ ws[chr(col)+str(row)] = "features"
514
+ col = col+1
515
+ ws[chr(col)+str(row)] = "clicks"
516
+ col = col+1
517
+ ws[chr(col)+str(row)] = "averaged click x"
518
+ col = col+1
519
+ ws[chr(col)+str(row)] = "averaged click y"
520
+ col = col+1
521
+ ws[chr(col)+str(row)] = "boxes"
522
+ col = col+1
523
+ row += 1
524
+ label_dict = {k.name:k for k in self.sam_handler.labels}
525
+ frame_paths = list(self.masks.keys())
526
+ frame_paths.sort()
527
+ idx = 0
528
+ points = {}
529
+ boxes = {}
530
+ avg_points = {}
531
+ for label in self.sam_handler.labels:
532
+ for k,v in label.pts.items():
533
+ for pt in v:
534
+ if (pt.idx + self.block_size * k) not in points:
535
+ points[pt.idx + self.block_size * k] = {}
536
+ avg_points[pt.idx + self.block_size * k] = {}
537
+ if label.name not in points[pt.idx + self.block_size * k]:
538
+ points[pt.idx + self.block_size * k][label.name] = []
539
+ avg_points[pt.idx + self.block_size * k][label.name] = [0,0,0]
540
+ points[pt.idx + self.block_size * k][label.name].append((pt.x,pt.y,pt.pt_type))
541
+ avg_points[pt.idx + self.block_size * k][label.name][0] += pt.x
542
+ avg_points[pt.idx + self.block_size * k][label.name][1] += pt.y
543
+ avg_points[pt.idx + self.block_size * k][label.name][2] += pt.pt_type
544
+ for k,v in label.boxes.items():
545
+ for box in v:
546
+ if (box.idx + self.block_size * k) not in boxes:
547
+ boxes[box.idx + self.block_size * k] = {}
548
+ if label.name not in boxes[box.idx + self.block_size * k]:
549
+ boxes[box.idx + self.block_size * k][label.name] = []
550
+ boxes[box.idx + self.block_size * k][label.name].append((box.fx,box.fy,box.x,box.y,box.pt_type))
551
+ point_indices = list(set(list(points.keys()) + list(boxes.keys())))
552
+ point_indices.sort()
553
+ for idx in point_indices:
554
+ if idx in points:
555
+ for k,v in points[idx].items():
556
+ col = ord("A")
557
+ ws[chr(col)+str(row)] = idx
558
+ col = col+1
559
+ for section in session_id:
560
+ ws[chr(col)+str(row)] = section
561
+ col = col+1
562
+ ws[chr(col)+str(row)] = k
563
+ col = col+1
564
+ ws[chr(col)+str(row)] = ','.join(str(x) for x in label_dict[k].features)
565
+ col = col+1
566
+ ws[chr(col)+str(row)] = ','.join(str(x) for x in v)
567
+ col = col+1
568
+ ws[chr(col)+str(row)] = avg_points[idx][k][0] / avg_points[idx][k][2]
569
+ col = col+1
570
+ ws[chr(col)+str(row)] = avg_points[idx][k][1] / avg_points[idx][k][2]
571
+ col = col+1
572
+ ws[chr(col)+str(row)] = ""
573
+ col = col+1
574
+ row += 1
575
+ if idx in boxes:
576
+ for k,v in boxes[idx].items():
577
+ col = ord("A")
578
+ ws[chr(col)+str(row)] = idx
579
+ col = col+1
580
+ for section in session_id:
581
+ ws[chr(col)+str(row)] = section
582
+ col = col+1
583
+ ws[chr(col)+str(row)] = k
584
+ col = col+1
585
+ ws[chr(col)+str(row)] = ','.join(str(x) for x in label_dict[k].features)
586
+ col = col+1
587
+ ws[chr(col)+str(row)] = ""
588
+ col = col+1
589
+ ws[chr(col)+str(row)] = ""
590
+ col = col+1
591
+ ws[chr(col)+str(row)] = ""
592
+ col = col+1
593
+ ws[chr(col)+str(row)] = ','.join(str(x) for x in v)
594
+ col = col+1
595
+ row += 1
596
+ wb.save(os.path.join(os.getcwd(),"export",self.session_name,"manual_data.xlsx"))
597
+ def export_interpolated_data(self,update_progress_callback):
598
+ wb = Workbook()
599
+ ws = wb.active
600
+ session_id = self.session_name.split("_")
601
+ frame_indices = list(self.idx_to_path.keys())
602
+ frame_indices.sort()
603
+ row = 1
604
+ col = ord("A")
605
+ ws[chr(col)+str(row)] = "frame_id"
606
+ col = col+1
607
+ for section in session_id:
608
+ ws[chr(col)+str(row)] = "session_id"
609
+ col = col+1
610
+ ws[chr(col)+str(row)] = "label"
611
+ col = col+1
612
+ ws[chr(col)+str(row)] = "features"
613
+ col = col+1
614
+ ws[chr(col)+str(row)] = "bounding box"
615
+ col = col+1
616
+ ws[chr(col)+str(row)] = "center-x"
617
+ col = col+1
618
+ ws[chr(col)+str(row)] = "center-y"
619
+ col = col+1
620
+ row += 1
621
+ label_dict = {k.name:k for k in self.sam_handler.labels}
622
+ frame_paths = list(self.masks.keys())
623
+ frame_paths.sort()
624
+ for idx, path in enumerate(frame_paths):
625
+ for k,v in self.masks[path].items():
626
+ col = ord("A")
627
+ ws[chr(col)+str(row)] = idx
628
+ col = col+1
629
+ for section in session_id:
630
+ ws[chr(col)+str(row)] = section
631
+ col = col+1
632
+ bbox,center = self.bbox_from_mask(v)
633
+ ws[chr(col)+str(row)] = k
634
+ col = col+1
635
+ feature_list = ""
636
+ for i, feature in enumerate(label_dict[k].features):
637
+ feature_list += label_dict[k].find_most_recent_feature(i, idx)
638
+ feature_list += ","
639
+ ws[chr(col)+str(row)] = feature_list
640
+ col = col+1
641
+ if bbox is not None:
642
+ ws[chr(col)+str(row)] = ','.join(str(x) for x in bbox)
643
+ col = col+1
644
+ ws[chr(col)+str(row)] = int(center[0])
645
+ col = col+1
646
+ ws[chr(col)+str(row)] = int(center[1])
647
+ col = col+1
648
+ else:
649
+ ws[chr(col)+str(row)] = '-'
650
+ col = col+1
651
+ ws[chr(col)+str(row)] = '-'
652
+ col = col+1
653
+ ws[chr(col)+str(row)] = '-'
654
+ col = col+1
655
+ row += 1
656
+ update_progress_callback("interpolated",idx,len(frame_paths))
657
+ wb.save(os.path.join(os.getcwd(),"export",self.session_name,"interpolated_data.xlsx"))
658
+ def export_overlays(self,update_progress_callback):
659
+ current_step = 0
660
+ total_steps = len(list(self.masks.keys()))
661
+ for k,v in self.masks.items():
662
+ cv2.imwrite(os.path.join(os.getcwd(),"export",self.session_name,"overlays",os.path.basename(k)),cv2.cvtColor(np.array(self.create_overlay_img(k)),cv2.COLOR_BGR2RGB))
663
+ update_progress_callback("overlay",current_step,total_steps)
664
+ current_step += 1
665
+ def export_masks(self,update_progress_callback):
666
+ current_step = 0
667
+ total_steps = len(list(self.masks.keys()))
668
+ label_to_id = {label.name: i for i, label in enumerate(self.sam_handler.labels)}
669
+ for k in self.masks.keys():
670
+ combined_mask = cv2.cvtColor(np.array(self.create_combined_mask(k)),cv2.COLOR_BGR2RGB)
671
+ h, w = combined_mask.shape[:2]
672
+ cv2.imwrite(os.path.join(os.getcwd(),"export",self.session_name,"masks",os.path.basename(k).split('.')[0] + ".png"), combined_mask)
673
+ with open(os.path.join(os.getcwd(),"export",self.session_name,"labels",os.path.basename(k).split('.')[0] + ".txt"), "w") as f:
674
+ for label in self.sam_handler.labels:
675
+ if label.name not in self.masks[k]:
676
+ continue
677
+ class_id = label_to_id[label.name]
678
+ try:
679
+ contours, _ = cv2.findContours(self.masks[k][label.name].astype(np.uint8) * 255, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
680
+ for contour in contours:
681
+ if len(contour) < 3:
682
+ continue
683
+ contour = contour.squeeze().astype(float)
684
+ contour[:, 0] /= w
685
+ contour[:, 1] /= h
686
+ coords = " ".join([f"{x:.6f} {y:.6f}" for x, y in contour])
687
+ f.write(f"{class_id} {coords}\n")
688
+ except Exception as e:
689
+ print(f"Error in exporting masks: {str(e)}")
690
+ img_rgb = cv2.imread(k)
691
+ cv2.imwrite(os.path.join(os.getcwd(),"export",self.session_name,"frames",os.path.basename(k).split('.')[0]+".png"), img_rgb)
692
+ update_progress_callback("mask",current_step,total_steps)
693
+ current_step += 1
694
+ def export_label_data(self):
695
+ wb = Workbook()
696
+ ws = wb.active
697
+ row = 1
698
+ col = ord("A")
699
+ ws[chr(col)+str(row)] = "label"
700
+ col = col+1
701
+ ws[chr(col)+str(row)] = "color"
702
+ col = col+1
703
+ row += 1
704
+ for label in self.sam_handler.labels:
705
+ col = ord("A")
706
+ ws[chr(col)+str(row)] = label.name
707
+ col = col+1
708
+ ws[chr(col)+str(row)] = str(self.hex_to_rgb(label.col))
709
+ col = col+1
710
+ row += 1
711
+ wb.save(os.path.join(os.getcwd(),"export",self.session_name,"label_data.xlsx"))
712
+ def init_export(self):
713
+ shutil.rmtree(os.path.join(os.getcwd(),"export",self.session_name), ignore_errors=True)
714
+ os.makedirs(os.path.join(os.getcwd(),"export",self.session_name),exist_ok=True)
715
+ os.makedirs(os.path.join(os.getcwd(),"export",self.session_name,"overlays"),exist_ok=True)
716
+ os.makedirs(os.path.join(os.getcwd(),"export",self.session_name,"masks"),exist_ok=True)
717
+ os.makedirs(os.path.join(os.getcwd(),"export", self.session_name,"labels"), exist_ok=True)
718
+ os.makedirs(os.path.join(os.getcwd(),"export", self.session_name,"frames"), exist_ok=True)
719
+
720
+ # MEDIA HANDLING
721
+
722
+ def reset_media(self):
723
+ self.media_files = []
724
+ self.curr_img_idx = -1
725
+ self.overlay_img = None
726
+ self.composite_mask = None
727
+ self.original_img = None
728
+ self.overlay_imgs = {}
729
+ self.combined_masks = {}
730
+ self.mode = "prompts"
731
+ self.view_mode = "prompts"
732
+ self.tracking_results = {}
733
+ self.sam_handler.object_id_to_label_name = {}
734
+ self.sam_handler.media_files = []
735
+ self.curr_img_shape = (0,0,0)
736
+ if self.sam_handler.inference_state:
737
+ self.sam_handler.predictor.reset_state(self.sam_handler.inference_state)
738
+ def clear_temp_dir(self):
739
+ self.temp_dir = "temp_dir"
740
+ shutil.rmtree(self.temp_dir, ignore_errors=True)
741
+ os.makedirs(self.temp_dir, exist_ok=True)
742
+ def load_main_folder_unified(self, file_path, block_size):
743
+ self.block_size = block_size
744
+ if file_path is not None and len(file_path) > 0:
745
+ extension = file_path.split(".")[-1]
746
+ if extension in self.image_file_types:
747
+ self.process_image_folder(os.path.dirname(file_path),self.current_block * block_size,(self.current_block + 1) * block_size)
748
+ return 0
749
+ elif os.path.isdir(file_path):
750
+ self.process_image_folder(file_path,self.current_block * block_size,(self.current_block + 1) * block_size)
751
+ return 0
752
+ elif extension in self.video_file_types:
753
+ self.process_video_file(file_path)
754
+ return 1
755
+ else:
756
+ print(f"Invalid file format!")
757
+ return -1
758
+ def process_image_folder(self, folder_path, start_frame, end_frame):
759
+ self.media_path = folder_path
760
+ self.video_name = ""
761
+ try:
762
+ self.extract_dir = os.path.join(self.temp_dir)
763
+ all_files = os.listdir(folder_path)
764
+ self.media_files = [os.path.join(folder_path, file) for file in all_files if file.split(".")[-1] in self.image_file_types]
765
+ def numeric_key( p):
766
+ name = os.path.splitext(os.path.basename(p))[0]
767
+ match = re.search(r'\d+', name)
768
+ if match:
769
+ return int(match.group())
770
+ return float('inf')
771
+ self.media_files.sort(key=numeric_key)
772
+ end_frame = np.amin([end_frame,len(self.media_files)])
773
+ print(f"{len(self.media_files)} vs {end_frame}")
774
+ if len(self.media_files) >= end_frame:
775
+ file_name = self.media_files[end_frame]
776
+ self.extra_frame_path[self.current_block] = os.path.join(self.sam_extract_dir,os.path.basename(file_name))
777
+ self.media_files = self.media_files[start_frame:end_frame+1]
778
+ else:
779
+ self.extra_frame_path[self.current_block] = None
780
+ self.media_files = self.media_files[start_frame:end_frame]
781
+
782
+ shutil.rmtree(self.sam_extract_dir, ignore_errors=True)
783
+ os.makedirs(self.sam_extract_dir, exist_ok=True)
784
+ for file_name in self.media_files:
785
+ shutil.copy(file_name,os.path.join(self.extract_dir,os.path.basename(file_name)))
786
+ shutil.copy(file_name,os.path.join(self.sam_extract_dir,os.path.basename(file_name)))
787
+ self.curr_img_idx = -1
788
+
789
+ except Exception as e:
790
+ print(f"Error loading folders: {str(e)}")
791
+ def process_video_file(self, video_path):
792
+ try:
793
+ self.media_path = os.path.dirname(video_path)
794
+ if self.read_frames == -1:
795
+ self.cap = cv2.VideoCapture(video_path)
796
+ self.video_name = video_path
797
+ self.extract_dir = self.temp_dir
798
+ self.extracted_frames = []
799
+ except Exception as e:
800
+ print(f"Error processing video: {str(e)}")
801
+ def get_loaded_frame_count(self):
802
+ return len(self.media_files)
803
+ def get_frame_count(self,video_path):
804
+ total_frames = 0
805
+ try:
806
+ if self.cap is not None:
807
+ total_frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
808
+ else:
809
+ cap = cv2.VideoCapture(video_path)
810
+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
811
+ cap.release()
812
+ except Exception as e:
813
+ print(f"Error: {str(e)}")
814
+ return total_frames
815
+ def get_frame_count_dir(self,folder_path):
816
+ temp_media_files = [os.path.join(folder_path, file) for file in os.listdir(folder_path) if file.split(".")[-1] in self.image_file_types]
817
+ return len(temp_media_files)
818
+ def reset_read_frames(self):
819
+ self.read_frames = -1
820
+ def extract_frames(self,start_frame,end_frame,interval,progress_var):
821
+ frame_count = 0
822
+ saved_count = 0
823
+ if self.read_frames > start_frame:
824
+ self.cap = cv2.VideoCapture(self.video_name)
825
+ for i in range(0,start_frame):
826
+ ret, frame = self.cap.read()
827
+ self.read_frames += 1
828
+ if not ret:
829
+ break
830
+ else:
831
+ for i in range(self.read_frames,start_frame):
832
+ ret, frame = self.cap.read()
833
+ self.read_frames += 1
834
+ if not ret:
835
+ break
836
+ self.extracted_frames = []
837
+ shutil.rmtree(self.sam_extract_dir, ignore_errors=True)
838
+ os.makedirs(self.sam_extract_dir, exist_ok=True)
839
+ for i in range(start_frame,end_frame):
840
+ ret, frame = self.cap.read()
841
+ self.read_frames += 1
842
+ if not ret:
843
+ break
844
+ if frame_count % interval == 0:
845
+ frame_path = os.path.join(self.extract_dir, f"{i:06d}.jpg")
846
+ self.extracted_frames.append(frame_path)
847
+ cv2.imwrite(frame_path, frame)
848
+ cv2.imwrite(os.path.join(self.sam_extract_dir, f"{i:06d}.jpg"), frame)
849
+ saved_count += 1
850
+ frame_count += 1
851
+ progress = (frame_count / (end_frame - start_frame)) * 100
852
+ progress_var.set(progress)
853
+ ret, frame = self.cap.read()
854
+ if ret:
855
+ frame_path = os.path.join(self.extract_dir, f"{(i+1):06d}.jpg")
856
+ self.extra_frame_path[self.current_block] = frame_path
857
+ cv2.imwrite(os.path.join(self.sam_extract_dir, f"{(i+1):06d}.jpg"), frame)
858
+ else:
859
+ self.extra_frame_path[self.current_block] = None
860
+ self.media_files = self.extracted_frames
861
+ self.curr_img_idx = -1
862
+
863
+ # RENDER FRAME
864
+
865
+ def hex_to_rgb(self, hex_color):
866
+ hex_color = hex_color.lstrip('#')
867
+ return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
868
+ def create_overlay_img(self,path = None,overwrite = False):
869
+ alpha = getattr(self, "alpha", 0.6)
870
+ if path is None:
871
+ file_path = self.media_files[self.curr_img_idx]
872
+ else:
873
+ file_path = path
874
+ if self.cache_images and path in self.overlay_imgs and not overwrite:
875
+ return self.overlay_imgs[file_path]
876
+ img_rgb = cv2.cvtColor(cv2.imread(file_path), cv2.COLOR_BGR2RGB)
877
+ self.curr_img_shape = img_rgb.shape
878
+ combined_mask = self.create_combined_mask(path, overwrite=overwrite)
879
+ has_mask = np.any(combined_mask > 0, axis=-1)
880
+ blended = img_rgb.copy()
881
+ if np.any(has_mask):
882
+ overlay_blend = cv2.addWeighted(img_rgb, 1.0 - alpha, combined_mask, alpha, 0)
883
+ blended[has_mask] = overlay_blend[has_mask]
884
+ return blended
885
+ def create_combined_mask(self,path = None, overwrite = False):
886
+ if path is None:
887
+ path = self.media_files[self.curr_img_idx]
888
+ if self.cache_images and (path in self.combined_masks) and (not overwrite):
889
+ return self.combined_masks[path]
890
+ mask_overlay = np.zeros(self.curr_img_shape,dtype=np.uint8)
891
+ if hasattr(self, 'masks') and path in self.masks:
892
+ for label_name, mask in self.masks[path].items():
893
+ label_color = None
894
+ for label in self.sam_handler.labels:
895
+ if label.name == label_name:
896
+ label_color = self.hex_to_rgb(label.col)
897
+ break
898
+ if label_color is None:
899
+ label_color = (255, 255, 255)
900
+ mask_overlay[self.masks[path][label_name]] = label_color
901
+ return mask_overlay
902
+ def get_img_to_resize(self):
903
+ if self.view_mode == "overlay":
904
+ if not hasattr(self, 'masks'):
905
+ return None
906
+ return self.create_overlay_img()
907
+ elif self.view_mode == "masks":
908
+ if not hasattr(self, 'masks'):
909
+ return None
910
+ return self.create_combined_mask()
911
+ else:
912
+ if not hasattr(self, 'original_img'):
913
+ return None
914
+ if self.curr_img_idx == -1:
915
+ return None
916
+ original_img = cv2.cvtColor(cv2.imread(self.media_files[self.curr_img_idx]), cv2.COLOR_BGR2RGB)
917
+ self.curr_img_shape = original_img.shape
918
+ return original_img
919
+
920
+ # ADD PROMPT
921
+
922
+ def add_point_prompt_to_label(self,x, y, pt_type,frame_idx, label_idx):
923
+ self.sam_handler.labels[label_idx].add_pt(x, y, pt_type,frame_idx,self.current_block)
924
+ def add_box_prompt_to_label(self,fx,fy, x, y, pt_type,frame_idx, label_idx):
925
+ self.sam_handler.labels[label_idx].add_box(fx, fy, x, y, pt_type,frame_idx,self.current_block)
926
+ def add_point_prompt_to_current_label(self,x, y, pt_type,frame_idx):
927
+ self.sam_handler.labels[self.curr_label_idx].add_pt(x, y, pt_type,frame_idx,self.current_block)
928
+ def add_box_prompt_to_current_label(self,fx,fy, x, y, pt_type,frame_idx):
929
+ self.sam_handler.labels[self.curr_label_idx].add_box(fx, fy, x, y, pt_type,frame_idx,self.current_block)
930
+
931
+ # SWITCH IMG
932
+
933
+ def load_img(self, image_path):
934
+ self.original_img = Image.open(image_path)
935
+ def set_img(self,idx):
936
+ if not self.media_files:
937
+ return
938
+ self.curr_img_idx = idx
939
+ self.refresh_img_data()
940
+ def next_img(self):
941
+ if not self.media_files:
942
+ return
943
+ if self.curr_img_idx < len(self.media_files) - 1:
944
+ self.curr_img_idx += 1
945
+ self.refresh_img_data()
946
+ def prev_img(self):
947
+ if not self.media_files:
948
+ return
949
+ if self.curr_img_idx > 0:
950
+ self.curr_img_idx -= 1
951
+ self.refresh_img_data()
952
+ def refresh_img_data(self):
953
+ if self.view_mode == "original":
954
+ self.load_img(self.media_files[self.curr_img_idx])
955
+ elif self.view_mode == "prompts":
956
+ self.load_img(self.media_files[self.curr_img_idx])
957
+ elif self.view_mode == "overlay":
958
+ if self.media_files[self.curr_img_idx] not in self.masks:
959
+ self.load_img(self.media_files[self.curr_img_idx])
960
+ self.view_mode = "original"
961
+ else:
962
+ overlay_img = self.create_overlay_img()
963
+ if not isinstance(overlay_img,Image.Image):
964
+ self.overlay_img = Image.fromarray(overlay_img)
965
+ else:
966
+ self.overlay_img = overlay_img
967
+ else:
968
+ if self.media_files[self.curr_img_idx] not in self.masks:
969
+ self.load_img(self.media_files[self.curr_img_idx])
970
+ self.view_mode = "original"
971
+ else:
972
+ composite_mask = self.create_combined_mask()
973
+ if not isinstance(composite_mask,Image.Image):
974
+ self.composite_mask = Image.fromarray(composite_mask)
975
+ else:
976
+ self.composite_mask = composite_mask
977
+ class PackedMasks:
978
+ def __init__(self, arr):
979
+ arr = np.asarray(arr, dtype=bool)
980
+ self.data = np.packbits(arr, axis=-1)
981
+ self.h, self.w = arr.shape
982
+ def _unpack(self):
983
+ return np.unpackbits(self.data, axis=-1)[:, :self.w].astype(bool)
984
+ def get(self):
985
+ return self._unpack()
986
+ def set(self, arr):
987
+ arr = np.asarray(arr, dtype=bool)
988
+ self.data = np.packbits(arr, axis=-1)
989
+ self.h, self.w = arr.shape
990
+ def __array__(self, dtype=None):
991
+ arr = self._unpack()
992
+ return arr.astype(dtype) if dtype is not None else arr
993
+ def __getitem__(self, key):
994
+ return self._unpack()[key]
995
+ def __setitem__(self, key, value):
996
+ arr = self._unpack()
997
+ arr[key] = value
998
+ self.set(arr)
999
+ def _binary_op(self, other, op):
1000
+ return op(self._unpack(), other)
1001
+ def astype(self, dtype, **kwargs):
1002
+ return self._unpack().astype(dtype, **kwargs)
1003
+ def __gt__(self, other):
1004
+ return self._binary_op(other, np.greater)
1005
+
1006
+ def __ge__(self, other):
1007
+ return self._binary_op(other, np.greater_equal)
1008
+
1009
+ def __lt__(self, other):
1010
+ return self._binary_op(other, np.less)
1011
+
1012
+ def __le__(self, other):
1013
+ return self._binary_op(other, np.less_equal)
1014
+
1015
+ def __eq__(self, other):
1016
+ return self._binary_op(other, np.equal)
1017
+
1018
+ def __ne__(self, other):
1019
+ return self._binary_op(other, np.not_equal)