-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1207 lines (1061 loc) · 55.2 KB
/
Copy pathmain.py
File metadata and controls
1207 lines (1061 loc) · 55.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# @Author : LG
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtGui import QColor
from ui.mainwindow import Ui_MainWindow
from opengl_widget import GLWidget
from functools import partial
import sys
from utils.pointcloud import PointCloudReadThread
from utils.ground_filter import USE_CSF, GroundFilterThread
from utils.elevation import ElevationColorThread
from widgets.category_choice_dialog import CategoryChoiceDialog
from widgets.setting_dialog import SettingDialog
from widgets.about_dialog import AboutDialog
from widgets.shortcut_doalog import ShortCutDialog
from collections import OrderedDict, deque
from configs import load_config, save_config, DEFAULT_CONFIG_FILE, MODE, DISPLAY
from json import load, dump
import functools
import numpy as np
import os
from typing import Optional
class PreAnnotateThread(QtCore.QThread):
finished_ok = QtCore.pyqtSignal(str, object, object, dict)
failed = QtCore.pyqtSignal(str)
def __init__(self, file_path: str, point_xyz: np.ndarray, point_offset: np.ndarray, caches: list,
radius: float, k: int, uncls_index: int, max_prev_points: int = 400000,
min_hit_fraction: float = 0.01):
super().__init__()
self.file_path = file_path
self.point_xyz = np.array(point_xyz, dtype=np.float32, copy=True)
self.point_offset = np.array(point_offset, dtype=np.float32, copy=True)
self.caches = caches[:] if isinstance(caches, list) else list(caches)
self.radius = float(radius)
self.k = int(k)
self.uncls_index = int(uncls_index)
self.max_prev_points = int(max_prev_points)
self.min_hit_fraction = float(min_hit_fraction)
def run(self):
try:
import math
N = int(self.point_xyz.shape[0])
# Gather non-empty caches
non_empty = []
for c in self.caches:
try:
cats = c.get('cats', None)
if cats is None:
continue
if int(np.asarray(cats).shape[0]) > 0:
non_empty.append(c)
except Exception:
continue
frames_used = len(non_empty)
if frames_used == 0:
self.finished_ok.emit(self.file_path, None, None, {'total': N, 'hit': 0, 'used_radius': None, 'mode': None, 'frames_used': 0})
return
concat_world, concat_local, concat_cats, concat_ins = [], [], [], []
for c in non_empty:
if 'xyz_world' in c:
concat_world.append(np.asarray(c['xyz_world'], dtype=np.float32))
elif 'xyz' in c:
concat_world.append(np.asarray(c['xyz'], dtype=np.float32))
if 'xyz_local' in c:
concat_local.append(np.asarray(c['xyz_local'], dtype=np.float32))
concat_cats.append(np.asarray(c['cats'], dtype=np.int16))
concat_ins.append(np.asarray(c['ins'], dtype=np.int16))
prev_world = np.concatenate(concat_world, axis=0) if len(concat_world) > 0 else None
prev_local = np.concatenate(concat_local, axis=0) if len(concat_local) > 0 else None
prev_cats = np.concatenate(concat_cats, axis=0) if len(concat_cats) > 0 else np.empty((0,), dtype=np.int16)
prev_ins = np.concatenate(concat_ins, axis=0) if len(concat_ins) > 0 else np.empty((0,), dtype=np.int16)
total_prev = int(prev_cats.shape[0])
if total_prev > self.max_prev_points and total_prev > 0:
rng = np.random.default_rng()
idx = rng.choice(total_prev, size=self.max_prev_points, replace=False)
prev_cats = prev_cats[idx]
prev_ins = prev_ins[idx]
if prev_world is not None:
prev_world = prev_world[idx]
if prev_local is not None:
prev_local = prev_local[idx]
def run_with(prev_xyz: np.ndarray, curr_xyz: np.ndarray, base_radius: float):
Nloc = curr_xyz.shape[0]
cats_out = np.full(Nloc, self.uncls_index, dtype=np.int16)
ins_out = np.zeros(Nloc, dtype=np.int16)
def pass_once(rr: float):
rr = float(max(1e-6, rr))
cell = rr * 0.75
inv = 1.0 / cell
buckets = {}
for i in range(prev_xyz.shape[0]):
key = tuple(np.floor(prev_xyz[i] * inv).astype(np.int64).tolist())
lst = buckets.get(key)
if lst is None:
buckets[key] = [i]
else:
lst.append(i)
r_cells = int(math.ceil(rr / cell))
nbr_offsets = [(dx, dy, dz)
for dx in range(-r_cells, r_cells + 1)
for dy in range(-r_cells, r_cells + 1)
for dz in range(-r_cells, r_cells + 1)]
r2 = rr * rr
kk = int(max(1, self.k))
hits_local = 0
for i in range(Nloc):
p = curr_xyz[i]
base = tuple(np.floor(p * inv).astype(np.int64).tolist())
cand_idx = []
for off in nbr_offsets:
key = (base[0] + off[0], base[1] + off[1], base[2] + off[2])
lst = buckets.get(key)
if lst:
cand_idx.extend(lst)
if not cand_idx:
continue
cand_idx_arr = np.asarray(cand_idx, dtype=np.int32)
d2 = np.sum((prev_xyz[cand_idx_arr] - p) ** 2, axis=1)
within = np.where(d2 <= r2)[0]
if within.size == 0:
continue
sel = within[np.argsort(d2[within])[:kk]]
neigh_idx = cand_idx_arr[sel]
cats = prev_cats[neigh_idx]
if cats.size == 1:
cat = int(cats[0])
else:
vals, counts = np.unique(cats, return_counts=True)
cat = int(vals[np.argmax(counts)])
cats_out[i] = cat
nearest = neigh_idx[np.argmin(d2[sel])]
ins_out[i] = int(prev_ins[nearest])
hits_local += 1
return hits_local
used_r = None
hits_total = 0
for scale in (1.0, 2.0, 4.0, 8.0):
rr = base_radius * scale
hits_total = pass_once(rr)
used_r = rr
if hits_total >= max(1, int(self.min_hit_fraction * Nloc)):
break
return hits_total, used_r, cats_out, ins_out
best_mode, best_hits, best_r, best_cats, best_ins = None, -1, None, None, None
if prev_world is not None and prev_world.shape[0] > 0:
curr_world = (self.point_xyz + self.point_offset).astype(np.float32, copy=False)
hits_w, r_w, cats_w, ins_w = run_with(prev_world.astype(np.float32, copy=False), curr_world, self.radius)
best_mode, best_hits, best_r, best_cats, best_ins = 'world', hits_w, r_w, cats_w, ins_w
if (best_hits < max(1, int(self.min_hit_fraction * N))) and (prev_local is not None) and (prev_local.shape[0] > 0):
curr_local = self.point_xyz.astype(np.float32, copy=False)
hits_l, r_l, cats_l, ins_l = run_with(prev_local.astype(np.float32, copy=False), curr_local, self.radius)
if hits_l >= best_hits:
best_mode, best_hits, best_r, best_cats, best_ins = 'local', hits_l, r_l, cats_l, ins_l
stats = {'total': N, 'hit': int(max(0, best_hits)), 'used_radius': best_r, 'mode': best_mode, 'frames_used': frames_used}
self.finished_ok.emit(self.file_path, best_cats, best_ins, stats)
except Exception as e:
self.failed.emit(str(e))
class Mainwindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super(Mainwindow, self).__init__()
self.setupUi(self)
self.openGLWidget=GLWidget(self, self)
self.setCentralWidget(self.openGLWidget)
self.actionPick.setEnabled(False)
self.actionCachePick.setEnabled(False)
self.actionFilter.setEnabled(False)
self.dockWidget_files.setVisible(False)
#
self.actionClassify.setVisible(False)
self.actionGround_filter.setVisible(False)
#
self.config_file = DEFAULT_CONFIG_FILE
self.current_file: Optional[str] = None
self.current_root: Optional[str] = None
self.results_root: Optional[str] = None
self.save_state = True
self.category_choice_dialog = CategoryChoiceDialog(self, self)
self.setting_dialog = SettingDialog(self, self)
self.shortcut_dialog = ShortCutDialog(self)
self.about_dialog = AboutDialog(self)
# Action: Reapply Category Colors
self.actionReapplyColors = QtWidgets.QAction(QtGui.QIcon(":/icons/ui/icons/调色盘_platte.svg"), "Reapply Colors", self)
self.actionReapplyColors.setObjectName("actionReapplyColors")
self.actionReapplyColors.setToolTip("Clamp indices and refresh category colors")
self.actionReapplyColors.triggered.connect(self.openGLWidget.reapply_category_colors)
try:
self.toolBar.addAction(self.actionReapplyColors)
except Exception:
pass
try:
self.menuView.addAction(self.actionReapplyColors)
except Exception:
pass
self.message = QtWidgets.QLabel('')
self.statusbar.addPermanentWidget(self.message)
self.point_cloud_read_thread = PointCloudReadThread()
self.point_cloud_read_thread.tag.connect(self.point_cloud_read_thread_finished)
self.point_cloud_read_thread.message.connect(self.show_message)
if USE_CSF:
self.actionGround_filter.setVisible(True)
self.ground_filter_thread = GroundFilterThread()
self.ground_filter_thread.tag.connect(self.ground_filter_thread_finished)
self.ground_filter_thread.message.connect(self.show_message)
self.elevation_color_thread = ElevationColorThread()
self.elevation_color_thread.tag.connect(self.elevation_color_thread_finished)
self.elevation_color_thread.message.connect(self.show_message)
self.category_color_dict: Optional[OrderedDict] = None
self.trans = QtCore.QTranslator()
# 初始化界面
self.info_widget.setVisible(True)
self.label_widget.setVisible(False)
self.init_connect()
self.reload_cfg()
# Auto Save timer: saves when there are unsaved changes and auto-save is enabled
self.auto_save_timer = QtCore.QTimer(self)
self.auto_save_timer.setInterval(800) # ms debounce
self.auto_save_timer.timeout.connect(self._auto_save_tick)
self.auto_save_timer.start()
# Hotkeys: A = previous file, D = next file
self.prev_shortcut = QtWidgets.QShortcut(QtGui.QKeySequence("A"), self)
self.prev_shortcut.activated.connect(self.go_previous_pointcloud)
self.next_shortcut = QtWidgets.QShortcut(QtGui.QKeySequence("D"), self)
self.next_shortcut.activated.connect(self.go_next_pointcloud)
# Pre-annotation defaults
self.preanno_enabled = False
self.preanno_radius = 0.4
self.preanno_k = 3
self.preanno_window_k = 3
self._annot_cache_deque = deque(maxlen=self.preanno_window_k)
self._prev_annot_cache = None
# Async pre-annotation configuration
self.preanno_thread = None
self.preanno_max_prev_points = 400000 # cap concatenated previous annotated points
self.preanno_min_hit_fraction = 0.01 # 1% coverage threshold to early-stop
def open_file(self):
self.dockWidget_files.setVisible(False)
self.listWidget_files.clear()
file, suffix = QtWidgets.QFileDialog.getOpenFileName(self, caption='point cloud file',
filter="point cloud (*.las *.ply *.txt)")
if file:
if not self.close_point_cloud():
return
# Reset pre-annotation window for a new sequence
try:
self._annot_cache_deque.clear()
self._prev_annot_cache = None
except Exception:
pass
self.current_root = os.path.split(file)[0]
self.current_file = file
self.point_cloud_read_thread_start(file)
def open_folder(self):
dir = QtWidgets.QFileDialog.getExistingDirectory(self)
if dir:
self.close_point_cloud()
# Reset pre-annotation window when a new folder is opened
try:
self._annot_cache_deque.clear()
self._prev_annot_cache = None
except Exception:
pass
self.dockWidget_files.setVisible(True)
self.listWidget_files.clear()
self.current_root = dir
file_list = [file for file in os.listdir(dir) if not file.endswith('.json')]
for file in file_list:
item = QtWidgets.QListWidgetItem()
item.setSizeHint(QtCore.QSize(200, 30))
item.setText(file)
self.listWidget_files.addItem(item)
def double_click_files_widget(self, item:QtWidgets.QListWidgetItem):
# Capture current annotations before switching
try:
self._update_prev_cache()
except Exception:
pass
file_path = os.path.join(self.current_root, item.text())
self.current_file = file_path
self.point_cloud_read_thread_start(file_path)
def point_cloud_read_thread_start(self, file_path):
if file_path.endswith('.las') or file_path.endswith('.ply') or file_path.endswith('.txt'):
self.point_cloud_read_thread.set_file_path(file_path) # 传递文件名
self.point_cloud_read_thread.start() # 线程读取文件
else:
QtWidgets.QMessageBox.warning(self, 'Warning', "Only support file endwith '.txt', '.ply', '.las'")
def point_cloud_read_thread_finished(self, tag:bool):
if tag:
pointcloud = self.point_cloud_read_thread.pointcloud
if pointcloud is None:
return
#
label_name = os.path.splitext(os.path.basename(self.current_file))[0] + '.json'
candidate_files = []
if getattr(self, 'results_root', None):
candidate_files.append(os.path.join(self.results_root, label_name))
candidate_files.append('.'.join(self.current_file.split('.')[:-1]) + '.json')
categorys = None
instances = None
for label_file in candidate_files:
if os.path.exists(label_file):
with open(label_file, 'r') as f:
datas = load(f)
info = datas.get('info', '')
if info == 'PSAT label file.':
categorys = datas.get('categorys', [])
instances = datas.get('instances', [])
categorys = np.array(categorys, dtype=np.int16)
instances = np.array(instances, dtype=np.int16)
if categorys.shape[0] != pointcloud.xyz.shape[0] or instances.shape[0] != pointcloud.xyz.shape[0]:
QtWidgets.QMessageBox.warning(self, 'Warning', 'Point cloud size does not match label size!')
if categorys.shape[0] != pointcloud.xyz.shape[0]:
categorys = None
if instances.shape[0] != pointcloud.xyz.shape[0]:
instances = None
# Remap category indices from saved file to current config using index_category_dict
try:
index_category_dict = datas.get('index_category_dict', {})
# JSON keys may be strings; normalize to int
index_category_dict = {int(k): v for k, v in index_category_dict.items()}
except Exception:
index_category_dict = {}
if index_category_dict and categorys is not None:
current_categories = list(self.category_color_dict.keys())
uncls_index = current_categories.index('__unclassified__') if '__unclassified__' in current_categories else 0
# Build old_index -> new_index mapping via category name
remap = {
old: (current_categories.index(cat) if cat in current_categories else uncls_index)
for old, cat in index_category_dict.items()
}
# Apply remap to loaded category indices
categorys = np.array([remap.get(int(i), uncls_index) for i in categorys.tolist()], dtype=np.int16)
break
if pointcloud.num_point < 1:
return
# If no labels found on disk and pre-annotation is enabled, start async pre-annotation (non-blocking)
if categorys is None and instances is None and getattr(self, 'preanno_enabled', False):
try:
self._start_preannotation(pointcloud)
except Exception as e:
self.show_message(f"Pre-annotate start failed: {e}", 5000)
self.openGLWidget.load_vertices(pointcloud, categorys, instances)
#
self.label_num_point.setText('{}'.format(pointcloud.num_point))
self.label_size_x.setText('{:.2f}'.format(pointcloud.size[0]))
self.label_size_y.setText('{:.2f}'.format(pointcloud.size[1]))
self.label_size_z.setText('{:.2f}'.format(pointcloud.size[2]))
self.label_offset_x.setText('{:.2f}'.format(pointcloud.offset[0]))
self.label_offset_y.setText('{:.2f}'.format(pointcloud.offset[1]))
self.label_offset_z.setText('{:.2f}'.format(pointcloud.offset[2]))
self.setWindowTitle(pointcloud.file_path)
self.actionPick.setEnabled(True)
self.actionCachePick.setEnabled(True)
self.actionFilter.setEnabled(True)
# After loading current, update previous-frame annotation cache for next propagation
try:
self._update_prev_cache()
except Exception:
pass
# Update projection overlay if enabled
try:
if getattr(self, 'actionToggleProjection', None) and self.actionToggleProjection.isChecked():
self.openGLWidget.update_projection_for_current(self.current_file)
except Exception:
pass
def ground_filter_thread_start(self):
if self.openGLWidget.pointcloud is None:
return
if self.openGLWidget.category_color is None:
self.openGLWidget.category_color_update()
self.ground_filter_thread.vertices = self.openGLWidget.pointcloud.xyz
self.ground_filter_thread.start()
def ground_filter_thread_finished(self, tag:bool):
if tag:
ground_index = self.ground_filter_thread.ground
self.openGLWidget.categorys[ground_index] = 1
self.openGLWidget.change_color_to_category()
self.save_state = False
def elevation_color_thread_start(self):
if self.openGLWidget.pointcloud is None:
return
self.elevation_color_thread.vertices = self.openGLWidget.pointcloud.xyz
self.elevation_color_thread.start()
def elevation_color_thread_finished(self, tag):
if tag:
self.openGLWidget.elevation_color = self.elevation_color_thread.elevation_color
self.openGLWidget.change_color_to_elevation()
def classify_thread_start(self):
if self.openGLWidget.pointcloud is None:
return
self.classify_thread.vertices = self.openGLWidget.pointcloud.xyz[self.openGLWidget.categorys!=1] # 非地面点
self.classify_thread.start()
def classify_thread_finished(self, tag):
if tag:
seg, ins = self.classify_thread.seg, self.classify_thread.ins
self.show_message("Classifier | Up sampling ...", 10000000)
mask = self.openGLWidget.categorys!=1
self.openGLWidget.categorys[mask] = seg
self.openGLWidget.instances[mask] = ins
self.openGLWidget.category_color_update()
self.openGLWidget.instance_color_update()
self.openGLWidget.change_color_to_category()
self.save_state = False
def close_point_cloud(self):
if not self.save_state:
result = QtWidgets.QMessageBox.question(self, 'Warning', 'Proceed without saved?', QtWidgets.QMessageBox.StandardButton.Yes|QtWidgets.QMessageBox.StandardButton.No, QtWidgets.QMessageBox.StandardButton.No)
if result == QtWidgets.QMessageBox.StandardButton.No:
return False
self.current_file = None
self.openGLWidget.reset()
self.openGLWidget.update()
self.message.clear()
self.save_state = True
self.setWindowTitle("PSAT - Point Cloud Segmentation Annotation Tool")
self.info_widget.setVisible(True)
self.label_num_point.setText('None')
self.label_size_x.setText('None')
self.label_size_y.setText('None')
self.label_size_z.setText('None')
self.label_offset_x.setText('None')
self.label_offset_y.setText('None')
self.label_offset_z.setText('None')
self.label_widget.setVisible(False)
self.actionPick.setEnabled(False)
self.actionCachePick.setEnabled(False)
# Clear pre-annotation caches when closing current sample/sequence
try:
self._annot_cache_deque.clear()
self._prev_annot_cache = None
except Exception:
pass
return True
def open_backgrpund_color_dialog(self):
color = QtWidgets.QColorDialog.getColor(parent=self)
if color.isValid():
self.openGLWidget.set_background_color(color.redF(), color.greenF(), color.blueF())
def show_message(self, message:str, msecs:int=5000):
self.statusbar.showMessage(message, msecs)
def reload_cfg(self):
self.cfg = load_config(self.config_file)
label_dict_list = self.cfg.get('label', [])
d = OrderedDict()
for index, label_dict in enumerate(label_dict_list):
category = label_dict.get('name', '__unclassified__')
color = label_dict.get('color', '#ffffff')
d[category] = color
self.category_color_dict = d
def save_cfg(self, config_file):
save_config(self.cfg, config_file)
def save_category_and_instance(self):
if self.openGLWidget.pointcloud is not None:
if self.openGLWidget.categorys is not None and self.openGLWidget.instances is not None:
if self.current_file is None:
return
base_name = os.path.splitext(os.path.basename(self.current_file))[0] + '.json'
target_dir = self.results_root if getattr(self, 'results_root', None) else os.path.dirname(self.current_file)
os.makedirs(target_dir, exist_ok=True)
label_file = os.path.join(target_dir, base_name)
datas = {}
datas['info'] = 'PSAT label file.'
datas['point cloud file'] = self.current_file
datas['index_category_dict'] = {index: category for index, (category, color) in enumerate(self.category_color_dict.items())}
datas['categorys'] = self.openGLWidget.categorys.tolist()
datas['instances'] = self.openGLWidget.instances.tolist()
with open(label_file, 'w') as f:
dump(datas, f, indent=4)
self.show_message('{} have saved!'.format(label_file))
self.save_state = True
def update_dock(self):
if self.openGLWidget.display == DISPLAY.ELEVATION:
self.info_widget.setVisible(True)
self.label_widget.setVisible(False)
self.dockWidget.setWindowTitle('Elevation')
self.label_num_point.setText('{}'.format(self.openGLWidget.pointcloud.num_point))
self.label_size_x.setText('{:.2f}'.format(self.openGLWidget.pointcloud.size[0]))
self.label_size_y.setText('{:.2f}'.format(self.openGLWidget.pointcloud.size[1]))
self.label_size_z.setText('{:.2f}'.format(self.openGLWidget.pointcloud.size[2]))
self.label_offset_x.setText('{:.2f}'.format(self.openGLWidget.pointcloud.offset[0]))
self.label_offset_y.setText('{:.2f}'.format(self.openGLWidget.pointcloud.offset[1]))
self.label_offset_z.setText('{:.2f}'.format(self.openGLWidget.pointcloud.offset[2]))
if self.openGLWidget.display == DISPLAY.RGB:
self.info_widget.setVisible(True)
self.label_widget.setVisible(False)
self.dockWidget.setWindowTitle('RGB')
self.label_num_point.setText('{}'.format(self.openGLWidget.pointcloud.num_point))
self.label_size_x.setText('{:.2f}'.format(self.openGLWidget.pointcloud.size[0]))
self.label_size_y.setText('{:.2f}'.format(self.openGLWidget.pointcloud.size[1]))
self.label_size_z.setText('{:.2f}'.format(self.openGLWidget.pointcloud.size[2]))
self.label_offset_x.setText('{:.2f}'.format(self.openGLWidget.pointcloud.offset[0]))
self.label_offset_y.setText('{:.2f}'.format(self.openGLWidget.pointcloud.offset[1]))
self.label_offset_z.setText('{:.2f}'.format(self.openGLWidget.pointcloud.offset[2]))
if self.openGLWidget.display == DISPLAY.CATEGORY:
self.info_widget.setVisible(False)
self.label_widget.setVisible(True)
self.dockWidget.setWindowTitle('Category')
self.label_listWidget.clear()
for index, (category, color) in enumerate(self.category_color_dict.items()):
item = QtWidgets.QListWidgetItem()
item.setSizeHint(QtCore.QSize(200, 30))
widget = QtWidgets.QWidget()
layout = QtWidgets.QHBoxLayout()
layout.setContentsMargins(9, 1, 9, 1)
check_box = QtWidgets.QCheckBox()
check_box.setFixedWidth(20)
check_box.setChecked(self.openGLWidget.category_display_state_dict.get(index, True))
check_box.setObjectName('check_box')
check_box.stateChanged.connect(functools.partial(self.point_cloud_visible))
label_category = QtWidgets.QLabel()
label_category.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
label_category.setText(category)
label_category.setObjectName('label_category')
label_color = QtWidgets.QLabel()
label_color.setFixedWidth(10)
label_color.setStyleSheet("background-color: {};".format(color))
label_color.setObjectName('label_color')
layout.addWidget(check_box)
layout.addWidget(label_color)
layout.addWidget(label_category)
widget.setLayout(layout)
self.label_listWidget.addItem(item)
self.label_listWidget.setItemWidget(item, widget)
if self.openGLWidget.display == DISPLAY.INSTANCE:
self.info_widget.setVisible(False)
self.label_widget.setVisible(True)
self.dockWidget.setWindowTitle('Instance')
self.label_listWidget.clear()
instances_set = list(set(self.openGLWidget.instances.tolist()))
instances_set.sort()
color_map = (self.openGLWidget.color_map * 255).astype(np.int32)
for index in instances_set:
item = QtWidgets.QListWidgetItem()
item.setSizeHint(QtCore.QSize(200, 30))
widget = QtWidgets.QWidget()
layout = QtWidgets.QHBoxLayout()
layout.setContentsMargins(9, 1, 9, 1)
check_box = QtWidgets.QCheckBox()
check_box.setFixedWidth(20)
check_box.setChecked(self.openGLWidget.instance_display_state_dict.get(index, True))
check_box.setObjectName('check_box')
check_box.stateChanged.connect(functools.partial(self.point_cloud_visible))
label_instance = QtWidgets.QLabel()
label_instance.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
label_instance.setText('{}'.format(index))
label_instance.setObjectName('label_instance')
c = color_map[index].tolist()
color = QColor(int(c[0]), int(c[1]), int(c[2]))
label_color = QtWidgets.QLabel()
label_color.setFixedWidth(10)
label_color.setStyleSheet("background-color: {};".format(color.name()))
label_color.setObjectName('label_color')
layout.addWidget(check_box)
layout.addWidget(label_color)
layout.addWidget(label_instance)
widget.setLayout(layout)
self.label_listWidget.addItem(item)
self.label_listWidget.setItemWidget(item, widget)
def point_cloud_visible(self):
if self.openGLWidget.display == DISPLAY.CATEGORY:
mask = np.ones(self.openGLWidget.categorys.shape, dtype=bool)
for index in range(self.label_listWidget.count()):
item = self.label_listWidget.item(index)
widget = self.label_listWidget.itemWidget(item)
check_box = widget.findChild(QtWidgets.QCheckBox, 'check_box')
if not check_box.isChecked():
mask[self.openGLWidget.categorys==index] = False
self.openGLWidget.category_display_state_dict[index] = False
else:
self.openGLWidget.category_display_state_dict[index] = True
self.openGLWidget.mask = mask
self.openGLWidget.current_vertices = self.openGLWidget.pointcloud.xyz[self.openGLWidget.mask]
self.openGLWidget.current_colors = self.openGLWidget.category_color[self.openGLWidget.mask]
elif self.openGLWidget.display == DISPLAY.INSTANCE:
mask = np.ones(self.openGLWidget.instances.shape, dtype=bool)
for index in range(self.label_listWidget.count()):
item = self.label_listWidget.item(index)
widget = self.label_listWidget.itemWidget(item)
label_instance = widget.findChild(QtWidgets.QLabel, 'label_instance')
label_instance = int(label_instance.text())
check_box = widget.findChild(QtWidgets.QCheckBox, 'check_box')
if not check_box.isChecked():
mask[self.openGLWidget.instances==label_instance] = False
self.openGLWidget.instance_display_state_dict[label_instance] = False
else:
self.openGLWidget.instance_display_state_dict[label_instance] = True
self.openGLWidget.mask = mask
self.openGLWidget.current_vertices = self.openGLWidget.pointcloud.xyz[self.openGLWidget.mask]
self.openGLWidget.current_colors = self.openGLWidget.instance_color[self.openGLWidget.mask]
self.openGLWidget.init_vertex_vao()
self.openGLWidget.update()
def check_show_all(self):
for index in range(self.label_listWidget.count()):
item = self.label_listWidget.item(index)
widget = self.label_listWidget.itemWidget(item)
check_box = widget.findChild(QtWidgets.QCheckBox, 'check_box')
check_box.setChecked(self.checkBox_showall.isChecked())
self.openGLWidget.mask.fill(self.checkBox_showall.isChecked())
self.openGLWidget.init_vertex_vao()
self.openGLWidget.update()
def setting(self):
self.setting_dialog.load_cfg()
self.setting_dialog.show()
def translate(self, language='zh'):
if language == 'zh':
self.trans.load('ui/zh_CN')
else:
self.trans.load('ui/en')
self.actionChinese.setChecked(language=='zh')
self.actionEnglish.setChecked(language=='en')
_app = QtWidgets.QApplication.instance()
_app.installTranslator(self.trans)
self.retranslateUi(self)
self.category_choice_dialog.retranslateUi(self.category_choice_dialog)
self.setting_dialog.retranslateUi(self.setting_dialog)
self.about_dialog.retranslateUi(self.about_dialog)
self.shortcut_dialog.retranslateUi(self.shortcut_dialog)
def translate_to_chinese(self):
self.translate('zh')
self.cfg['language'] = 'zh'
def translate_to_english(self):
self.translate('en')
self.cfg['language'] = 'en'
def load_projection_calibration(self):
"""
Select calibration.json (with camera_to_image, dist, lidar_to_camera) and optionally an image folder.
Then update the projection overlay for the current point cloud if enabled.
"""
try:
json_path, _ = QtWidgets.QFileDialog.getOpenFileName(self, caption='Select calibration.json', filter='JSON (*.json)')
if not json_path:
return
ok = self.openGLWidget.load_projection_from_file(json_path)
if not ok:
QtWidgets.QMessageBox.warning(self, 'Warning', 'Invalid calibration file or parse error.')
return
# If calibration didn’t define an image folder, ask user
if not getattr(self.openGLWidget, 'proj_image_folder', None):
img_dir = QtWidgets.QFileDialog.getExistingDirectory(self, caption='Select image folder')
if img_dir:
self.openGLWidget.proj_image_folder = img_dir
# Default image extension if not set by calibration
if not getattr(self.openGLWidget, 'proj_image_ext', None):
self.openGLWidget.proj_image_ext = '.jpg'
# If user has toggled overlay ON and a point cloud is loaded, update now
if getattr(self, 'actionToggleProjection', None) and self.actionToggleProjection.isChecked():
if self.current_file and os.path.isfile(self.current_file):
self.openGLWidget.update_projection_for_current(self.current_file)
else:
self.show_message('Calibration loaded. Open a point cloud to see projection.', 4000)
except Exception as e:
self.show_message(f'Failed to load calibration: {e}', 5000)
def shortcut(self):
self.shortcut_dialog.show()
def about(self):
self.about_dialog.show()
def on_actionAutoSave_toggled(self, checked: bool):
# Update statusbar message when Auto Save toggled
self.show_message(f"Auto Save {'enabled' if checked else 'disabled'}")
def _auto_save_tick(self):
# Periodically auto-save when dirty and auto-save is enabled
try:
if hasattr(self, 'actionAutoSave') and self.actionAutoSave.isChecked():
if not self.save_state:
self.save_category_and_instance()
except Exception:
# Avoid any unexpected timer crash; do nothing
pass
def go_previous_pointcloud(self):
self._navigate_pointcloud(-1)
def go_next_pointcloud(self):
self._navigate_pointcloud(1)
def _navigate_pointcloud(self, direction: int):
"""
Navigate to previous/next point cloud file within current_root.
direction: -1 for previous (A), +1 for next (D)
"""
if self.current_root is None:
return
# Capture current annotations before switching files
try:
self._update_prev_cache()
except Exception:
pass
try:
files = [f for f in os.listdir(self.current_root) if not f.endswith('.json')]
except Exception:
return
if not files:
return
files.sort()
if self.current_file is None:
target_index = 0 if direction > 0 else len(files) - 1
else:
basename = os.path.basename(self.current_file)
try:
idx = files.index(basename)
except ValueError:
idx = 0
target_index = (idx + direction) % len(files)
target_name = files[target_index]
target_path = os.path.join(self.current_root, target_name)
# Reflect selection in list widget if present
for i in range(self.listWidget_files.count()):
item = self.listWidget_files.item(i)
if item.text() == target_name:
self.listWidget_files.setCurrentRow(i)
break
self.current_file = target_path
self.point_cloud_read_thread_start(target_path)
def set_preanno_window(self):
"""
Prompt user to set K (number of previous frames to accumulate for pre-annotation).
"""
try:
val, ok = QtWidgets.QInputDialog.getInt(self, "Pre-annotate Window Size", "K (frames):",
value=int(getattr(self, 'preanno_window_k', 3)),
min=1, max=50)
if not ok:
return
self.preanno_window_k = int(val)
# Rebuild deque with new maxlen while keeping most recent caches
old = list(getattr(self, '_annot_cache_deque', []))
self._annot_cache_deque = deque(maxlen=self.preanno_window_k)
if old:
for c in old[-self.preanno_window_k:]:
self._annot_cache_deque.append(c)
self.show_message(f"Pre-annotate window K set to {self.preanno_window_k}")
except Exception as e:
self.show_message(f"Failed to set window size: {e}", 5000)
def _preannotate_from_prev(self, pointcloud, radius: float, k: int):
"""
Pre-annotate using accumulated annotations from up to K previous frames (user-defined window).
Strategy:
1) Concatenate annotated points from the last K frames (skip empty frames).
2) Try world coordinates (xyz + offset) first with progressive radii.
3) If coverage too low, fallback to local (xyz) with progressive radii.
Returns (categorys, instances, stats dict).
"""
import math
# Collect caches from deque (up to K frames)
caches = list(getattr(self, '_annot_cache_deque', []))
non_empty = []
for c in caches:
try:
n = int(c.get('cats', np.empty((0,), dtype=np.int16)).shape[0])
if n > 0:
non_empty.append(c)
except Exception:
continue
frames_used = len(non_empty)
N = pointcloud.xyz.shape[0]
if frames_used == 0:
return None, None, {'total': N, 'hit': 0, 'used_radius': None, 'mode': None, 'frames_used': 0}
# Concatenate world/local coords and labels
concat_world = []
concat_local = []
concat_cats = []
concat_ins = []
for c in non_empty:
if 'xyz_world' in c:
concat_world.append(c['xyz_world'])
elif 'xyz' in c:
concat_world.append(c['xyz'])
if 'xyz_local' in c:
concat_local.append(c['xyz_local'])
concat_cats.append(c['cats'])
concat_ins.append(c['ins'])
prev_world = np.concatenate(concat_world, axis=0) if len(concat_world) > 0 else None
prev_local = np.concatenate(concat_local, axis=0) if len(concat_local) > 0 else None
prev_cats = np.concatenate(concat_cats, axis=0)
prev_ins = np.concatenate(concat_ins, axis=0)
# Prepare outputs
try:
cats_list = list(self.category_color_dict.keys())
uncls_index = cats_list.index('__unclassified__')
except Exception:
uncls_index = 0
def run_with(prev_xyz: np.ndarray, curr_xyz: np.ndarray, base_radius: float):
cats_out = np.full(N, uncls_index, dtype=np.int16)
ins_out = np.zeros(N, dtype=np.int16)
def pass_once(rr: float):
rr = float(max(1e-6, rr))
cell = rr * 0.75
inv = 1.0 / cell
def hkey(p):
return (int(math.floor(p[0] * inv)),
int(math.floor(p[1] * inv)),
int(math.floor(p[2] * inv)))
buckets = {}
for i in range(prev_xyz.shape[0]):
key = hkey(prev_xyz[i])
lst = buckets.get(key)
if lst is None:
buckets[key] = [i]
else:
lst.append(i)
r_cells = int(math.ceil(rr / cell))
nbr_offsets = [(dx, dy, dz)
for dx in range(-r_cells, r_cells + 1)
for dy in range(-r_cells, r_cells + 1)
for dz in range(-r_cells, r_cells + 1)]
r2 = rr * rr
kk = int(max(1, k))
hits_local = 0
for i in range(N):
p = curr_xyz[i]
base = hkey(p)
cand_idx = []
for off in nbr_offsets:
key = (base[0] + off[0], base[1] + off[1], base[2] + off[2])
if key in buckets:
cand_idx.extend(buckets[key])
if not cand_idx:
continue
d2 = np.sum((prev_xyz[cand_idx] - p) ** 2, axis=1)
within = np.where(d2 <= r2)[0]
if within.size == 0:
continue
sel = within[np.argsort(d2[within])[:kk]]
neigh_idx = np.asarray(cand_idx, dtype=np.int32)[sel]
cats = prev_cats[neigh_idx]
if cats.size == 1:
cat = int(cats[0])
else:
vals, counts = np.unique(cats, return_counts=True)
cat = int(vals[np.argmax(counts)])
cats_out[i] = cat
nearest = neigh_idx[np.argmin(d2[sel])]
ins_out[i] = int(prev_ins[nearest])
hits_local += 1
return hits_local
used_r = None
hits_total = 0
for scale in (1.0, 2.0, 4.0, 8.0):
rr = base_radius * scale
hits_total = pass_once(rr)
used_r = rr
if hits_total >= max(1, int(0.01 * N)):
break
return hits_total, used_r, cats_out, ins_out
best_mode = None
best_hits = -1
best_r = None
best_cats = None
best_ins = None
# World coordinates first if available
if prev_world is not None and prev_world.shape[0] > 0:
curr_world = (pointcloud.xyz + pointcloud.offset).astype(np.float32, copy=False)
hits_w, r_w, cats_w, ins_w = run_with(prev_world.astype(np.float32, copy=False),
curr_world,
radius)
best_mode, best_hits, best_r, best_cats, best_ins = 'world', hits_w, r_w, cats_w, ins_w
# Fallback to local
if (best_hits < max(1, int(0.01 * N))) and (prev_local is not None) and (prev_local.shape[0] > 0):
curr_local = pointcloud.xyz.astype(np.float32, copy=False)
hits_l, r_l, cats_l, ins_l = run_with(prev_local.astype(np.float32, copy=False),
curr_local,
radius)
if hits_l >= best_hits:
best_mode, best_hits, best_r, best_cats, best_ins = 'local', hits_l, r_l, cats_l, ins_l
return best_cats, best_ins, {
'total': N,
'hit': int(max(0, best_hits)),
'used_radius': best_r,
'mode': best_mode,
'frames_used': frames_used
}
def _update_prev_cache(self):
"""
Capture current sample's annotated points into cache for next-frame pre-annotation.
Store points that are annotated by category or have a non-zero instance id to be robust.
"""
if self.openGLWidget.pointcloud is None or self.openGLWidget.categorys is None:
self._prev_annot_cache = None
return