SP-TransientBench / codes /annotation tool /labelLidarwave.py
shuinb's picture
Upload STB code utilities
b004d6f verified
Raw
History Blame Contribute Delete
80.4 kB
# visualize_semantic_labels_v3.py
# ------------------------------------------------------------
# Sequential peak annotation workflow + Multi-layer semantic 3D
#
# Added: Traditional Magic Wand UI & Edge-aware region growing
#
# MOD (New Features Request - V3):
# ✅ [Restored] 3D Bins Visualization button and logic.
# ✅ [Modified] Pixel Histogram now works in a dedicated "Inspect" tool mode.
# - Pick/Brush/Eraser: Perform labeling ONLY.
# - Inspect: Performs histogram visualization ONLY (Safe mode).
# ------------------------------------------------------------
import sys
import os
import traceback
import argparse
import numpy as np
import cv2
from glob import glob
from collections import deque
import matplotlib
from concurrent.futures import ProcessPoolExecutor, as_completed
# Set backend before importing pyplot
matplotlib.use("Qt5Agg")
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
try:
import pandas as pd
HAS_PANDAS = True
except ImportError:
HAS_PANDAS = False
print("[Warning] Pandas not installed. TXT->NPY conversion will be disabled.")
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QLabel, QPushButton, QSlider, QRadioButton, QGroupBox,
QSplitter, QSizePolicy, QTextEdit, QScrollArea, QCheckBox,
QButtonGroup, QShortcut, QListWidget, QListWidgetItem,
QProgressBar, QMessageBox, QLineEdit, QFileDialog, QDialog
)
from PyQt5.QtCore import Qt, QPoint, QRect, QThread, pyqtSignal
from PyQt5.QtGui import QImage, QPixmap, QPainter, QColor, QPen, QKeySequence
try:
import open3d as o3d
HAS_OPEN3D = True
except ImportError:
HAS_OPEN3D = False
print("[Warning] Open3D not installed. 3D visualization will be disabled.")
# ==========================================
# Config
# ==========================================
class AppConfig:
IMG_H = 192
IMG_W = 256
NUM_LAYERS = 30
BIN_UNIT = 297 * 1e-12 * 299792458 / 2.0
DEFAULT_SIGNAL_THRESHOLD = 5
DEFAULT_SNR_THRESHOLD = 2.0
LABEL_FWHM_RATIO = 0.5
CLASS_LABELS = [
"Tree (树)", "Road (路)", "Fence (围栏)", "Person (人)",
"Non-motor (非机动车)", "Car (汽车)", "Street Light (路灯)",
"Signage (指示牌)", "Traffic Light (信号灯)", "Door (门)",
"Building (建筑)", "Wall (墙壁)", "Indoor Roof (室内屋顶)",
"Unknown (未知)"
]
CUSTOM_COLORS = {
1: (0, 255, 0), 2: (128, 128, 128), 3: (255, 165, 0),
4: (255, 0, 0), 5: (255, 20, 147), 6: (30, 144, 255),
7: (218, 165, 32), 8: (0, 255, 255), 9: (255, 69, 0),
10: (165, 42, 42), 11: (160, 32, 240), 12: (189, 183, 107),
13: (0, 128, 128), 14: (255, 255, 0)
}
CAM_K = np.array([[120.94, 0.0, 130.41], [0.0, 121.12, 97.12], [0.0, 0.0, 1.0]], dtype=np.float64)
CAM_D = np.array([-0.276, 0.062, 0.0, 0.0, 0.0], dtype=np.float64)
DEFAULT_WAND_TOLERANCE = 15
DEFAULT_WAND_EDGE_HIGH = 80
DEFAULT_WAND_CONNECTIVITY_8 = True
DEFAULT_WAND_EDGE_AWARE = True
def get_class_colors_dict():
colors = {0: (0, 0, 0)}
colors.update(AppConfig.CUSTOM_COLORS)
return colors
CLASS_COLORS = get_class_colors_dict()
def _cv2_cmap(name: str, fallback):
return getattr(cv2, name, fallback)
PEAK_CMAPS = [
("VIRIDIS", _cv2_cmap("COLORMAP_VIRIDIS", cv2.COLORMAP_JET)),
("PLASMA", _cv2_cmap("COLORMAP_PLASMA", cv2.COLORMAP_JET)),
("INFERNO", _cv2_cmap("COLORMAP_INFERNO", cv2.COLORMAP_JET)),
("MAGMA", _cv2_cmap("COLORMAP_MAGMA", cv2.COLORMAP_JET)),
("TURBO", _cv2_cmap("COLORMAP_TURBO", cv2.COLORMAP_JET)),
("JET", cv2.COLORMAP_JET),
("HOT", cv2.COLORMAP_HOT),
("OCEAN", cv2.COLORMAP_OCEAN),
]
# ==========================================
# Helpers (General)
# ==========================================
def load_hist_npy(path: str) -> np.ndarray:
try:
print(f"[Log] Loading NPY: {path}")
data = np.load(path, mmap_mode="r")
if data.ndim == 3:
H, W, B = data.shape
data = data.reshape(-1, B)
elif data.ndim == 1:
data = data.reshape(1, -1)
return np.ascontiguousarray(data, dtype=np.float32)
except Exception as e:
print(f"[Error] Loading {path} failed: {e}", flush=True)
return None
def analyze_peak_structure(vector, peak_idx, noise_floor):
B = len(vector)
peak_val = vector[peak_idx]
if peak_val <= noise_floor:
return (peak_idx, peak_idx), (peak_idx, peak_idx)
label_thresh = peak_val * AppConfig.LABEL_FWHM_RATIO
l_lab, r_lab = peak_idx, peak_idx
while l_lab > 0 and vector[l_lab] > label_thresh:
l_lab -= 1
while r_lab < B - 1 and vector[r_lab] > label_thresh:
r_lab += 1
l_rem, r_rem = peak_idx, peak_idx
while l_rem > 0:
if vector[l_rem] < noise_floor or vector[l_rem - 1] > vector[l_rem]:
break
l_rem -= 1
while r_rem < B - 1:
if vector[r_rem] < noise_floor or vector[r_rem + 1] > vector[r_rem]:
break
r_rem += 1
l_rem = min(l_rem, l_lab)
r_rem = max(r_rem, r_lab)
return (l_lab, r_lab), (l_rem, r_rem)
def safe_numpy_to_pixmap(img_data):
if img_data is None:
return None
h, w = img_data.shape[:2]
try:
if not img_data.flags["C_CONTIGUOUS"]:
img_data = np.ascontiguousarray(img_data)
if img_data.ndim == 2:
qimg = QImage(img_data.data, w, h, w, QImage.Format_Grayscale8).copy()
elif img_data.ndim == 3:
if img_data.shape[2] == 3:
img_rgba = cv2.cvtColor(img_data, cv2.COLOR_BGR2RGBA)
qimg = QImage(img_rgba.data, w, h, w * 4, QImage.Format_RGBA8888).copy()
elif img_data.shape[2] == 4:
qimg = QImage(img_data.data, w, h, w * 4, QImage.Format_RGBA8888).copy()
else:
return None
else:
return None
return QPixmap.fromImage(qimg)
except Exception:
return None
def get_robust_colors(values, colormap_name="jet", p_min=2, p_max=99.5):
vmin, vmax = np.percentile(values, [p_min, p_max])
denom = max(vmax - vmin, 1e-6)
norm_values = np.clip((values - vmin) / denom, 0, 1)
cmap = plt.get_cmap(colormap_name)
colors = cmap(norm_values)[:, :3]
return colors
def sem_bins_to_layers(sem_bins: np.ndarray, H: int, W: int, num_layers: int):
N, B = sem_bins.shape
masks = [np.zeros((H, W), dtype=np.uint8) for _ in range(num_layers)]
flat = sem_bins
for i in range(N):
row = flat[i]
nz = np.flatnonzero(row)
if nz.size == 0:
continue
breaks = np.flatnonzero(np.diff(nz) != 1)
run_starts = np.concatenate(([0], breaks + 1))
run_ends = np.concatenate((breaks, [nz.size - 1]))
segments = []
for rs, re in zip(run_starts, run_ends):
b0 = int(nz[rs])
b1 = int(nz[re])
cid = int(row[b0])
if cid <= 0: continue
segments.append((b0, b1, cid))
segments.sort(key=lambda t: t[0])
y = i // W
x = i % W
for k, (_, __, cid) in enumerate(segments[:num_layers]):
masks[k][y, x] = cid
return masks
def save_iterative_peeling_layers(out_path, raw_data, manual_masks, layer_thresholds, H, W, fallback_thresh):
try:
folder = os.path.dirname(out_path)
if folder and not os.path.exists(folder):
os.makedirs(folder, exist_ok=True)
N, B = raw_data.shape
sem_bins = np.zeros((N, B), dtype=np.uint8)
working_data = raw_data.copy()
saved_count = 0
for l, mask2d in enumerate(manual_masks):
thr = layer_thresholds[l] if layer_thresholds[l] is not None else fallback_thresh
mask_flat = mask2d.reshape(-1)
labeled_idx = np.flatnonzero(mask_flat > 0)
if labeled_idx.size == 0:
continue
for idx in labeled_idx:
cid = int(mask_flat[idx])
hist = working_data[idx]
if np.max(hist) <= thr:
continue
peak_idx = int(np.argmax(hist))
(l_lab, r_lab), (l_rem, r_rem) = analyze_peak_structure(hist, peak_idx, thr)
if r_rem <= l_rem:
continue
sem_bins[idx, l_lab:r_lab + 1] = cid
working_data[idx, l_rem:r_rem + 1] = 0
saved_count += 1
np.save(out_path, sem_bins)
return True, f"Saved: {os.path.basename(out_path)} [Pts: {saved_count}]", saved_count
except Exception as e:
traceback.print_exc()
return False, f"Error saving: {str(e)}", 0
# ==========================================
# Batch Conversion
# ==========================================
def convert_one_file(file_path, output_root):
try:
import pandas as pd
basename = os.path.basename(file_path)
npy_name = os.path.splitext(basename)[0] + '.npy'
out_path = os.path.join(output_root, npy_name)
if os.path.exists(out_path):
return "Skipped (Exists)"
df = pd.read_csv(file_path, sep=r'\s+', header=None, dtype=np.float32, engine='c', memory_map=True)
data = df.values
if data.ndim == 1:
data = data.reshape(1, -1)
np.save(out_path, data)
return "Success"
except Exception as e:
return f"Error: {str(e)}"
class BatchConverterThread(QThread):
progress_signal = pyqtSignal(int, int)
log_signal = pyqtSignal(str)
finished_signal = pyqtSignal(int, int, int)
def __init__(self, root_search_dir, output_dir):
super().__init__()
self.root_search_dir = root_search_dir
self.output_dir = output_dir
self.is_running = True
def run(self):
if not HAS_PANDAS:
self.log_signal.emit("[Error] Pandas not found.")
self.finished_signal.emit(0, 0, 0)
return
self.log_signal.emit(f"Scanning for TXT files in: {self.root_search_dir}")
search_pattern = os.path.join(self.root_search_dir, "**", "RawDataHistogramMap_frame_*.txt")
files = glob(search_pattern, recursive=True)
if not files:
search_pattern_alt = os.path.join(self.root_search_dir, "**", "*.txt")
files = glob(search_pattern_alt, recursive=True)
total_files = len(files)
self.log_signal.emit(f"Found {total_files} files.")
if total_files == 0:
self.finished_signal.emit(0, 0, 0)
return
try:
os.makedirs(self.output_dir, exist_ok=True)
except Exception as e:
self.finished_signal.emit(0, 0, 0)
return
success_count = 0
skip_count = 0
error_count = 0
processed = 0
max_workers = min(os.cpu_count() or 4, 8)
with ProcessPoolExecutor(max_workers=max_workers) as executor:
future_to_file = {executor.submit(convert_one_file, f, self.output_dir): f for f in files}
for future in as_completed(future_to_file):
if not self.is_running:
executor.shutdown(wait=False, cancel_futures=True)
break
result = future.result()
processed += 1
if result == "Success": success_count += 1
elif result == "Skipped (Exists)": skip_count += 1
else: error_count += 1
self.progress_signal.emit(processed, total_files)
self.finished_signal.emit(success_count, skip_count, error_count)
def stop(self):
self.is_running = False
# ==========================================
# GUI widgets
# ==========================================
class CenteredCanvas(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setMouseTracking(True)
self.setFocusPolicy(Qt.StrongFocus)
self.img_pixmap = None
self.zoom = 1.0
self.offset = QPoint(0, 0)
self.last_mouse_pos = QPoint()
self.mode = "pick"
self.panning = False
self.drawing = False
self.start_pos = QPoint()
self.curr_pos = QPoint()
self.action_callback = None
self.mask_overlay = None
self.ghost_overlay = None
self.hide_labels = False
self.ctrl_pressed = False
def set_content(self, pixmap, mask_pixmap, ghost_pixmap=None):
self.img_pixmap = pixmap
self.mask_overlay = mask_pixmap
self.ghost_overlay = ghost_pixmap
self.update()
def fit_to_window(self):
if self.img_pixmap is None:
return
w_view, h_view = self.width(), self.height()
w_img, h_img = self.img_pixmap.width(), self.img_pixmap.height()
if w_img > 0 and h_img > 0:
self.zoom = min(w_view / w_img, h_view / h_img) * 0.98
self.offset = QPoint(0, 0)
self.update()
def paintEvent(self, event):
painter = QPainter(self)
painter.fillRect(self.rect(), QColor(40, 40, 40))
if self.img_pixmap is None:
return
ww, wh = self.width(), self.height()
cx, cy = ww // 2, wh // 2
painter.translate(cx + self.offset.x(), cy + self.offset.y())
painter.scale(self.zoom, self.zoom)
iw, ih = self.img_pixmap.width(), self.img_pixmap.height()
painter.translate(-iw // 2, -ih // 2)
painter.setRenderHint(QPainter.SmoothPixmapTransform, False)
painter.drawPixmap(0, 0, self.img_pixmap)
if not self.hide_labels:
if self.ghost_overlay is not None:
painter.setOpacity(0.30)
painter.drawPixmap(0, 0, self.ghost_overlay)
painter.setOpacity(1.0)
if self.mask_overlay is not None:
painter.setOpacity(1.0)
painter.drawPixmap(0, 0, self.mask_overlay)
# Only draw selection box if NOT in inspect mode or pure panning
if self.drawing and self.mode == "pick":
pen = QPen(Qt.green, 2) if self.ctrl_pressed else QPen(Qt.yellow, 1)
pen.setStyle(Qt.SolidLine if self.ctrl_pressed else Qt.DashLine)
painter.setPen(pen)
painter.drawRect(QRect(self.start_pos, self.curr_pos).normalized())
def get_img_pos(self, widget_pos):
ww, wh = self.width(), self.height()
cx, cy = ww // 2, wh // 2
if self.img_pixmap:
dx = widget_pos.x() - (cx + self.offset.x())
dy = widget_pos.y() - (cy + self.offset.y())
return int(dx / self.zoom + self.img_pixmap.width() / 2), int(dy / self.zoom + self.img_pixmap.height() / 2)
return 0, 0
def wheelEvent(self, event):
self.zoom *= 1.1 if event.angleDelta().y() > 0 else 0.9
self.zoom = max(0.1, min(self.zoom, 50.0))
self.update()
def mousePressEvent(self, event):
if event.button() == Qt.MiddleButton:
self.panning = True
self.last_mouse_pos = event.pos()
self.setCursor(Qt.ClosedHandCursor)
elif event.button() == Qt.LeftButton:
x, y = self.get_img_pos(event.pos())
self.start_pos = QPoint(x, y)
self.curr_pos = QPoint(x, y)
self.drawing = True
if self.mode == "draw" and self.action_callback:
self.action_callback("draw_start", self.start_pos, None)
def mouseMoveEvent(self, event):
if self.panning:
self.offset += event.pos() - self.last_mouse_pos
self.last_mouse_pos = event.pos()
self.update()
else:
x, y = self.get_img_pos(event.pos())
self.curr_pos = QPoint(x, y)
if self.drawing:
if self.mode == "draw" and self.action_callback:
self.action_callback("draw_drag", self.start_pos, self.curr_pos)
self.start_pos = self.curr_pos
elif self.mode == "pick":
self.update()
def mouseReleaseEvent(self, event):
if self.panning:
self.panning = False
self.setCursor(Qt.ArrowCursor)
return
if event.button() == Qt.LeftButton and self.drawing:
self.drawing = False
end_pos = self.curr_pos if not self.curr_pos.isNull() else self.start_pos
if self.mode == "pick" and self.action_callback:
self.action_callback("pick_end_ctrl" if self.ctrl_pressed else "pick_end", self.start_pos, end_pos)
elif self.mode == "draw" and self.action_callback:
self.action_callback("draw_end", end_pos, None)
self.update()
class PopupImageDialog(QDialog):
def __init__(self, pixmap, title, parent=None):
super().__init__(parent)
self.setWindowTitle(title + " (Double click to close)")
self.resize(800, 600)
self.setWindowFlags(Qt.Window)
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
self.viewer = CenteredCanvas()
self.viewer.set_content(pixmap, None)
self.viewer.fit_to_window()
layout.addWidget(self.viewer)
def showEvent(self, event):
self.viewer.fit_to_window()
super().showEvent(event)
class ResizableImage(QWidget):
def __init__(self, parent=None, title=""):
super().__init__(parent)
self.pixmap = None
self.title = title
self.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
self.setMinimumHeight(150)
self.setCursor(Qt.PointingHandCursor)
self.setToolTip("Double click to enlarge (Popup)")
def set_image(self, pixmap):
self.pixmap = pixmap
self.update()
def set_title(self, title: str):
self.title = title
self.update()
def paintEvent(self, event):
painter = QPainter(self)
painter.fillRect(self.rect(), QColor(25, 25, 25))
painter.setPen(Qt.white)
painter.drawText(10, 20, self.title)
if self.pixmap:
target = self.rect().adjusted(0, 25, 0, 0)
scaled = self.pixmap.scaled(target.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)
x = target.x() + (target.width() - scaled.width()) // 2
y = target.y() + (target.height() - scaled.height()) // 2
painter.drawPixmap(x, y, scaled)
def mouseDoubleClickEvent(self, event):
if self.pixmap:
self.pop = PopupImageDialog(self.pixmap, self.title, self)
self.pop.show()
class PixelHistogramDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Pixel Histogram Inspector")
self.resize(600, 450)
self.setWindowFlags(Qt.Window)
layout = QVBoxLayout(self)
self.fig = Figure(figsize=(5, 4), dpi=100)
self.canvas = FigureCanvas(self.fig)
self.canvas.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
layout.addWidget(self.canvas)
self.ax = self.fig.add_subplot(111)
self.status_label = QLabel("Switch tool to 'Inspect' and click pixel.")
layout.addWidget(self.status_label)
def update_plot(self, x, y, raw_vec, labels_info, noise_floor=0):
self.ax.clear()
self.ax.plot(raw_vec, color='black', linewidth=1.0, label='Photon Counts')
max_val = np.max(raw_vec) if raw_vec.size > 0 else 1.0
drawn_labels = set()
for item in labels_info:
cid = item['cid']
l_range, r_range = item['range']
rgb = item['color']
c_norm = (rgb[0]/255.0, rgb[1]/255.0, rgb[2]/255.0)
x_vals = np.arange(l_range, r_range + 1)
if x_vals.size > 0:
label_text = f"Class {cid}"
if cid not in drawn_labels:
self.ax.fill_between(x_vals, 0, max_val * 1.1, color=c_norm, alpha=0.3, label=label_text)
drawn_labels.add(cid)
else:
self.ax.fill_between(x_vals, 0, max_val * 1.1, color=c_norm, alpha=0.3)
if noise_floor > 0:
self.ax.axhline(y=noise_floor, color='gray', linestyle='--', alpha=0.5, label='Noise Level')
self.ax.set_title(f"Pixel ({x}, {y}) | Max: {max_val:.1f}")
self.ax.set_xlabel("Time Bins")
self.ax.set_ylabel("Counts")
self.ax.grid(True, linestyle=':', alpha=0.6)
if drawn_labels:
self.ax.legend(loc='upper right')
self.canvas.draw()
self.status_label.setText(f"Inspecting Pixel: x={x}, y={y}")
# ==========================================
# Main window
# ==========================================
class SPADLabelerPixel(QMainWindow):
def __init__(self, args):
super().__init__()
self.args = args
self.setWindowTitle("SPAD Labeler - Sequential Peak Annotation")
self.resize(1780, 1040)
os.makedirs(self.args.cache_dir, exist_ok=True)
self.H, self.W = AppConfig.IMG_H, AppConfig.IMG_W
self.num_layers = AppConfig.NUM_LAYERS
self.class_names = {i + 1: name for i, name in enumerate(AppConfig.CLASS_LABELS)}
self.UNKNOWN_CID = int(max(self.class_names.keys()))
self.class_colors_rgb = CLASS_COLORS
self.raw_data = None
self.noise_map = None
self.layer_view_cache = {}
self.manual_masks = [np.zeros((self.H, self.W), dtype=np.uint8) for _ in range(self.num_layers)]
self.layer_thresholds = [None for _ in range(self.num_layers)]
self.undo_stack = deque(maxlen=20)
self.is_dirty = False
self.mask_revision = 0
self.brush_size = 5
self.tool_mode = "pick"
self.current_class = 1
self.peel_depth = 0
self.edit_layer = 0
self.region_step = 0
self.peel_by_class = True
self._region_cache_layer = None
self._region_cache_revision = -1
self._region_cache_mode = None
self._region_cache_regions = []
self.wand_tolerance = int(AppConfig.DEFAULT_WAND_TOLERANCE)
self.wand_connectivity_8 = bool(AppConfig.DEFAULT_WAND_CONNECTIVITY_8)
self.wand_edge_aware = bool(AppConfig.DEFAULT_WAND_EDGE_AWARE)
self.wand_edge_high = int(AppConfig.DEFAULT_WAND_EDGE_HIGH)
self.converter_thread = None
self.hist_inspector = None
self.init_ui()
self.file_list = sorted(glob(os.path.join(args.in_dir, args.pattern)))
self.current_file_idx = 0
self.update_file_list_ui()
if self.file_list:
self.load_file(self.file_list[0])
# ---------------- UI ----------------
def init_ui(self):
self.splitter = QSplitter(Qt.Horizontal)
self.setCentralWidget(self.splitter)
self.left_panel = QSplitter(Qt.Vertical)
self.lbl_global = ResizableImage(title="Layer 0 (Raw Peak)")
self.left_panel.addWidget(self.lbl_global)
self.lbl_result = ResizableImage(title="Annotation Preview (Unpeeled + Current Region State)")
self.left_panel.addWidget(self.lbl_result)
self.lbl_info = ResizableImage(title="Peeling View")
self.left_panel.addWidget(self.lbl_info)
self.lbl_depth = ResizableImage(title="Depth Map (Visible Peak)")
self.left_panel.addWidget(self.lbl_depth)
self.left_ctrl = QWidget()
l_lay = QVBoxLayout(self.left_ctrl)
l_lay.addWidget(QLabel("<b>Peel / Edit / Region Control</b>"))
l_lay.addWidget(QLabel("<i>Tip: Double-click images above to enlarge.</i>"))
l_lay.addWidget(QLabel("Peel Depth (display stage):"))
self.sl_peel = QSlider(Qt.Horizontal)
self.sl_peel.setRange(0, self.num_layers)
self.sl_peel.setValue(0)
self.sl_peel.valueChanged.connect(self.change_peel_depth)
l_lay.addWidget(self.sl_peel)
self.lbl_region = QLabel("Semantic Step (current peeled layer): 0 / 0")
l_lay.addWidget(self.lbl_region)
self.sl_region = QSlider(Qt.Horizontal)
self.sl_region.setRange(0, 0)
self.sl_region.setValue(0)
self.sl_region.valueChanged.connect(self.change_region_step)
l_lay.addWidget(self.sl_region)
self.lbl_next_region = QLabel("Selected Peel Target: -")
self.lbl_next_region.setWordWrap(True)
l_lay.addWidget(self.lbl_next_region)
l_lay.addWidget(QLabel("Edit Layer (write target):"))
self.sl_edit = QSlider(Qt.Horizontal)
self.sl_edit.setRange(0, self.num_layers - 1)
self.sl_edit.setValue(0)
self.sl_edit.valueChanged.connect(self.change_edit_layer)
l_lay.addWidget(self.sl_edit)
self.chk_auto_edit = QCheckBox("Auto Edit Layer = Peel Depth (recommended)")
self.chk_auto_edit.setChecked(True)
self.chk_auto_edit.toggled.connect(self.on_auto_edit_toggled)
l_lay.addWidget(self.chk_auto_edit)
self.chk_lock_to_visible = QCheckBox("Lock labeling to visible peak")
self.chk_lock_to_visible.setChecked(True)
self.chk_lock_to_visible.toggled.connect(self.update_all_views)
l_lay.addWidget(self.chk_lock_to_visible)
self.chk_focus_edit = QCheckBox("Focus view to Edit Layer")
self.chk_focus_edit.setChecked(True)
self.chk_focus_edit.toggled.connect(self.update_all_views)
l_lay.addWidget(self.chk_focus_edit)
self.chk_peel_class = QCheckBox("Region Step by Semantic")
self.chk_peel_class.setChecked(True)
self.chk_peel_class.toggled.connect(self.on_peel_mode_changed)
l_lay.addWidget(self.chk_peel_class)
self.lbl_state = QLabel("Peel Depth: 0 | Region Step: 0 | Edit Layer: 0")
l_lay.addWidget(self.lbl_state)
self.lbl_peeled_ids = QLabel("Fully Peeled Layers: None")
self.lbl_peeled_ids.setStyleSheet("color: #FFA500; font-weight: bold;")
l_lay.addWidget(self.lbl_peeled_ids)
self.btn_clear_layer_thr = QPushButton("Clear Layer Threshold Locks")
self.btn_clear_layer_thr.clicked.connect(self.clear_layer_threshold_locks)
l_lay.addWidget(self.btn_clear_layer_thr)
l_lay.addStretch()
self.left_panel.addWidget(self.left_ctrl)
self.left_panel.setSizes([220, 220, 220, 220, 300])
self.splitter.addWidget(self.left_panel)
self.canvas = CenteredCanvas()
self.canvas.action_callback = self.handle_canvas_action
self.splitter.addWidget(self.canvas)
self.right_panel = QWidget()
r_lay = QVBoxLayout(self.right_panel)
r_lay.addWidget(QLabel("<b>File List:</b>"))
self.file_list_widget = QListWidget()
self.file_list_widget.setFixedHeight(200)
self.file_list_widget.currentRowChanged.connect(self.on_file_list_clicked)
r_lay.addWidget(self.file_list_widget)
r_lay.addWidget(QLabel("<b>Batch Convert Config:</b>"))
h_src = QHBoxLayout()
self.txt_source_edit = QLineEdit()
self.txt_source_edit.setText(self.args.in_dir)
self.txt_source_edit.setPlaceholderText("Path to folder with TXT files...")
btn_browse_src = QPushButton("...")
btn_browse_src.setFixedWidth(30)
btn_browse_src.clicked.connect(self.browse_txt_source)
h_src.addWidget(self.txt_source_edit)
h_src.addWidget(btn_browse_src)
r_lay.addLayout(h_src)
self.btn_convert = QPushButton("Batch Convert TXT -> NPY")
self.btn_convert.setStyleSheet("background-color: #3d3d3d; color: #aaffaa;")
self.btn_convert.clicked.connect(self.start_batch_conversion)
r_lay.addWidget(self.btn_convert)
self.pbar = QProgressBar()
self.pbar.setVisible(False)
r_lay.addWidget(self.pbar)
h_nav = QHBoxLayout()
btn_pl = QPushButton("Peel -1 (A)")
btn_pl.clicked.connect(self.apply_peel_prev)
btn_nl = QPushButton("Peel +1 (D)")
btn_nl.clicked.connect(self.apply_peel_next)
h_nav.addWidget(btn_pl)
h_nav.addWidget(btn_nl)
r_lay.addLayout(h_nav)
h_reg = QHBoxLayout()
btn_rprev = QPushButton("Region -1 (Z)")
btn_rprev.clicked.connect(self.region_prev)
btn_rnext = QPushButton("Region +1 (X)")
btn_rnext.clicked.connect(self.region_next)
h_reg.addWidget(btn_rprev)
h_reg.addWidget(btn_rnext)
r_lay.addLayout(h_reg)
h_edit = QHBoxLayout()
btn_el = QPushButton("Edit -1 (Shift+A)")
btn_el.clicked.connect(self.edit_prev)
btn_er = QPushButton("Edit +1 (Shift+D)")
btn_er.clicked.connect(self.edit_next)
h_edit.addWidget(btn_el)
h_edit.addWidget(btn_er)
r_lay.addLayout(h_edit)
h_file = QHBoxLayout()
btn_pf = QPushButton("<< File")
btn_pf.clicked.connect(self.prev_file)
btn_nf = QPushButton("File >>")
btn_nf.clicked.connect(self.next_file)
h_file.addWidget(btn_pf)
h_file.addWidget(btn_nf)
r_lay.addLayout(h_file)
self.chk_autosave = QCheckBox("Auto Save")
self.chk_autosave.setChecked(True)
r_lay.addWidget(self.chk_autosave)
h_viz = QHBoxLayout()
self.chk_ghost = QCheckBox("Ghost (G)")
self.chk_ghost.toggled.connect(self.update_all_views)
self.chk_hide = QCheckBox("Hide (H)")
self.chk_hide.toggled.connect(self.update_all_views)
btn_viz = QPushButton("3D Depth")
btn_viz.clicked.connect(self.visualize_3d_point_cloud)
btn_sem = QPushButton("3D Semantic")
btn_sem.clicked.connect(self.visualize_3d_semantic_point_cloud)
# [RESTORED] 3D Bins Button
btn_bins = QPushButton("3D Bins")
btn_bins.clicked.connect(self.visualize_3d_semantic_bins_point_cloud)
btn_hist = QPushButton("Pixel Hist")
btn_hist.clicked.connect(self.open_pixel_inspector)
h_viz.addWidget(self.chk_ghost)
h_viz.addWidget(self.chk_hide)
h_viz.addWidget(btn_viz)
h_viz.addWidget(btn_sem)
h_viz.addWidget(btn_bins) # Add back
h_viz.addWidget(btn_hist)
r_lay.addLayout(h_viz)
g_filt = QGroupBox("Filter (Threshold & SNR)")
f_lay = QVBoxLayout(g_filt)
self.sl_thresh = QSlider(Qt.Horizontal)
self.sl_thresh.setRange(0, 2000)
self.sl_thresh.setValue(AppConfig.DEFAULT_SIGNAL_THRESHOLD)
self.lbl_thr = QLabel(f"Int Thresh: {AppConfig.DEFAULT_SIGNAL_THRESHOLD}")
self.sl_thresh.valueChanged.connect(self.on_thresh_changed)
h_t = QHBoxLayout()
h_t.addWidget(self.sl_thresh)
h_t.addWidget(self.lbl_thr)
f_lay.addLayout(h_t)
self.sl_snr = QSlider(Qt.Horizontal)
self.sl_snr.setRange(10, 200)
self.sl_snr.setValue(int(AppConfig.DEFAULT_SNR_THRESHOLD * 10))
self.lbl_snr = QLabel(f"SNR (Peak/Mean) > {AppConfig.DEFAULT_SNR_THRESHOLD:.1f}")
self.sl_snr.valueChanged.connect(self.on_snr_changed)
h_s = QHBoxLayout()
h_s.addWidget(self.sl_snr)
h_s.addWidget(self.lbl_snr)
f_lay.addLayout(h_s)
r_lay.addWidget(g_filt)
g_wand = QGroupBox("Magic Wand (传统魔棒)")
w_lay = QVBoxLayout(g_wand)
self.chk_wand_edge = QCheckBox("Edge-aware")
self.chk_wand_edge.setChecked(self.wand_edge_aware)
self.chk_wand_edge.toggled.connect(self.on_wand_params_changed)
w_lay.addWidget(self.chk_wand_edge)
self.chk_wand_conn8 = QCheckBox("8-way connectivity")
self.chk_wand_conn8.setChecked(self.wand_connectivity_8)
self.chk_wand_conn8.toggled.connect(self.on_wand_params_changed)
w_lay.addWidget(self.chk_wand_conn8)
w_lay.addWidget(QLabel("Tolerance:"))
self.sl_wand_tol = QSlider(Qt.Horizontal)
self.sl_wand_tol.setRange(0, 255)
self.sl_wand_tol.setValue(self.wand_tolerance)
self.sl_wand_tol.valueChanged.connect(self.on_wand_tol_changed)
self.lbl_wand_tol = QLabel(str(self.wand_tolerance))
h_tol = QHBoxLayout()
h_tol.addWidget(self.sl_wand_tol)
h_tol.addWidget(self.lbl_wand_tol)
w_lay.addLayout(h_tol)
w_lay.addWidget(QLabel("Edge strength:"))
self.sl_wand_edge = QSlider(Qt.Horizontal)
self.sl_wand_edge.setRange(0, 255)
self.sl_wand_edge.setValue(self.wand_edge_high)
self.sl_wand_edge.valueChanged.connect(self.on_wand_edge_changed)
self.lbl_wand_edge = QLabel(str(self.wand_edge_high))
h_ed = QHBoxLayout()
h_ed.addWidget(self.sl_wand_edge)
h_ed.addWidget(self.lbl_wand_edge)
w_lay.addLayout(h_ed)
r_lay.addWidget(g_wand)
g_tool = QGroupBox("Tools")
t_lay = QVBoxLayout(g_tool)
self.rb_pick = QRadioButton("Pick (Q)")
self.rb_pick.setChecked(True)
self.rb_pick.toggled.connect(self.update_tool_mode)
self.rb_brush = QRadioButton("Brush (W)")
self.rb_brush.toggled.connect(self.update_tool_mode)
self.rb_eraser = QRadioButton("Eraser (E)")
self.rb_eraser.toggled.connect(self.update_tool_mode)
# [NEW] Inspect Mode
self.rb_inspect = QRadioButton("Inspect (I)")
self.rb_inspect.toggled.connect(self.update_tool_mode)
t_lay.addWidget(self.rb_pick)
t_lay.addWidget(self.rb_brush)
t_lay.addWidget(self.rb_eraser)
t_lay.addWidget(self.rb_inspect)
h_sz = QHBoxLayout()
h_sz.addWidget(QLabel("Brush Size:"))
self.sl_size = QSlider(Qt.Horizontal)
self.sl_size.setRange(1, 30)
self.sl_size.setValue(self.brush_size)
self.lbl_size = QLabel(str(self.brush_size))
self.sl_size.valueChanged.connect(self.update_brush_size)
h_sz.addWidget(self.sl_size)
h_sz.addWidget(self.lbl_size)
t_lay.addLayout(h_sz)
self.chk_overwrite = QCheckBox("Allow Overwrite (允许覆盖)")
self.chk_overwrite.setChecked(True)
t_lay.addWidget(self.chk_overwrite)
r_lay.addWidget(g_tool)
g_cls = QGroupBox("Classes")
scroll = QScrollArea()
scroll.setWidgetResizable(True)
content = QWidget()
sc_lay = QVBoxLayout(content)
self.cls_bg = QButtonGroup(self)
self.cls_radios = {}
for cid, name in self.class_names.items():
rgb = self.class_colors_rgb.get(cid, (0, 0, 0))
rb = QRadioButton(f"■ {name}")
rb.setStyleSheet(f"color: rgb{rgb}; font-weight: bold;")
self.cls_bg.addButton(rb, cid)
self.cls_radios[cid] = rb
sc_lay.addWidget(rb)
scroll.setWidget(content)
c_lay = QVBoxLayout(g_cls)
c_lay.addWidget(scroll)
r_lay.addWidget(g_cls)
self.cls_bg.buttonClicked[int].connect(lambda i: setattr(self, "current_class", int(i)))
self.log_win = QTextEdit()
self.log_win.setReadOnly(True)
self.log_win.setFixedHeight(100)
r_lay.addWidget(self.log_win)
btn_unk = QPushButton("Fill Unknown (Layer U)")
btn_unk.clicked.connect(self.fill_unknown_current_layer)
r_lay.addWidget(btn_unk)
btn_save = QPushButton("SAVE (Ctrl+S)")
btn_save.clicked.connect(self.save_current)
r_lay.addWidget(btn_save)
self.splitter.addWidget(self.right_panel)
self.splitter.setSizes([430, 980, 340])
self.init_shortcuts()
self.hist_inspector = PixelHistogramDialog(self)
def init_shortcuts(self):
QShortcut(QKeySequence("A"), self, self.apply_peel_prev)
QShortcut(QKeySequence("D"), self, self.apply_peel_next)
QShortcut(QKeySequence("Z"), self, self.region_prev)
QShortcut(QKeySequence("X"), self, self.region_next)
QShortcut(QKeySequence("Shift+A"), self, self.edit_prev)
QShortcut(QKeySequence("Shift+D"), self, self.edit_next)
QShortcut(QKeySequence("Left"), self, self.prev_file)
QShortcut(QKeySequence("Right"), self, self.next_file)
QShortcut(QKeySequence("Q"), self, lambda: self.rb_pick.setChecked(True))
QShortcut(QKeySequence("W"), self, lambda: self.rb_brush.setChecked(True))
QShortcut(QKeySequence("E"), self, lambda: self.rb_eraser.setChecked(True))
# [NEW] Shortcut for Inspect
QShortcut(QKeySequence("I"), self, lambda: self.rb_inspect.setChecked(True))
QShortcut(QKeySequence("Ctrl+S"), self, self.save_current)
QShortcut(QKeySequence("Ctrl+Z"), self, self.undo)
QShortcut(QKeySequence("U"), self, self.fill_unknown_current_layer)
QShortcut(QKeySequence("H"), self, lambda: self.chk_hide.setChecked(not self.chk_hide.isChecked()))
QShortcut(QKeySequence("G"), self, lambda: self.chk_ghost.setChecked(not self.chk_ghost.isChecked()))
QShortcut(QKeySequence("F"), self, lambda: self.chk_focus_edit.setChecked(not self.chk_focus_edit.isChecked()))
QShortcut(QKeySequence("T"), self, lambda: self.chk_lock_to_visible.setChecked(not self.chk_lock_to_visible.isChecked()))
QShortcut(QKeySequence("R"), self, lambda: self.chk_peel_class.setChecked(not self.chk_peel_class.isChecked()))
QShortcut(QKeySequence("["), self, self.cycle_class_prev)
QShortcut(QKeySequence("]"), self, self.cycle_class_next)
QShortcut(QKeySequence("="), self, lambda: self.morph_current_mask("dilate"))
QShortcut(QKeySequence("-"), self, lambda: self.morph_current_mask("erode"))
keys = [Qt.Key_1, Qt.Key_2, Qt.Key_3, Qt.Key_4, Qt.Key_5,
Qt.Key_6, Qt.Key_7, Qt.Key_8, Qt.Key_9, Qt.Key_0]
for i, key in enumerate(keys):
cls_idx = i + 1
if cls_idx in self.class_names:
QShortcut(QKeySequence(key), self, lambda idx=cls_idx: self.set_class_by_key(idx))
# ---------------- UI Helper Methods ----------------
def browse_txt_source(self):
directory = QFileDialog.getExistingDirectory(
self, "Select TXT Source Directory", self.txt_source_edit.text()
)
if directory:
self.txt_source_edit.setText(directory)
# ---------------- Pixel Inspector ----------------
def open_pixel_inspector(self):
if self.hist_inspector is None:
self.hist_inspector = PixelHistogramDialog(self)
self.hist_inspector.show()
self.hist_inspector.raise_()
self.hist_inspector.activateWindow()
# Auto switch to inspect mode for convenience? Optional.
# self.rb_inspect.setChecked(True)
def update_histogram_inspector(self, x, y):
if self.hist_inspector is None or not self.hist_inspector.isVisible():
# If closed, re-open
self.open_pixel_inspector()
if self.raw_data is None: return
idx = y * self.W + x
if idx >= self.raw_data.shape[0]: return
raw_vec = self.raw_data[idx]
labels_info = self.simulate_pixel_peeling(x, y, raw_vec)
noise = self.noise_map[y, x] if self.noise_map is not None else 0
self.hist_inspector.update_plot(x, y, raw_vec, labels_info, noise)
def simulate_pixel_peeling(self, x, y, raw_vec):
labels_info = []
working_vec = raw_vec.copy()
curr_thr = int(self.sl_thresh.value())
for l in range(self.num_layers):
m = self.manual_masks[l]
cid = int(m[y, x])
if cid > 0:
thr = self.layer_thresholds[l] if self.layer_thresholds[l] is not None else curr_thr
if np.max(working_vec) > thr:
peak_idx = int(np.argmax(working_vec))
(l_lab, r_lab), (l_rem, r_rem) = analyze_peak_structure(working_vec, peak_idx, thr)
if r_lab >= l_lab:
color = self.class_colors_rgb.get(cid, (128, 128, 128))
labels_info.append({'cid': cid, 'range': (l_lab, r_lab), 'color': color})
if r_rem > l_rem:
working_vec[l_rem:r_rem + 1] = 0
return labels_info
# ... [Batch Conversion methods kept same] ...
def start_batch_conversion(self):
if self.converter_thread is not None and self.converter_thread.isRunning(): return
target_dir = self.txt_source_edit.text().strip()
if not target_dir or not os.path.isdir(target_dir):
QMessageBox.warning(self, "Invalid Path", "Please select a valid directory containing TXT files.")
return
script_dir = os.path.dirname(os.path.abspath(__file__))
output_npy_dir = os.path.join(script_dir, "npy")
reply = QMessageBox.question(self, 'Batch Convert',
f"Convert TXT files from:\n{target_dir}\n\nTo NPY files in:\n{output_npy_dir} ?",
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.No: return
self.btn_convert.setEnabled(False)
self.pbar.setVisible(True)
self.pbar.setValue(0)
self.log_win.append(f"Starting batch conversion...")
self.converter_thread = BatchConverterThread(target_dir, output_npy_dir)
self.converter_thread.progress_signal.connect(self.on_conversion_progress)
self.converter_thread.log_signal.connect(self.log_win.append)
self.converter_thread.finished_signal.connect(self.on_conversion_finished)
self.converter_thread.start()
def on_conversion_progress(self, current, total):
self.pbar.setMaximum(total)
self.pbar.setValue(current)
def on_conversion_finished(self, success, skip, error):
self.log_win.append(f"Conversion Done! Success: {success}, Skipped: {skip}, Errors: {error}")
self.pbar.setVisible(False)
self.btn_convert.setEnabled(True)
source_dir = self.txt_source_edit.text().strip()
output_npy_dir = os.path.join(source_dir, "npy")
if os.path.abspath(self.args.in_dir) == os.path.abspath(output_npy_dir):
self.file_list = sorted(glob(os.path.join(self.args.in_dir, self.args.pattern)))
self.update_file_list_ui()
# ---------------- Magic Wand/Tools ----------------
def on_wand_params_changed(self, _=None):
self.wand_edge_aware = bool(self.chk_wand_edge.isChecked())
self.wand_connectivity_8 = bool(self.chk_wand_conn8.isChecked())
def on_wand_tol_changed(self, v):
self.wand_tolerance = int(v)
self.lbl_wand_tol.setText(str(int(v)))
def on_wand_edge_changed(self, v):
self.wand_edge_high = int(v)
self.lbl_wand_edge.setText(str(int(v)))
# ... [State helpers kept same] ...
def clear_layer_cache(self): self.layer_view_cache.clear()
def set_dirty(self):
self.clear_layer_cache()
self.is_dirty = True
self.mask_revision += 1
if " *" not in self.windowTitle(): self.setWindowTitle(self.windowTitle() + " *")
def push_undo(self):
stack = np.stack(self.manual_masks, axis=0).copy()
thr = list(self.layer_thresholds)
self.undo_stack.append((stack, thr, self.peel_depth, self.region_step, self.edit_layer, self.peel_by_class))
def clear_layer_threshold_locks(self):
self.layer_thresholds = [None for _ in range(self.num_layers)]
self.clear_layer_cache()
self.update_all_views()
def _clamp_xy(self, x, y):
x = max(0, min(int(x), self.W - 1))
y = max(0, min(int(y), self.H - 1))
return x, y
def _ensure_layer_threshold(self, layer_idx: int):
if self.layer_thresholds[layer_idx] is None:
self.layer_thresholds[layer_idx] = int(self.sl_thresh.value())
def update_brush_size(self, val):
self.brush_size = int(val)
self.lbl_size.setText(str(self.brush_size))
def on_thresh_changed(self, v):
self.clear_layer_cache()
self.update_all_views()
self.lbl_thr.setText(f"Int Thresh: {int(v)}")
def on_snr_changed(self, v):
val = float(v) / 10.0
self.lbl_snr.setText(f"SNR > {val:.1f}")
self.clear_layer_cache()
self.update_all_views()
def update_tool_mode(self):
# Determine mode
if self.rb_pick.isChecked(): self.tool_mode = "pick"
elif self.rb_brush.isChecked(): self.tool_mode = "brush"
elif self.rb_eraser.isChecked(): self.tool_mode = "eraser"
elif self.rb_inspect.isChecked(): self.tool_mode = "inspect"
# Set canvas visual mode (inspect shares pick cursor logic, but handled differently in click)
if self.tool_mode in ["brush", "eraser"]:
self.canvas.mode = "draw"
else:
self.canvas.mode = "pick"
# ... [Peel/Edit logic kept same] ...
def on_auto_edit_toggled(self, checked):
if checked: self._sync_edit_with_peel()
self.update_all_views()
def on_peel_mode_changed(self, checked):
self.peel_by_class = bool(checked)
self.region_step = 0
self.clear_layer_cache()
self._region_cache_layer = None
self._region_cache_revision = -1
self._region_cache_mode = None
self._region_cache_regions = []
self._sync_region_slider()
self.update_all_views()
def _sync_edit_with_peel(self):
target = min(int(self.peel_depth), self.num_layers - 1)
if int(self.edit_layer) != target:
self.edit_layer = target
self.sl_edit.blockSignals(True)
self.sl_edit.setValue(self.edit_layer)
self.sl_edit.blockSignals(False)
def change_peel_depth(self, idx):
self.peel_depth = int(idx)
self.region_step = 0
if self.chk_auto_edit.isChecked(): self._sync_edit_with_peel()
self._sync_region_slider()
self.update_all_views()
def change_region_step(self, idx):
self.region_step = int(idx)
self.clear_layer_cache()
self.update_all_views()
def change_edit_layer(self, idx):
self.edit_layer = int(idx)
self.update_all_views()
def apply_peel_next(self):
self.peel_depth = min(self.num_layers, self.peel_depth + 1)
self.region_step = 0
self.sl_peel.blockSignals(True)
self.sl_peel.setValue(self.peel_depth)
self.sl_peel.blockSignals(False)
if self.chk_auto_edit.isChecked(): self._sync_edit_with_peel()
self._sync_region_slider()
self.update_all_views()
def apply_peel_prev(self):
self.peel_depth = max(0, self.peel_depth - 1)
self.region_step = 0
self.sl_peel.blockSignals(True)
self.sl_peel.setValue(self.peel_depth)
self.sl_peel.blockSignals(False)
if self.chk_auto_edit.isChecked(): self._sync_edit_with_peel()
self._sync_region_slider()
self.update_all_views()
def region_next(self):
maxv = self.sl_region.maximum()
self.region_step = min(maxv, self.region_step + 1)
self.sl_region.blockSignals(True)
self.sl_region.setValue(self.region_step)
self.sl_region.blockSignals(False)
self.clear_layer_cache()
self.update_all_views()
def region_prev(self):
self.region_step = max(0, self.region_step - 1)
self.sl_region.blockSignals(True)
self.sl_region.setValue(self.region_step)
self.sl_region.blockSignals(False)
self.clear_layer_cache()
self.update_all_views()
def edit_next(self):
self.edit_layer = min(self.num_layers - 1, self.edit_layer + 1)
self.sl_edit.blockSignals(True)
self.sl_edit.setValue(self.edit_layer)
self.sl_edit.blockSignals(False)
self.update_all_views()
def edit_prev(self):
self.edit_layer = max(0, self.edit_layer - 1)
self.sl_edit.blockSignals(True)
self.sl_edit.setValue(self.edit_layer)
self.sl_edit.blockSignals(False)
self.update_all_views()
def _get_peak_cmap_for_depth(self, peel_depth: int):
name, cmap = PEAK_CMAPS[int(peel_depth) % len(PEAK_CMAPS)]
return name, cmap
# ... [File list / Load Save ... same] ...
def update_file_list_ui(self):
self.file_list_widget.clear()
for f in self.file_list:
base = os.path.splitext(os.path.basename(f))[0]
is_lbl = os.path.exists(os.path.join(self.args.out_root, f"{base}_semantic.npy"))
item = QListWidgetItem(os.path.basename(f))
if is_lbl:
item.setForeground(QColor(0, 150, 0))
font = item.font()
font.setBold(True)
item.setFont(font)
item.setText(f"✔ {os.path.basename(f)}")
self.file_list_widget.addItem(item)
if 0 <= self.current_file_idx < len(self.file_list):
self.file_list_widget.setCurrentRow(self.current_file_idx)
def on_file_list_clicked(self, row):
if row < 0 or row >= len(self.file_list): return
if self.chk_autosave.isChecked() and self.is_dirty: self.save_current(silent=True)
self.current_file_idx = int(row)
self.load_file(self.file_list[self.current_file_idx])
def prev_file(self): self.on_file_list_clicked(max(0, self.current_file_idx - 1))
def next_file(self): self.on_file_list_clicked(min(len(self.file_list) - 1, self.current_file_idx + 1))
def load_file(self, path):
QApplication.setOverrideCursor(Qt.WaitCursor)
self.is_dirty = False
try:
self.undo_stack.clear()
self.current_file_path = path
self.setWindowTitle(f"SPAD Labeler - {os.path.basename(path)}")
self.raw_data = load_hist_npy(path)
if self.raw_data is None: return
self.noise_map = np.mean(self.raw_data, axis=1).reshape(self.H, self.W)
self.manual_masks = [np.zeros((self.H, self.W), dtype=np.uint8) for _ in range(self.num_layers)]
self.layer_thresholds = [None for _ in range(self.num_layers)]
self.layer_view_cache.clear()
base = os.path.splitext(os.path.basename(path))[0]
npy = os.path.join(self.args.out_root, f"{base}_semantic.npy")
if os.path.exists(npy):
try:
d = np.load(npy)
if d.ndim == 2 and d.shape[0] == self.H * self.W:
self.manual_masks = sem_bins_to_layers(d.astype(np.uint8), self.H, self.W, self.num_layers)
self.log_win.append("Loaded existing semantic.npy.")
except Exception: pass
self.peel_depth = 0
self.edit_layer = 0
self.region_step = 0
self.peel_by_class = bool(self.chk_peel_class.isChecked())
self.sl_peel.setValue(0)
self.sl_edit.setValue(0)
self._sync_region_slider()
self.update_all_views()
if self.hist_inspector and self.hist_inspector.isVisible():
self.hist_inspector.ax.clear()
self.hist_inspector.canvas.draw()
except Exception as e:
traceback.print_exc()
finally:
QApplication.restoreOverrideCursor()
def save_current(self, silent=False):
if not self.is_dirty and not silent: return
base = os.path.splitext(os.path.basename(self.current_file_path))[0]
out = os.path.join(self.args.out_root, f"{base}_semantic.npy")
ok, msg, _ = save_iterative_peeling_layers(out, self.raw_data, self.manual_masks, self.layer_thresholds, self.H, self.W, int(self.sl_thresh.value()))
if ok:
self.is_dirty = False
self.setWindowTitle(f"SPAD Labeler - {os.path.basename(self.current_file_path)}")
if not silent: self.log_win.append(msg)
self.update_file_list_ui()
def closeEvent(self, event):
if self.chk_autosave.isChecked() and self.is_dirty: self.save_current(silent=True)
if self.hist_inspector: self.hist_inspector.close()
event.accept()
# ... [Region calc/Peel calc/Display state... same] ...
def _get_current_peeled_layer(self):
if self.peel_depth <= 0: return None
return self.peel_depth - 1
def _compute_regions_for_layer(self, layer_idx: int, peel_by_class: bool):
mask2d = self.manual_masks[layer_idx]
regions = []
if peel_by_class:
flat = mask2d.reshape(-1)
for cid in sorted(self.class_names.keys()):
pix = np.flatnonzero(flat == cid)
if pix.size == 0: continue
regions.append({"cid": int(cid), "pixels": pix, "area": int(pix.size)})
regions.sort(key=lambda r: (r["cid"],))
return regions
for cid in sorted(self.class_names.keys()):
binary = (mask2d == cid).astype(np.uint8)
if binary.sum() == 0: continue
n, cc = cv2.connectedComponents(binary, connectivity=8)
for k in range(1, n):
pix = np.flatnonzero(cc.reshape(-1) == k)
if pix.size == 0: continue
regions.append({"cid": int(cid), "pixels": pix, "area": int(pix.size)})
regions.sort(key=lambda r: (r["cid"], -r["area"]))
return regions
def _get_regions_cached(self, layer_idx: int):
if layer_idx is None: return []
mode = bool(self.peel_by_class)
if (self._region_cache_layer == layer_idx and self._region_cache_revision == self.mask_revision and self._region_cache_mode == mode):
return self._region_cache_regions
regions = self._compute_regions_for_layer(layer_idx, peel_by_class=mode)
self._region_cache_layer = layer_idx
self._region_cache_revision = self.mask_revision
self._region_cache_mode = mode
self._region_cache_regions = regions
return regions
def _sync_region_slider(self):
L = self._get_current_peeled_layer()
if L is None:
self.sl_region.blockSignals(True)
self.sl_region.setRange(0, 0)
self.sl_region.setValue(0)
self.sl_region.blockSignals(False)
self.lbl_region.setText("Semantic Step: 0 / 0")
self.lbl_next_region.setText("Selected Peel Target: -")
return
regions = self._get_regions_cached(L)
n = len(regions)
self.region_step = max(0, min(self.region_step, n))
self.sl_region.blockSignals(True)
self.sl_region.setRange(0, n)
self.sl_region.setValue(self.region_step)
self.sl_region.blockSignals(False)
self.lbl_region.setText(f"Semantic Step (Layer {L}): {self.region_step} / {n}")
if n == 0: self.lbl_next_region.setText("Target: (no regions)")
elif self.region_step == 0: self.lbl_next_region.setText("Target: (none)")
else:
rid = min(max(0, self.region_step - 1), n - 1)
r = regions[rid]
cname = self.class_names.get(int(r["cid"]), f"Class {r['cid']}")
self.lbl_next_region.setText(f"Target: #{rid+1} | {cname} | area={r['area']}")
def _peel_pixels_peak_segment(self, working_data, pixel_indices, thr, peel_count=None):
if pixel_indices is None or pixel_indices.size == 0: return
for idx in pixel_indices:
hist = working_data[idx]
if np.max(hist) > thr:
p_idx = int(np.argmax(hist))
_, (l_rem, r_rem) = analyze_peak_structure(hist, p_idx, thr)
if r_rem > l_rem:
working_data[idx, l_rem:r_rem + 1] = 0
if peel_count is not None: peel_count[idx] += 1
def _build_working_hist_for_display(self, return_peel_count=False):
working = self.raw_data.copy()
curr_thr = int(self.sl_thresh.value())
peel_count = None
if return_peel_count: peel_count = np.zeros((self.H * self.W,), dtype=np.int16)
if self.peel_depth <= 0: return (working, peel_count) if return_peel_count else working
full_end = self.peel_depth - 1
for l in range(0, max(0, full_end)):
mask_flat = self.manual_masks[l].reshape(-1)
pix = np.flatnonzero(mask_flat > 0)
if pix.size == 0: continue
thr = self.layer_thresholds[l] if self.layer_thresholds[l] is not None else curr_thr
self._peel_pixels_peak_segment(working, pix, thr, peel_count=peel_count)
L = self.peel_depth - 1
thrL = self.layer_thresholds[L] if self.layer_thresholds[L] is not None else curr_thr
regions = self._get_regions_cached(L)
if len(regions) > 0 and self.region_step > 0:
rid = min(max(0, self.region_step - 1), len(regions) - 1)
self._peel_pixels_peak_segment(working, regions[rid]["pixels"], thrL, peel_count=peel_count)
return (working, peel_count) if return_peel_count else working
def get_display_state(self, return_peak_idx=False):
key_thr = int(self.sl_thresh.value())
lock_sig = tuple([(-1 if t is None else int(t)) for t in self.layer_thresholds[:max(0, self.peel_depth)]])
key = (int(self.peel_depth), int(self.region_step), int(self.peel_by_class), key_thr, lock_sig, int(self.mask_revision), int(return_peak_idx))
if key in self.layer_view_cache: return self.layer_view_cache[key]
working, peel_count = self._build_working_hist_for_display(return_peel_count=True)
raw2d = np.max(working, axis=1).reshape(self.H, self.W)
peel2d = peel_count.reshape(self.H, self.W)
if return_peak_idx:
peak_idx2d = np.argmax(working, axis=1).reshape(self.H, self.W)
self.layer_view_cache[key] = (raw2d, peel2d, peak_idx2d)
return raw2d, peel2d, peak_idx2d
self.layer_view_cache[key] = (raw2d, peel2d)
return raw2d, peel2d
def _get_valid_edit_mask(self, peel2d):
if not self.chk_lock_to_visible.isChecked(): return np.ones((self.H, self.W), dtype=bool)
return peel2d == int(self.edit_layer)
def _get_snr_mask(self, current_intensity):
if self.noise_map is None: return np.ones((self.H, self.W), dtype=bool)
snr_map = current_intensity / (self.noise_map + 1e-6)
return snr_map > (float(self.sl_snr.value()) / 10.0)
# ... [Combine layers/Split layers... same] ...
def _combine_layers(self, l_start, l_end_exclusive):
combined = np.zeros((self.H, self.W), dtype=np.uint8)
for l in range(max(0, int(l_start)), min(self.num_layers, int(l_end_exclusive))):
m = self.manual_masks[l]
combined[m > 0] = m[m > 0]
return combined
def _split_partial_layer_by_region_step(self, layer_idx):
peeled = np.zeros(self.H * self.W, dtype=np.uint8)
unpeeled = np.zeros(self.H * self.W, dtype=np.uint8)
if layer_idx is None: return peeled, unpeeled
regions = self._get_regions_cached(layer_idx)
if len(regions) == 0: return peeled, unpeeled
if self.region_step <= 0:
for r in regions: unpeeled[r["pixels"]] = np.uint8(r["cid"])
return peeled, unpeeled
sel = min(max(0, self.region_step - 1), len(regions) - 1)
for rid, r in enumerate(regions):
if rid == sel: peeled[r["pixels"]] = np.uint8(r["cid"])
else: unpeeled[r["pixels"]] = np.uint8(r["cid"])
return peeled, unpeeled
# ... [update_all_views ... same] ...
def update_all_views(self):
if self.raw_data is None: return
self._sync_region_slider()
L = self._get_current_peeled_layer()
raw, peel2d, peak_idx2d = self.get_display_state(return_peak_idx=True)
display_raw = raw.copy()
snr_mask = self._get_snr_mask(display_raw)
if self.chk_focus_edit.isChecked():
display_raw[~self._get_valid_edit_mask(peel2d)] = 0
display_raw[display_raw < int(self.sl_thresh.value())] = 0
display_raw[~snr_mask] = 0
norm = cv2.normalize(np.log1p(display_raw), None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
cmap_name, cmap = self._get_peak_cmap_for_depth(self.peel_depth)
self.lbl_info.set_image(safe_numpy_to_pixmap(cv2.applyColorMap(norm, cmap)))
depth_vis = peak_idx2d.astype(np.float32) * float(AppConfig.BIN_UNIT)
valid = display_raw > 0
depth_vis[~valid] = 0.0
if np.any(valid):
d = depth_vis[valid]
lo, hi = float(np.percentile(d, 2)), float(np.percentile(d, 98))
if hi <= lo: hi = lo + 1e-6
dn = np.clip((depth_vis - lo) / (hi - lo), 0.0, 1.0)
depth_col = cv2.applyColorMap((dn * 255.0).astype(np.uint8), _cv2_cmap("COLORMAP_TURBO", cv2.COLORMAP_JET))
depth_col[~valid] = 0
else: depth_col = np.zeros((self.H, self.W, 3), dtype=np.uint8)
self.lbl_depth.set_image(safe_numpy_to_pixmap(depth_col))
l0_raw = np.max(self.raw_data, axis=1).reshape(self.H, self.W)
n0 = cv2.normalize(np.log1p(l0_raw), None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
self.lbl_global.set_image(safe_numpy_to_pixmap(cv2.applyColorMap(n0, _cv2_cmap("COLORMAP_MAGMA", cv2.COLORMAP_JET))))
unpeeled_mask = self._combine_layers(self.peel_depth, self.num_layers)
ghost_mask = self._combine_layers(0, max(0, self.peel_depth - 1)) if self.chk_ghost.isChecked() else None
pL, uL = self._split_partial_layer_by_region_step(L)
if L is not None: unpeeled_mask[uL.reshape(self.H, self.W) > 0] = uL.reshape(self.H, self.W)[uL.reshape(self.H, self.W) > 0]
if self.chk_ghost.isChecked() and L is not None and ghost_mask is not None:
ghost_mask[pL.reshape(self.H, self.W) > 0] = pL.reshape(self.H, self.W)[pL.reshape(self.H, self.W) > 0]
mask_rgba = np.zeros((self.H, self.W, 4), dtype=np.uint8)
ghost_rgba = np.zeros((self.H, self.W, 4), dtype=np.uint8) if ghost_mask is not None else None
if not self.chk_hide.isChecked():
for cid, rgb in self.class_colors_rgb.items():
if cid <= 0: continue
mask_rgba[unpeeled_mask == cid] = [rgb[0], rgb[1], rgb[2], 180]
if ghost_rgba is not None: ghost_rgba[ghost_mask == cid] = [rgb[0], rgb[1], rgb[2], 180]
self.canvas.hide_labels = self.chk_hide.isChecked()
self.canvas.set_content(safe_numpy_to_pixmap(depth_col), safe_numpy_to_pixmap(mask_rgba), safe_numpy_to_pixmap(ghost_rgba))
res_rgb = np.zeros((self.H, self.W, 3), dtype=np.uint8)
for cid, rgb in self.class_colors_rgb.items():
if cid > 0: res_rgb[unpeeled_mask == cid] = rgb
self.lbl_result.set_image(safe_numpy_to_pixmap(res_rgb))
# ... [Assign/Erase... same] ...
def _assign_to_current_layer(self, region, cid, layer, overwrite=True):
if cid <= 0 or region is None or not np.any(region): return 0
m = self.manual_masks[int(layer)]
target = region if overwrite else (region & (m == 0))
if not np.count_nonzero(target): return 0
m[target] = np.uint8(cid)
self._ensure_layer_threshold(int(layer))
return np.count_nonzero(target)
def _erase_current_layer(self, region, layer):
if region is None or not np.any(region): return 0
m = self.manual_masks[int(layer)]
hit = region & (m > 0)
if not np.count_nonzero(hit): return 0
m[hit] = 0
return np.count_nonzero(hit)
def _erase_topmost_per_pixel(self, region): return self._erase_current_layer(region, self.edit_layer)
def _make_brush_region_circle(self, x, y, radius):
tmp = np.zeros((self.H, self.W), dtype=np.uint8)
cv2.circle(tmp, (x, y), int(radius), 1, -1)
return tmp > 0
def _make_brush_region_line(self, x1, y1, x2, y2, thickness):
tmp = np.zeros((self.H, self.W), dtype=np.uint8)
cv2.line(tmp, (x1, y1), (x2, y2), 1, int(thickness))
return tmp > 0
# ... [Magic Wand ... same] ...
def _compute_edge_barrier(self, raw_u8):
if not self.wand_edge_aware: return np.zeros_like(raw_u8, dtype=bool)
high = int(self.wand_edge_high)
return cv2.Canny(raw_u8, max(0, min(255, int(high * 0.5))), high).astype(bool)
def _magic_wand_grow(self, seed_x, seed_y, raw2d, valid_mask, thr):
if seed_x < 0 or seed_x >= self.W or seed_y < 0 or seed_y >= self.H: return np.zeros((self.H, self.W), dtype=bool)
if not valid_mask[seed_y, seed_x] or raw2d[seed_y, seed_x] <= thr: return np.zeros((self.H, self.W), dtype=bool)
raw_u8 = cv2.normalize(np.log1p(np.clip(raw2d, 0, None)), None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
seed_I, tol, barrier = int(raw_u8[seed_y, seed_x]), int(self.wand_tolerance), self._compute_edge_barrier(raw_u8)
neigh = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)] if self.wand_connectivity_8 else [(0, -1), (-1, 0), (1, 0), (0, 1)]
visited, region = np.zeros((self.H, self.W), dtype=bool), np.zeros((self.H, self.W), dtype=bool)
dq = deque([(seed_x, seed_y)])
visited[seed_y, seed_x] = True
while dq:
x, y = dq.popleft()
if barrier[y, x] or not valid_mask[y, x] or raw2d[y, x] <= thr or abs(int(raw_u8[y, x]) - seed_I) > tol: continue
region[y, x] = True
for dx, dy in neigh:
nx, ny = x + dx, y + dy
if 0 <= nx < self.W and 0 <= ny < self.H and not visited[ny, nx]:
visited[ny, nx] = True
if not barrier[ny, nx] and valid_mask[ny, nx] and raw2d[ny, nx] > thr: dq.append((nx, ny))
return region
# ==========================================
# Canvas actions (Modified for Inspect Mode)
# ==========================================
def handle_canvas_action(self, action, p1, p2):
if self.raw_data is None or p1 is None: return
if action == "draw_end": return
x1, y1 = self._clamp_xy(p1.x(), p1.y())
x2, y2 = (x1, y1) if p2 is None else self._clamp_xy(p2.x(), p2.y())
# [NEW LOGIC] If in Inspect Mode, only update histogram and exit.
if self.tool_mode == "inspect":
if action in ["pick_end", "pick_end_ctrl"]:
# Only react to single clicks to avoid confusion with dragging
if (p1 - p2).manhattanLength() <= 5:
self.update_histogram_inspector(x1, y1)
return # <--- STOP HERE, do NOT proceed to labeling logic
# --- Labeling Logic Below (Pick/Brush/Eraser) ---
raw, peel2d, peak_idx2d = self.get_display_state(return_peak_idx=True)
curr_thresh = int(self.sl_thresh.value())
is_erase_action = (self.tool_mode == "eraser") or (action == "pick_end_ctrl")
valid_mask = np.ones((self.H, self.W), dtype=bool) if is_erase_action else self._get_valid_edit_mask(peel2d)
valid_mask = valid_mask & self._get_snr_mask(raw)
if action in ["draw_start", "pick_end", "pick_end_ctrl"]: self.push_undo()
changed = 0
allow_overwrite = self.chk_overwrite.isChecked()
if action == "draw_start":
region = self._make_brush_region_circle(x1, y1, self.brush_size)
if not is_erase_action: region = region & valid_mask
changed = self._erase_topmost_per_pixel(region) if self.tool_mode == "eraser" else self._assign_to_current_layer(region, int(self.current_class), int(self.edit_layer), allow_overwrite)
elif action == "draw_drag":
region = self._make_brush_region_line(x1, y1, x2, y2, self.brush_size * 2)
if not is_erase_action: region = region & valid_mask
changed = self._erase_topmost_per_pixel(region) if self.tool_mode == "eraser" else self._assign_to_current_layer(region, int(self.current_class), int(self.edit_layer), allow_overwrite)
elif action in ["pick_end", "pick_end_ctrl"]:
if (p1 - p2).manhattanLength() > 5:
xs, xe, ys, ye = sorted([x1, x2])[0], sorted([x1, x2])[1], sorted([y1, y2])[0], sorted([y1, y2])[1]
xe, ye = min(xe + 1, self.W), min(ye + 1, self.H)
region = np.zeros((self.H, self.W), dtype=bool)
roi = raw[ys:ye, xs:xe]
region[ys:ye, xs:xe] = (roi > curr_thresh) & valid_mask[ys:ye, xs:xe]
else:
region = self._magic_wand_grow(x1, y1, raw, valid_mask, curr_thresh)
if not np.any(region):
if not is_erase_action and self.chk_lock_to_visible.isChecked():
self.log_win.append("Pick ignored: invalid area.")
else:
ctrl_erase = (action == "pick_end_ctrl")
changed = self._erase_topmost_per_pixel(region) if (ctrl_erase or self.tool_mode == "eraser") else self._assign_to_current_layer(region, int(self.current_class), int(self.edit_layer), allow_overwrite)
if changed > 0:
self.set_dirty()
self.update_all_views()
# ... [Undo/Morph/Key events ... same] ...
def undo(self):
if not self.undo_stack: return
stack, thr, pd, rs, el, peel_mode = self.undo_stack.pop()
self.manual_masks = [stack[l].copy() for l in range(self.num_layers)]
self.layer_thresholds = list(thr)
self.peel_depth, self.region_step, self.edit_layer, self.peel_by_class = int(pd), int(rs), int(el), bool(peel_mode)
self.chk_peel_class.blockSignals(True)
self.chk_peel_class.setChecked(self.peel_by_class)
self.chk_peel_class.blockSignals(False)
self.sl_peel.blockSignals(True)
self.sl_peel.setValue(self.peel_depth)
self.sl_peel.blockSignals(False)
self.sl_edit.blockSignals(True)
self.sl_edit.setValue(self.edit_layer)
self.sl_edit.blockSignals(False)
self.clear_layer_cache()
self.is_dirty = True
self.mask_revision += 1
self._sync_region_slider()
self.update_all_views()
self.log_win.append("Undo.")
if self.hist_inspector and self.hist_inspector.isVisible():
self.hist_inspector.ax.clear()
self.hist_inspector.canvas.draw()
def keyPressEvent(self, event):
if event.key() == Qt.Key_Up: self.sl_thresh.setValue(self.sl_thresh.value() + (10 if event.modifiers() & Qt.ShiftModifier else 1))
elif event.key() == Qt.Key_Down: self.sl_thresh.setValue(max(0, self.sl_thresh.value() - (10 if event.modifiers() & Qt.ShiftModifier else 1)))
elif event.key() == Qt.Key_Control:
self.canvas.ctrl_pressed = True
self.canvas.update()
else: super().keyPressEvent(event)
def keyReleaseEvent(self, event):
if event.key() == Qt.Key_Control:
self.canvas.ctrl_pressed = False
self.canvas.update()
super().keyReleaseEvent(event)
def set_class_by_key(self, idx):
if int(idx) in self.cls_radios:
self.cls_radios[int(idx)].setChecked(True)
self.current_class = int(idx)
def cycle_class_prev(self): self.set_class_by_key(self.current_class - 1 if self.current_class > 1 else len(self.class_names))
def cycle_class_next(self): self.set_class_by_key(self.current_class + 1 if self.current_class < len(self.class_names) else 1)
def morph_current_mask(self, op):
mask = self.manual_masks[0]
if not np.any(mask): return
self.push_undo()
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
for cid in self.class_names:
c_mask = (mask == cid).astype(np.uint8)
if not np.any(c_mask): continue
proc = cv2.dilate(c_mask, kernel) if op == "dilate" else cv2.erode(c_mask, kernel)
mask[proc > 0] = cid
self.set_dirty()
self.update_all_views()
def fill_unknown_current_layer(self):
if self.raw_data is None: return
layer = int(self.edit_layer)
raw2d, peel2d = self.get_display_state()
valid = self._get_valid_edit_mask(peel2d) & self._get_snr_mask(raw2d)
region = (raw2d > int(self.sl_thresh.value())) & valid
m = self.manual_masks[layer]
fill = region & (m == 0)
if not np.count_nonzero(fill): return
self.push_undo()
m[fill] = np.uint8(self.UNKNOWN_CID)
self._ensure_layer_threshold(layer)
self.set_dirty()
self.update_all_views()
# ==========================================
# 3D
# ==========================================
def visualize_3d_point_cloud(self):
if not HAS_OPEN3D or self.raw_data is None: return
QApplication.setOverrideCursor(Qt.WaitCursor)
try:
raw, _ = self.get_display_state()
snr_mask = self._get_snr_mask(raw)
valid = (raw > int(self.sl_thresh.value())) & snr_mask
rows, cols = np.where(valid)
working_data = self._build_working_hist_for_display(return_peel_count=False)
zs = [int(np.argmax(working_data[r * self.W + c])) for r, c in zip(rows, cols)]
Z = np.array(zs, dtype=np.float32) * AppConfig.BIN_UNIT
u, v = cols.astype(float), rows.astype(float)
pts_uv = np.stack([u, v], axis=1).reshape(-1, 1, 2)
pts_undist = cv2.undistortPoints(pts_uv, AppConfig.CAM_K, AppConfig.CAM_D).reshape(-1, 2)
xyz = np.stack([pts_undist[:, 0] * Z, pts_undist[:, 1] * Z, Z], axis=1)
pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(xyz)
pcd.colors = o3d.utility.Vector3dVector(get_robust_colors(raw[rows, cols]))
o3d.visualization.draw_geometries([pcd], window_name=f"3D Depth (PeelDepth {self.peel_depth})")
finally: QApplication.restoreOverrideCursor()
def visualize_3d_semantic_point_cloud(self):
if not HAS_OPEN3D or self.raw_data is None: return
QApplication.setOverrideCursor(Qt.WaitCursor)
try:
curr_thr = int(self.sl_thresh.value())
working = self.raw_data.copy()
all_rows, all_cols, all_Z, all_cids = [], [], [], []
for l in range(self.num_layers):
m = self.manual_masks[l]
flat = m.reshape(-1)
labeled_idx = np.flatnonzero(flat > 0)
if labeled_idx.size == 0: continue
thr_l = self.layer_thresholds[l] if self.layer_thresholds[l] is not None else curr_thr
for idx in labeled_idx:
cid = int(flat[idx])
hist = working[idx]
if np.max(hist) <= thr_l: continue
peak_idx = int(np.argmax(hist))
(__, ___), (l_rem, r_rem) = analyze_peak_structure(hist, peak_idx, thr_l)
if r_rem <= l_rem: continue
all_rows.append(int(idx // self.W))
all_cols.append(int(idx % self.W))
all_Z.append(float(peak_idx) * AppConfig.BIN_UNIT)
all_cids.append(cid)
working[idx, l_rem:r_rem + 1] = 0
if len(all_rows) == 0: return
rows, cols, Z, cids = np.asarray(all_rows), np.asarray(all_cols), np.asarray(all_Z), np.asarray(all_cids)
u, v = cols.astype(np.float32), rows.astype(np.float32)
pts_uv = np.stack([u, v], axis=1).reshape(-1, 1, 2)
pts_undist = cv2.undistortPoints(pts_uv, AppConfig.CAM_K, AppConfig.CAM_D).reshape(-1, 2)
xyz = np.stack([pts_undist[:, 0] * Z, pts_undist[:, 1] * Z, Z], axis=1)
colors = np.zeros((cids.size, 3), dtype=np.float32)
for i, cid in enumerate(cids):
rgb = self.class_colors_rgb.get(int(cid), (255, 255, 255))
colors[i] = [rgb[0]/255.0, rgb[1]/255.0, rgb[2]/255.0]
pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(xyz)
pcd.colors = o3d.utility.Vector3dVector(colors)
o3d.visualization.draw_geometries([pcd], window_name="3D Semantic (Multi-layer)")
finally: QApplication.restoreOverrideCursor()
# [RESTORED METHOD]
def visualize_3d_semantic_bins_point_cloud(self):
if not HAS_OPEN3D or self.raw_data is None: return
QApplication.setOverrideCursor(Qt.WaitCursor)
try:
thr_global = int(self.sl_thresh.value())
H, W = self.H, self.W
BIN_STRIDE = 1
PIX_STRIDE = 1
MAX_POINTS = 2_000_000
working = self.raw_data.copy()
all_xyz, all_rgb = [], []
total_pts = 0
for layer in range(self.num_layers):
m = self.manual_masks[layer]
flat = m.reshape(-1)
pix = np.flatnonzero(flat > 0)
if pix.size == 0: continue
if PIX_STRIDE > 1: pix = pix[::PIX_STRIDE]
thr = self.layer_thresholds[layer] if self.layer_thresholds[layer] is not None else thr_global
thr = int(thr)
rows, cols = (pix // W).astype(np.int32), (pix % W).astype(np.int32)
pts_uv = np.stack([cols.astype(np.float32), rows.astype(np.float32)], axis=1).reshape(-1, 1, 2)
pts_undist = cv2.undistortPoints(pts_uv, AppConfig.CAM_K, AppConfig.CAM_D).reshape(-1, 2)
xnd, ynd = pts_undist[:, 0], pts_undist[:, 1]
cids = flat[pix].astype(np.int32)
for i, idx in enumerate(pix):
hist = working[idx]
if hist.max() <= thr: continue
p_idx = int(np.argmax(hist))
(l_lab, r_lab), (l_rem, r_rem) = analyze_peak_structure(hist, p_idx, thr)
if r_lab >= l_lab:
bins = np.arange(l_lab, r_lab + 1, BIN_STRIDE, dtype=np.int32)
if bins.size > 0:
Z = bins.astype(np.float32) * float(AppConfig.BIN_UNIT)
xyz = np.stack([xnd[i] * Z, ynd[i] * Z, Z], axis=1)
cid = int(cids[i])
rgb = self.class_colors_rgb.get(cid, (64, 64, 64))
rgb_f = (np.array(rgb, dtype=np.float32) / 255.0).reshape(1, 3)
rgb_arr = np.repeat(rgb_f, xyz.shape[0], axis=0)
all_xyz.append(xyz)
all_rgb.append(rgb_arr)
total_pts += xyz.shape[0]
if total_pts >= MAX_POINTS: break
if r_rem > l_rem: working[idx, l_rem:r_rem + 1] = 0
if total_pts >= MAX_POINTS: break
if total_pts == 0:
self.log_win.append("3D Labeled Bins: no labeled bin segments to draw.")
return
xyz = np.concatenate(all_xyz, axis=0)
rgb = np.concatenate(all_rgb, axis=0)
pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(xyz)
pcd.colors = o3d.utility.Vector3dVector(rgb)
o3d.visualization.draw_geometries([pcd], window_name="3D Labeled Bins (per-pixel labeled segments)")
finally: QApplication.restoreOverrideCursor()
if __name__ == "__main__":
import multiprocessing as mp
mp.freeze_support()
ap = argparse.ArgumentParser()
ap.add_argument("--in_dir", default="npy")
ap.add_argument("--out_root", default="output")
ap.add_argument("--pattern", default="*.npy")
ap.add_argument("--cache_dir", default="cache")
args = ap.parse_args()
app = QApplication(sys.argv)
win = SPADLabelerPixel(args)
win.show()
sys.exit(app.exec_())