setiastrosuitepro 1.6.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of setiastrosuitepro might be problematic. Click here for more details.
- setiastro/__init__.py +2 -0
- setiastro/saspro/__init__.py +20 -0
- setiastro/saspro/__main__.py +784 -0
- setiastro/saspro/_generated/__init__.py +7 -0
- setiastro/saspro/_generated/build_info.py +2 -0
- setiastro/saspro/abe.py +1295 -0
- setiastro/saspro/abe_preset.py +196 -0
- setiastro/saspro/aberration_ai.py +694 -0
- setiastro/saspro/aberration_ai_preset.py +224 -0
- setiastro/saspro/accel_installer.py +218 -0
- setiastro/saspro/accel_workers.py +30 -0
- setiastro/saspro/add_stars.py +621 -0
- setiastro/saspro/astrobin_exporter.py +1007 -0
- setiastro/saspro/astrospike.py +153 -0
- setiastro/saspro/astrospike_python.py +1839 -0
- setiastro/saspro/autostretch.py +196 -0
- setiastro/saspro/backgroundneutral.py +560 -0
- setiastro/saspro/batch_convert.py +325 -0
- setiastro/saspro/batch_renamer.py +519 -0
- setiastro/saspro/blemish_blaster.py +488 -0
- setiastro/saspro/blink_comparator_pro.py +2923 -0
- setiastro/saspro/bundles.py +61 -0
- setiastro/saspro/bundles_dock.py +114 -0
- setiastro/saspro/cheat_sheet.py +168 -0
- setiastro/saspro/clahe.py +342 -0
- setiastro/saspro/comet_stacking.py +1377 -0
- setiastro/saspro/config.py +38 -0
- setiastro/saspro/config_bootstrap.py +40 -0
- setiastro/saspro/config_manager.py +316 -0
- setiastro/saspro/continuum_subtract.py +1617 -0
- setiastro/saspro/convo.py +1397 -0
- setiastro/saspro/convo_preset.py +414 -0
- setiastro/saspro/copyastro.py +187 -0
- setiastro/saspro/cosmicclarity.py +1564 -0
- setiastro/saspro/cosmicclarity_preset.py +407 -0
- setiastro/saspro/crop_dialog_pro.py +948 -0
- setiastro/saspro/crop_preset.py +189 -0
- setiastro/saspro/curve_editor_pro.py +2544 -0
- setiastro/saspro/curves_preset.py +375 -0
- setiastro/saspro/debayer.py +670 -0
- setiastro/saspro/debug_utils.py +29 -0
- setiastro/saspro/dnd_mime.py +35 -0
- setiastro/saspro/doc_manager.py +2634 -0
- setiastro/saspro/exoplanet_detector.py +2166 -0
- setiastro/saspro/file_utils.py +284 -0
- setiastro/saspro/fitsmodifier.py +744 -0
- setiastro/saspro/free_torch_memory.py +48 -0
- setiastro/saspro/frequency_separation.py +1343 -0
- setiastro/saspro/function_bundle.py +1594 -0
- setiastro/saspro/ghs_dialog_pro.py +660 -0
- setiastro/saspro/ghs_preset.py +284 -0
- setiastro/saspro/graxpert.py +634 -0
- setiastro/saspro/graxpert_preset.py +287 -0
- setiastro/saspro/gui/__init__.py +0 -0
- setiastro/saspro/gui/main_window.py +8494 -0
- setiastro/saspro/gui/mixins/__init__.py +33 -0
- setiastro/saspro/gui/mixins/dock_mixin.py +263 -0
- setiastro/saspro/gui/mixins/file_mixin.py +445 -0
- setiastro/saspro/gui/mixins/geometry_mixin.py +403 -0
- setiastro/saspro/gui/mixins/header_mixin.py +441 -0
- setiastro/saspro/gui/mixins/mask_mixin.py +421 -0
- setiastro/saspro/gui/mixins/menu_mixin.py +361 -0
- setiastro/saspro/gui/mixins/theme_mixin.py +367 -0
- setiastro/saspro/gui/mixins/toolbar_mixin.py +1324 -0
- setiastro/saspro/gui/mixins/update_mixin.py +309 -0
- setiastro/saspro/gui/mixins/view_mixin.py +435 -0
- setiastro/saspro/halobgon.py +462 -0
- setiastro/saspro/header_viewer.py +445 -0
- setiastro/saspro/headless_utils.py +88 -0
- setiastro/saspro/histogram.py +753 -0
- setiastro/saspro/history_explorer.py +939 -0
- setiastro/saspro/image_combine.py +414 -0
- setiastro/saspro/image_peeker_pro.py +1596 -0
- setiastro/saspro/imageops/__init__.py +37 -0
- setiastro/saspro/imageops/mdi_snap.py +292 -0
- setiastro/saspro/imageops/scnr.py +36 -0
- setiastro/saspro/imageops/starbasedwhitebalance.py +210 -0
- setiastro/saspro/imageops/stretch.py +244 -0
- setiastro/saspro/isophote.py +1179 -0
- setiastro/saspro/layers.py +208 -0
- setiastro/saspro/layers_dock.py +714 -0
- setiastro/saspro/lazy_imports.py +193 -0
- setiastro/saspro/legacy/__init__.py +2 -0
- setiastro/saspro/legacy/image_manager.py +2226 -0
- setiastro/saspro/legacy/numba_utils.py +3659 -0
- setiastro/saspro/legacy/xisf.py +1071 -0
- setiastro/saspro/linear_fit.py +534 -0
- setiastro/saspro/live_stacking.py +1830 -0
- setiastro/saspro/log_bus.py +5 -0
- setiastro/saspro/logging_config.py +460 -0
- setiastro/saspro/luminancerecombine.py +309 -0
- setiastro/saspro/main_helpers.py +201 -0
- setiastro/saspro/mask_creation.py +928 -0
- setiastro/saspro/masks_core.py +56 -0
- setiastro/saspro/mdi_widgets.py +353 -0
- setiastro/saspro/memory_utils.py +666 -0
- setiastro/saspro/metadata_patcher.py +75 -0
- setiastro/saspro/mfdeconv.py +3826 -0
- setiastro/saspro/mfdeconv_earlystop.py +71 -0
- setiastro/saspro/mfdeconvcudnn.py +3263 -0
- setiastro/saspro/mfdeconvsport.py +2382 -0
- setiastro/saspro/minorbodycatalog.py +567 -0
- setiastro/saspro/morphology.py +382 -0
- setiastro/saspro/multiscale_decomp.py +1290 -0
- setiastro/saspro/nbtorgb_stars.py +531 -0
- setiastro/saspro/numba_utils.py +3044 -0
- setiastro/saspro/numba_warmup.py +141 -0
- setiastro/saspro/ops/__init__.py +9 -0
- setiastro/saspro/ops/command_help_dialog.py +623 -0
- setiastro/saspro/ops/command_runner.py +217 -0
- setiastro/saspro/ops/commands.py +1594 -0
- setiastro/saspro/ops/script_editor.py +1102 -0
- setiastro/saspro/ops/scripts.py +1413 -0
- setiastro/saspro/ops/settings.py +560 -0
- setiastro/saspro/parallel_utils.py +554 -0
- setiastro/saspro/pedestal.py +121 -0
- setiastro/saspro/perfect_palette_picker.py +1053 -0
- setiastro/saspro/pipeline.py +110 -0
- setiastro/saspro/pixelmath.py +1600 -0
- setiastro/saspro/plate_solver.py +2435 -0
- setiastro/saspro/project_io.py +797 -0
- setiastro/saspro/psf_utils.py +136 -0
- setiastro/saspro/psf_viewer.py +549 -0
- setiastro/saspro/pyi_rthook_astroquery.py +95 -0
- setiastro/saspro/remove_green.py +314 -0
- setiastro/saspro/remove_stars.py +1625 -0
- setiastro/saspro/remove_stars_preset.py +404 -0
- setiastro/saspro/resources.py +472 -0
- setiastro/saspro/rgb_combination.py +207 -0
- setiastro/saspro/rgb_extract.py +19 -0
- setiastro/saspro/rgbalign.py +723 -0
- setiastro/saspro/runtime_imports.py +7 -0
- setiastro/saspro/runtime_torch.py +754 -0
- setiastro/saspro/save_options.py +72 -0
- setiastro/saspro/selective_color.py +1552 -0
- setiastro/saspro/sfcc.py +1425 -0
- setiastro/saspro/shortcuts.py +2807 -0
- setiastro/saspro/signature_insert.py +1099 -0
- setiastro/saspro/stacking_suite.py +17712 -0
- setiastro/saspro/star_alignment.py +7420 -0
- setiastro/saspro/star_alignment_preset.py +329 -0
- setiastro/saspro/star_metrics.py +49 -0
- setiastro/saspro/star_spikes.py +681 -0
- setiastro/saspro/star_stretch.py +470 -0
- setiastro/saspro/stat_stretch.py +502 -0
- setiastro/saspro/status_log_dock.py +78 -0
- setiastro/saspro/subwindow.py +3267 -0
- setiastro/saspro/supernovaasteroidhunter.py +1712 -0
- setiastro/saspro/swap_manager.py +99 -0
- setiastro/saspro/torch_backend.py +89 -0
- setiastro/saspro/torch_rejection.py +434 -0
- setiastro/saspro/view_bundle.py +1555 -0
- setiastro/saspro/wavescale_hdr.py +624 -0
- setiastro/saspro/wavescale_hdr_preset.py +100 -0
- setiastro/saspro/wavescalede.py +657 -0
- setiastro/saspro/wavescalede_preset.py +228 -0
- setiastro/saspro/wcs_update.py +374 -0
- setiastro/saspro/whitebalance.py +456 -0
- setiastro/saspro/widgets/__init__.py +48 -0
- setiastro/saspro/widgets/common_utilities.py +305 -0
- setiastro/saspro/widgets/graphics_views.py +122 -0
- setiastro/saspro/widgets/image_utils.py +518 -0
- setiastro/saspro/widgets/preview_dialogs.py +280 -0
- setiastro/saspro/widgets/spinboxes.py +275 -0
- setiastro/saspro/widgets/themed_buttons.py +13 -0
- setiastro/saspro/widgets/wavelet_utils.py +299 -0
- setiastro/saspro/window_shelf.py +185 -0
- setiastro/saspro/xisf.py +1123 -0
- setiastrosuitepro-1.6.0.dist-info/METADATA +266 -0
- setiastrosuitepro-1.6.0.dist-info/RECORD +174 -0
- setiastrosuitepro-1.6.0.dist-info/WHEEL +4 -0
- setiastrosuitepro-1.6.0.dist-info/entry_points.txt +6 -0
- setiastrosuitepro-1.6.0.dist-info/licenses/LICENSE +674 -0
- setiastrosuitepro-1.6.0.dist-info/licenses/license.txt +2580 -0
|
@@ -0,0 +1,1290 @@
|
|
|
1
|
+
# pro/multiscale_decomp.py
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
import numpy as np
|
|
4
|
+
import cv2
|
|
5
|
+
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from PyQt6.QtCore import Qt, QTimer
|
|
8
|
+
from PyQt6.QtGui import QImage, QPixmap, QPen, QColor, QIcon
|
|
9
|
+
from PyQt6.QtWidgets import (
|
|
10
|
+
QDialog, QVBoxLayout, QHBoxLayout, QGroupBox, QFormLayout,
|
|
11
|
+
QPushButton, QComboBox, QSpinBox, QDoubleSpinBox, QCheckBox,
|
|
12
|
+
QTableWidget, QTableWidgetItem, QWidget, QLabel, QGraphicsView,
|
|
13
|
+
QGraphicsScene, QGraphicsPixmapItem, QMessageBox, QToolButton, QSlider, QSplitter,
|
|
14
|
+
QProgressDialog, QApplication
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class _ZoomPanView(QGraphicsView):
|
|
20
|
+
def __init__(self, *args, **kwargs):
|
|
21
|
+
super().__init__(*args, **kwargs)
|
|
22
|
+
self.setDragMode(QGraphicsView.DragMode.NoDrag)
|
|
23
|
+
self.setTransformationAnchor(QGraphicsView.ViewportAnchor.AnchorUnderMouse)
|
|
24
|
+
self.setResizeAnchor(QGraphicsView.ViewportAnchor.AnchorUnderMouse)
|
|
25
|
+
|
|
26
|
+
self._panning = False
|
|
27
|
+
self._pan_start = None
|
|
28
|
+
|
|
29
|
+
def wheelEvent(self, ev):
|
|
30
|
+
# Ctrl+wheel optional – but I’ll make plain wheel zoom since you asked
|
|
31
|
+
delta = ev.angleDelta().y()
|
|
32
|
+
if delta == 0:
|
|
33
|
+
return
|
|
34
|
+
factor = 1.25 if delta > 0 else 0.8
|
|
35
|
+
self.scale(factor, factor)
|
|
36
|
+
ev.accept()
|
|
37
|
+
|
|
38
|
+
def mousePressEvent(self, ev):
|
|
39
|
+
if ev.button() == Qt.MouseButton.LeftButton:
|
|
40
|
+
self._panning = True
|
|
41
|
+
self._pan_start = ev.pos()
|
|
42
|
+
self.setCursor(Qt.CursorShape.ClosedHandCursor)
|
|
43
|
+
ev.accept()
|
|
44
|
+
return
|
|
45
|
+
super().mousePressEvent(ev)
|
|
46
|
+
|
|
47
|
+
def mouseMoveEvent(self, ev):
|
|
48
|
+
if self._panning and self._pan_start is not None:
|
|
49
|
+
delta = ev.pos() - self._pan_start
|
|
50
|
+
self._pan_start = ev.pos()
|
|
51
|
+
|
|
52
|
+
h = self.horizontalScrollBar()
|
|
53
|
+
v = self.verticalScrollBar()
|
|
54
|
+
h.setValue(h.value() - delta.x())
|
|
55
|
+
v.setValue(v.value() - delta.y())
|
|
56
|
+
ev.accept()
|
|
57
|
+
return
|
|
58
|
+
super().mouseMoveEvent(ev)
|
|
59
|
+
|
|
60
|
+
def mouseReleaseEvent(self, ev):
|
|
61
|
+
if ev.button() == Qt.MouseButton.LeftButton and self._panning:
|
|
62
|
+
self._panning = False
|
|
63
|
+
self._pan_start = None
|
|
64
|
+
self.setCursor(Qt.CursorShape.ArrowCursor)
|
|
65
|
+
ev.accept()
|
|
66
|
+
return
|
|
67
|
+
super().mouseReleaseEvent(ev)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
# ─────────────────────────────────────────────
|
|
71
|
+
# Core math (your backbone)
|
|
72
|
+
# ─────────────────────────────────────────────
|
|
73
|
+
|
|
74
|
+
def _blur_gaussian(img01: np.ndarray, sigma: float) -> np.ndarray:
|
|
75
|
+
k = int(max(3, 2 * round(3 * sigma) + 1)) # odd
|
|
76
|
+
return cv2.GaussianBlur(img01, (k, k), sigmaX=sigma, sigmaY=sigma, borderType=cv2.BORDER_REFLECT)
|
|
77
|
+
|
|
78
|
+
def multiscale_decompose(img01: np.ndarray, layers: int, base_sigma: float = 1.0):
|
|
79
|
+
c = img01.astype(np.float32, copy=False)
|
|
80
|
+
details = []
|
|
81
|
+
for k in range(layers):
|
|
82
|
+
sigma = base_sigma * (2 ** k)
|
|
83
|
+
c_next = _blur_gaussian(c, sigma)
|
|
84
|
+
w = c - c_next
|
|
85
|
+
details.append(w)
|
|
86
|
+
c = c_next
|
|
87
|
+
residual = c
|
|
88
|
+
return details, residual
|
|
89
|
+
|
|
90
|
+
def multiscale_reconstruct(details, residual):
|
|
91
|
+
out = residual.astype(np.float32, copy=True)
|
|
92
|
+
for w in details:
|
|
93
|
+
out += w
|
|
94
|
+
return out
|
|
95
|
+
|
|
96
|
+
def soft_threshold(x: np.ndarray, t: float):
|
|
97
|
+
a = np.abs(x)
|
|
98
|
+
return np.sign(x) * np.maximum(0.0, a - t)
|
|
99
|
+
|
|
100
|
+
def apply_layer_ops(
|
|
101
|
+
w: np.ndarray,
|
|
102
|
+
bias_gain: float,
|
|
103
|
+
thr_sigma: float, # threshold in units of σ
|
|
104
|
+
amount: float,
|
|
105
|
+
denoise_strength: float = 0.0,
|
|
106
|
+
sigma: float | np.ndarray | None = None,
|
|
107
|
+
*,
|
|
108
|
+
mode: str = "μ–σ Thresholding",
|
|
109
|
+
):
|
|
110
|
+
w2 = w
|
|
111
|
+
|
|
112
|
+
# Normalize mode to something robust to label wording
|
|
113
|
+
m = (mode or "").strip().lower()
|
|
114
|
+
is_linear = m.startswith("linear")
|
|
115
|
+
|
|
116
|
+
# --- Linear mode: strictly linear multiscale transform ---
|
|
117
|
+
if is_linear:
|
|
118
|
+
# Ignore thresholding and denoise; just apply gain
|
|
119
|
+
if abs(bias_gain - 1.0) > 1e-6:
|
|
120
|
+
return w * bias_gain
|
|
121
|
+
return w
|
|
122
|
+
|
|
123
|
+
# --- μ–σ Thresholding mode (robust nonlinear) ---
|
|
124
|
+
# 1) Noise reduction step (MMT-style NR)
|
|
125
|
+
if denoise_strength > 0.0:
|
|
126
|
+
if sigma is None:
|
|
127
|
+
sigma = _robust_sigma(w2)
|
|
128
|
+
sigma_f = float(sigma)
|
|
129
|
+
# 3σ at denoise=1, scaled linearly
|
|
130
|
+
t_dn = max(0.0, denoise_strength * 3.0 * sigma_f)
|
|
131
|
+
if t_dn > 0.0:
|
|
132
|
+
w_dn = soft_threshold(w2, t_dn)
|
|
133
|
+
# Blend original vs denoised based on denoise_strength
|
|
134
|
+
w2 = (1.0 - denoise_strength) * w2 + denoise_strength * w_dn
|
|
135
|
+
|
|
136
|
+
# 2) Threshold in σ units + bias shaping
|
|
137
|
+
if thr_sigma > 0.0:
|
|
138
|
+
if sigma is None:
|
|
139
|
+
sigma = _robust_sigma(w2)
|
|
140
|
+
sigma_f = float(sigma)
|
|
141
|
+
t = thr_sigma * sigma_f # convert N·σ → absolute threshold
|
|
142
|
+
if t > 0.0:
|
|
143
|
+
wt = soft_threshold(w2, t)
|
|
144
|
+
w2 = (1.0 - amount) * w2 + amount * wt
|
|
145
|
+
|
|
146
|
+
if abs(bias_gain - 1.0) > 1e-6:
|
|
147
|
+
w2 = w2 * bias_gain
|
|
148
|
+
return w2
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _robust_sigma(arr: np.ndarray) -> float:
|
|
152
|
+
"""
|
|
153
|
+
Robust per-layer sigma estimate using MAD, fallback to std if needed.
|
|
154
|
+
Ignores NaN/Inf and uses a subset if very large.
|
|
155
|
+
"""
|
|
156
|
+
a = np.asarray(arr, dtype=np.float32)
|
|
157
|
+
a = a[np.isfinite(a)]
|
|
158
|
+
if a.size == 0:
|
|
159
|
+
return 1e-6
|
|
160
|
+
|
|
161
|
+
# Optional: subsample for speed on huge arrays
|
|
162
|
+
if a.size > 500_000:
|
|
163
|
+
idx = np.random.choice(a.size, 500_000, replace=False)
|
|
164
|
+
a = a[idx]
|
|
165
|
+
|
|
166
|
+
med = np.median(a)
|
|
167
|
+
mad = np.median(np.abs(a - med))
|
|
168
|
+
if mad <= 0:
|
|
169
|
+
# fallback to plain std if MAD degenerates
|
|
170
|
+
s = float(np.std(a))
|
|
171
|
+
return s if s > 0 else 1e-6
|
|
172
|
+
|
|
173
|
+
sigma = 1.4826 * mad # MAD → σ for Gaussian
|
|
174
|
+
return sigma if sigma > 0 else 1e-6
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
# ─────────────────────────────────────────────
|
|
178
|
+
# Layer config
|
|
179
|
+
# ─────────────────────────────────────────────
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
@dataclass
|
|
183
|
+
class LayerCfg:
|
|
184
|
+
enabled: bool = True
|
|
185
|
+
bias_gain: float = 1.0 # 1.0 = unchanged
|
|
186
|
+
thr: float = 0.0 # soft threshold in detail domain
|
|
187
|
+
amount: float = 0.0 # 0..1 blend toward thresholded
|
|
188
|
+
denoise: float = 0.0 # 0..1 additional noise reduction
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
# ─────────────────────────────────────────────
|
|
192
|
+
# Dialog
|
|
193
|
+
# ─────────────────────────────────────────────
|
|
194
|
+
|
|
195
|
+
class MultiscaleDecompDialog(QDialog):
|
|
196
|
+
def __init__(self, parent, doc):
|
|
197
|
+
super().__init__(parent)
|
|
198
|
+
self.setWindowTitle("Multiscale Decomposition")
|
|
199
|
+
self.setMinimumSize(1050, 700)
|
|
200
|
+
self.residual_enabled = True
|
|
201
|
+
self._layer_noise = None # list[float] per detail layer
|
|
202
|
+
|
|
203
|
+
self._doc = doc
|
|
204
|
+
base = getattr(doc, "image", None)
|
|
205
|
+
if base is None:
|
|
206
|
+
raise RuntimeError("Document has no image.")
|
|
207
|
+
|
|
208
|
+
# normalize to float32 [0..1] ...
|
|
209
|
+
img = np.asarray(base)
|
|
210
|
+
img = img.astype(np.float32, copy=False)
|
|
211
|
+
if img.dtype.kind in "ui":
|
|
212
|
+
maxv = float(np.nanmax(img)) or 1.0
|
|
213
|
+
img = img / max(1.0, maxv)
|
|
214
|
+
img = np.clip(img, 0.0, 1.0).astype(np.float32, copy=False)
|
|
215
|
+
|
|
216
|
+
self._orig_shape = img.shape
|
|
217
|
+
self._orig_mono = (img.ndim == 2) or (img.ndim == 3 and img.shape[2] == 1)
|
|
218
|
+
|
|
219
|
+
# force display buffer to 3ch ...
|
|
220
|
+
if img.ndim == 2:
|
|
221
|
+
img3 = np.repeat(img[:, :, None], 3, axis=2)
|
|
222
|
+
elif img.ndim == 3 and img.shape[2] == 1:
|
|
223
|
+
img3 = np.repeat(img, 3, axis=2)
|
|
224
|
+
else:
|
|
225
|
+
img3 = img[:, :, :3]
|
|
226
|
+
|
|
227
|
+
self._image = img3.copy() # working linear image (edited on Apply only)
|
|
228
|
+
self._preview_img = img3.copy()
|
|
229
|
+
|
|
230
|
+
# decomposition cache
|
|
231
|
+
self._cached_layers = None
|
|
232
|
+
self._cached_residual = None
|
|
233
|
+
self._cached_key = None
|
|
234
|
+
|
|
235
|
+
# per-layer configs
|
|
236
|
+
self.layers = 4
|
|
237
|
+
self.base_sigma = 1.0
|
|
238
|
+
self.cfgs: list[LayerCfg] = [LayerCfg() for _ in range(self.layers)]
|
|
239
|
+
|
|
240
|
+
# debounce preview updates
|
|
241
|
+
self._preview_timer = QTimer(self)
|
|
242
|
+
self._preview_timer.setSingleShot(True)
|
|
243
|
+
self._preview_timer.timeout.connect(self._rebuild_preview)
|
|
244
|
+
|
|
245
|
+
self._build_ui()
|
|
246
|
+
|
|
247
|
+
# ───── NEW: initialization busy dialog ─────
|
|
248
|
+
prog = QProgressDialog("Initializing multiscale decomposition…", "", 0, 0, self)
|
|
249
|
+
prog.setWindowTitle("Multiscale Decomposition")
|
|
250
|
+
prog.setWindowModality(Qt.WindowModality.ApplicationModal)
|
|
251
|
+
prog.setCancelButton(None) # no cancel button, just a busy indicator
|
|
252
|
+
prog.setMinimumDuration(0) # show immediately
|
|
253
|
+
prog.show()
|
|
254
|
+
QApplication.processEvents()
|
|
255
|
+
|
|
256
|
+
# heavy work (MADs, blurs, etc.)
|
|
257
|
+
self._recompute_decomp(force=True)
|
|
258
|
+
self._rebuild_preview()
|
|
259
|
+
|
|
260
|
+
prog.close()
|
|
261
|
+
# ─────────────── END NEW ───────────────
|
|
262
|
+
|
|
263
|
+
QTimer.singleShot(0, self._fit_view)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
# ---------- UI ----------
|
|
267
|
+
def _build_ui(self):
|
|
268
|
+
root = QHBoxLayout(self)
|
|
269
|
+
|
|
270
|
+
# Splitter between preview (left) and controls (right)
|
|
271
|
+
splitter = QSplitter(Qt.Orientation.Horizontal)
|
|
272
|
+
root.addWidget(splitter)
|
|
273
|
+
|
|
274
|
+
# ----- LEFT: preview -----
|
|
275
|
+
left_widget = QWidget(self)
|
|
276
|
+
left = QVBoxLayout(left_widget)
|
|
277
|
+
|
|
278
|
+
self.scene = QGraphicsScene(self)
|
|
279
|
+
self.view = _ZoomPanView(self.scene)
|
|
280
|
+
self.view.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
|
281
|
+
self.pix = QGraphicsPixmapItem()
|
|
282
|
+
self.scene.addItem(self.pix)
|
|
283
|
+
|
|
284
|
+
left.addWidget(self.view)
|
|
285
|
+
|
|
286
|
+
zoom_row = QHBoxLayout()
|
|
287
|
+
|
|
288
|
+
self.zoom_out_btn = QToolButton()
|
|
289
|
+
self.zoom_out_btn.setIcon(QIcon.fromTheme("zoom-out"))
|
|
290
|
+
self.zoom_out_btn.setToolTip("Zoom Out")
|
|
291
|
+
|
|
292
|
+
self.zoom_in_btn = QToolButton()
|
|
293
|
+
self.zoom_in_btn.setIcon(QIcon.fromTheme("zoom-in"))
|
|
294
|
+
self.zoom_in_btn.setToolTip("Zoom In")
|
|
295
|
+
|
|
296
|
+
self.fit_btn = QToolButton()
|
|
297
|
+
self.fit_btn.setIcon(QIcon.fromTheme("zoom-fit-best"))
|
|
298
|
+
self.fit_btn.setToolTip("Fit to Preview")
|
|
299
|
+
|
|
300
|
+
self.one_to_one_btn = QToolButton()
|
|
301
|
+
self.one_to_one_btn.setIcon(QIcon.fromTheme("zoom-original"))
|
|
302
|
+
self.one_to_one_btn.setToolTip("1:1")
|
|
303
|
+
|
|
304
|
+
self.zoom_out_btn.clicked.connect(lambda: self.view.scale(0.8, 0.8))
|
|
305
|
+
self.zoom_in_btn.clicked.connect(lambda: self.view.scale(1.25, 1.25))
|
|
306
|
+
self.fit_btn.clicked.connect(self._fit_view)
|
|
307
|
+
self.one_to_one_btn.clicked.connect(self._one_to_one)
|
|
308
|
+
|
|
309
|
+
zoom_row.addStretch(1)
|
|
310
|
+
zoom_row.addWidget(self.zoom_out_btn)
|
|
311
|
+
zoom_row.addWidget(self.zoom_in_btn)
|
|
312
|
+
zoom_row.addSpacing(10)
|
|
313
|
+
zoom_row.addWidget(self.fit_btn)
|
|
314
|
+
zoom_row.addWidget(self.one_to_one_btn)
|
|
315
|
+
zoom_row.addStretch(1)
|
|
316
|
+
|
|
317
|
+
left.addLayout(zoom_row)
|
|
318
|
+
|
|
319
|
+
# ----- RIGHT: controls -----
|
|
320
|
+
right_widget = QWidget(self)
|
|
321
|
+
right = QVBoxLayout(right_widget)
|
|
322
|
+
|
|
323
|
+
gb_global = QGroupBox("Global")
|
|
324
|
+
form = QFormLayout(gb_global)
|
|
325
|
+
|
|
326
|
+
self.spin_layers = QSpinBox()
|
|
327
|
+
self.spin_layers.setRange(1, 10)
|
|
328
|
+
self.spin_layers.setValue(self.layers)
|
|
329
|
+
|
|
330
|
+
self.spin_sigma = QDoubleSpinBox()
|
|
331
|
+
self.spin_sigma.setRange(0.3, 5.0)
|
|
332
|
+
self.spin_sigma.setSingleStep(0.1)
|
|
333
|
+
self.spin_sigma.setValue(self.base_sigma)
|
|
334
|
+
|
|
335
|
+
self.cb_linked_rgb = QCheckBox("Linked RGB (apply same params to all channels)")
|
|
336
|
+
self.cb_linked_rgb.setChecked(True)
|
|
337
|
+
|
|
338
|
+
# New: Mode combo (Mean vs Linear)
|
|
339
|
+
self.combo_mode = QComboBox()
|
|
340
|
+
self.combo_mode.addItems(["μ–σ Thresholding", "Linear"])
|
|
341
|
+
self.combo_mode.setCurrentText("μ–σ Thresholding")
|
|
342
|
+
self.combo_mode.setToolTip(
|
|
343
|
+
"Multiscale mode:\n"
|
|
344
|
+
"• μ–σ Thresholding: σ-based thresholding + denoise and gain (nonlinear).\n"
|
|
345
|
+
"• Linear: strictly linear multiscale transform; only Gain is applied."
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
self.combo_preview = QComboBox()
|
|
349
|
+
self._refresh_preview_combo()
|
|
350
|
+
|
|
351
|
+
form.addRow("Layers:", self.spin_layers)
|
|
352
|
+
form.addRow("Base sigma:", self.spin_sigma)
|
|
353
|
+
form.addRow(self.cb_linked_rgb)
|
|
354
|
+
form.addRow("Mode:", self.combo_mode) # <── NEW ROW
|
|
355
|
+
form.addRow("Layer preview:", self.combo_preview)
|
|
356
|
+
|
|
357
|
+
right.addWidget(gb_global)
|
|
358
|
+
|
|
359
|
+
# Layers table
|
|
360
|
+
gb_layers = QGroupBox("Layers")
|
|
361
|
+
v = QVBoxLayout(gb_layers)
|
|
362
|
+
self.table = QTableWidget(0, 8)
|
|
363
|
+
self.table.setHorizontalHeaderLabels(
|
|
364
|
+
["On", "Layer", "Scale", "Gain", "Thr (σ)", "Amt", "NR", "Type"]
|
|
365
|
+
)
|
|
366
|
+
|
|
367
|
+
self.table.verticalHeader().setVisible(False)
|
|
368
|
+
self.table.setSelectionBehavior(self.table.SelectionBehavior.SelectRows)
|
|
369
|
+
self.table.setSelectionMode(self.table.SelectionMode.SingleSelection)
|
|
370
|
+
v.addWidget(self.table)
|
|
371
|
+
right.addWidget(gb_layers, stretch=1)
|
|
372
|
+
|
|
373
|
+
# Per-layer editor (now with sliders)
|
|
374
|
+
gb_edit = QGroupBox("Selected Layer")
|
|
375
|
+
ef = QFormLayout(gb_edit)
|
|
376
|
+
self.lbl_sel = QLabel("Layer: —")
|
|
377
|
+
|
|
378
|
+
# --- Spin boxes ---
|
|
379
|
+
self.spin_gain = QDoubleSpinBox()
|
|
380
|
+
self.spin_gain.setRange(0.0, 3.0)
|
|
381
|
+
self.spin_gain.setSingleStep(0.05)
|
|
382
|
+
self.spin_gain.setValue(1.0)
|
|
383
|
+
self.spin_gain.setToolTip(
|
|
384
|
+
"Gain: multiplies the detail coefficients on this layer.\n"
|
|
385
|
+
"1.0 = unchanged, >1.0 boosts detail, <1.0 reduces it."
|
|
386
|
+
)
|
|
387
|
+
|
|
388
|
+
self.spin_thr = QDoubleSpinBox()
|
|
389
|
+
self.spin_thr.setRange(0.0, 10.0) # N·σ
|
|
390
|
+
self.spin_thr.setSingleStep(0.1)
|
|
391
|
+
self.spin_thr.setDecimals(2)
|
|
392
|
+
self.spin_thr.setToolTip(
|
|
393
|
+
"Threshold (σ): soft threshold level in units of this layer's noise σ.\n"
|
|
394
|
+
"0 = no thresholding; 1–3 ≈ mild to strong suppression of small coefficients."
|
|
395
|
+
)
|
|
396
|
+
|
|
397
|
+
self.spin_amt = QDoubleSpinBox()
|
|
398
|
+
self.spin_amt.setRange(0.0, 1.0)
|
|
399
|
+
self.spin_amt.setSingleStep(0.05)
|
|
400
|
+
self.spin_amt.setToolTip(
|
|
401
|
+
"Amount: blend factor toward the thresholded version of the layer.\n"
|
|
402
|
+
"0 = ignore thresholding, 1 = fully use the thresholded layer."
|
|
403
|
+
)
|
|
404
|
+
|
|
405
|
+
self.spin_denoise = QDoubleSpinBox()
|
|
406
|
+
self.spin_denoise.setRange(0.0, 1.0)
|
|
407
|
+
self.spin_denoise.setSingleStep(0.05)
|
|
408
|
+
self.spin_denoise.setValue(0.0)
|
|
409
|
+
self.spin_denoise.setToolTip(
|
|
410
|
+
"Denoise: extra multiscale noise reduction on this layer.\n"
|
|
411
|
+
"0 = off, 1 = strong NR (≈3σ soft threshold blended in)."
|
|
412
|
+
)
|
|
413
|
+
|
|
414
|
+
# --- Sliders (int ranges, mapped to spins) ---
|
|
415
|
+
self.slider_gain = QSlider(Qt.Orientation.Horizontal)
|
|
416
|
+
self.slider_gain.setRange(0, 300) # 0..3.00
|
|
417
|
+
self.slider_gain.setToolTip(self.spin_gain.toolTip())
|
|
418
|
+
|
|
419
|
+
self.slider_thr = QSlider(Qt.Orientation.Horizontal)
|
|
420
|
+
self.slider_thr.setRange(0, 1000) # 0..10.00 σ (×0.01)
|
|
421
|
+
self.slider_thr.setToolTip(self.spin_thr.toolTip())
|
|
422
|
+
|
|
423
|
+
self.slider_amt = QSlider(Qt.Orientation.Horizontal)
|
|
424
|
+
self.slider_amt.setRange(0, 100) # 0..1.00
|
|
425
|
+
self.slider_amt.setToolTip(self.spin_amt.toolTip())
|
|
426
|
+
|
|
427
|
+
self.slider_denoise = QSlider(Qt.Orientation.Horizontal)
|
|
428
|
+
self.slider_denoise.setRange(0, 100) # 0..1.00
|
|
429
|
+
self.slider_denoise.setToolTip(self.spin_denoise.toolTip())
|
|
430
|
+
|
|
431
|
+
# Layout rows: label -> [slider | spinbox]
|
|
432
|
+
ef.addRow(self.lbl_sel)
|
|
433
|
+
|
|
434
|
+
gain_row = QHBoxLayout()
|
|
435
|
+
gain_row.addWidget(self.slider_gain)
|
|
436
|
+
gain_row.addWidget(self.spin_gain)
|
|
437
|
+
ef.addRow("Gain:", gain_row)
|
|
438
|
+
|
|
439
|
+
thr_row = QHBoxLayout()
|
|
440
|
+
thr_row.addWidget(self.slider_thr)
|
|
441
|
+
thr_row.addWidget(self.spin_thr)
|
|
442
|
+
ef.addRow("Threshold (σ):", thr_row)
|
|
443
|
+
|
|
444
|
+
amt_row = QHBoxLayout()
|
|
445
|
+
amt_row.addWidget(self.slider_amt)
|
|
446
|
+
amt_row.addWidget(self.spin_amt)
|
|
447
|
+
ef.addRow("Amount:", amt_row)
|
|
448
|
+
|
|
449
|
+
dn_row = QHBoxLayout()
|
|
450
|
+
dn_row.addWidget(self.slider_denoise)
|
|
451
|
+
dn_row.addWidget(self.spin_denoise)
|
|
452
|
+
ef.addRow("Denoise:", dn_row)
|
|
453
|
+
|
|
454
|
+
right.addWidget(gb_edit)
|
|
455
|
+
|
|
456
|
+
# Buttons
|
|
457
|
+
btn_row = QHBoxLayout()
|
|
458
|
+
self.btn_apply = QPushButton("Apply to Document")
|
|
459
|
+
self.btn_detail_new = QPushButton("Send to New Document")
|
|
460
|
+
self.btn_split_layers = QPushButton("Split Layers to Documents")
|
|
461
|
+
self.btn_close = QPushButton("Close")
|
|
462
|
+
|
|
463
|
+
btn_row.addStretch(1)
|
|
464
|
+
btn_row.addWidget(self.btn_apply)
|
|
465
|
+
btn_row.addWidget(self.btn_detail_new)
|
|
466
|
+
btn_row.addWidget(self.btn_split_layers)
|
|
467
|
+
btn_row.addWidget(self.btn_close)
|
|
468
|
+
right.addLayout(btn_row)
|
|
469
|
+
|
|
470
|
+
# Add widgets to splitter
|
|
471
|
+
splitter.addWidget(left_widget)
|
|
472
|
+
splitter.addWidget(right_widget)
|
|
473
|
+
splitter.setStretchFactor(0, 2)
|
|
474
|
+
splitter.setStretchFactor(1, 1)
|
|
475
|
+
|
|
476
|
+
# ----- Signals -----
|
|
477
|
+
self.spin_layers.valueChanged.connect(self._on_layers_changed)
|
|
478
|
+
self.spin_sigma.valueChanged.connect(self._on_global_changed)
|
|
479
|
+
self.combo_mode.currentIndexChanged.connect(self._on_mode_changed)
|
|
480
|
+
self.combo_preview.currentIndexChanged.connect(self._schedule_preview)
|
|
481
|
+
|
|
482
|
+
self.table.itemSelectionChanged.connect(self._on_table_select)
|
|
483
|
+
|
|
484
|
+
# spinboxes -> layer cfg
|
|
485
|
+
self.spin_gain.valueChanged.connect(self._on_layer_editor_changed)
|
|
486
|
+
self.spin_thr.valueChanged.connect(self._on_layer_editor_changed)
|
|
487
|
+
self.spin_amt.valueChanged.connect(self._on_layer_editor_changed)
|
|
488
|
+
self.spin_denoise.valueChanged.connect(self._on_layer_editor_changed)
|
|
489
|
+
|
|
490
|
+
# sliders -> spinboxes
|
|
491
|
+
self.slider_gain.valueChanged.connect(self._on_gain_slider_changed)
|
|
492
|
+
self.slider_thr.valueChanged.connect(self._on_thr_slider_changed)
|
|
493
|
+
self.slider_amt.valueChanged.connect(self._on_amt_slider_changed)
|
|
494
|
+
self.slider_denoise.valueChanged.connect(self._on_dn_slider_changed)
|
|
495
|
+
|
|
496
|
+
self.btn_apply.clicked.connect(self._commit_to_doc)
|
|
497
|
+
self.btn_detail_new.clicked.connect(self._send_detail_to_new_doc)
|
|
498
|
+
self.btn_split_layers.clicked.connect(self._split_layers_to_docs)
|
|
499
|
+
self.btn_close.clicked.connect(self.reject)
|
|
500
|
+
|
|
501
|
+
# ---------- Preview plumbing ----------
|
|
502
|
+
def _on_mode_changed(self, idx: int):
|
|
503
|
+
# Re-enable/disable controls as needed
|
|
504
|
+
self._update_param_widgets_for_mode()
|
|
505
|
+
self._schedule_preview()
|
|
506
|
+
|
|
507
|
+
def _schedule_preview(self):
|
|
508
|
+
self._preview_timer.start(60)
|
|
509
|
+
|
|
510
|
+
def _recompute_decomp(self, force: bool = False):
|
|
511
|
+
layers = int(self.spin_layers.value())
|
|
512
|
+
base_sigma = float(self.spin_sigma.value())
|
|
513
|
+
key = (layers, base_sigma)
|
|
514
|
+
|
|
515
|
+
if (not force) and self._cached_key == key and self._cached_layers is not None:
|
|
516
|
+
return
|
|
517
|
+
|
|
518
|
+
self.layers = layers
|
|
519
|
+
self.base_sigma = base_sigma
|
|
520
|
+
|
|
521
|
+
self._cached_layers, self._cached_residual = multiscale_decompose(
|
|
522
|
+
self._image, layers=self.layers, base_sigma=self.base_sigma
|
|
523
|
+
)
|
|
524
|
+
self._cached_key = key
|
|
525
|
+
|
|
526
|
+
self._layer_noise = []
|
|
527
|
+
for w in self._cached_layers:
|
|
528
|
+
sigma = _robust_sigma(w) if w.size else 1e-6
|
|
529
|
+
self._layer_noise.append(sigma)
|
|
530
|
+
|
|
531
|
+
# ensure cfg list matches layer count
|
|
532
|
+
if len(self.cfgs) != self.layers:
|
|
533
|
+
old = self.cfgs[:]
|
|
534
|
+
self.cfgs = [LayerCfg() for _ in range(self.layers)]
|
|
535
|
+
for i in range(min(len(old), self.layers)):
|
|
536
|
+
self.cfgs[i] = old[i]
|
|
537
|
+
|
|
538
|
+
self._rebuild_table()
|
|
539
|
+
self._refresh_preview_combo()
|
|
540
|
+
|
|
541
|
+
def _build_tuned_layers(self):
|
|
542
|
+
"""
|
|
543
|
+
Ensure decomposition is current and apply per-layer ops
|
|
544
|
+
using the current mode and layer configs.
|
|
545
|
+
|
|
546
|
+
Returns (tuned_layers, residual) or (None, None) on failure.
|
|
547
|
+
"""
|
|
548
|
+
self._recompute_decomp(force=False)
|
|
549
|
+
|
|
550
|
+
details = self._cached_layers
|
|
551
|
+
residual = self._cached_residual
|
|
552
|
+
if details is None or residual is None:
|
|
553
|
+
return None, None
|
|
554
|
+
|
|
555
|
+
mode = self.combo_mode.currentText() # "μ–σ Thresholding" or "Linear"
|
|
556
|
+
|
|
557
|
+
tuned = []
|
|
558
|
+
for i, w in enumerate(details):
|
|
559
|
+
cfg = self.cfgs[i]
|
|
560
|
+
if not cfg.enabled:
|
|
561
|
+
tuned.append(np.zeros_like(w))
|
|
562
|
+
else:
|
|
563
|
+
sigma = None
|
|
564
|
+
if self._layer_noise is not None and i < len(self._layer_noise):
|
|
565
|
+
sigma = self._layer_noise[i]
|
|
566
|
+
tuned.append(
|
|
567
|
+
apply_layer_ops(
|
|
568
|
+
w,
|
|
569
|
+
cfg.bias_gain,
|
|
570
|
+
cfg.thr,
|
|
571
|
+
cfg.amount,
|
|
572
|
+
cfg.denoise,
|
|
573
|
+
sigma,
|
|
574
|
+
mode=mode,
|
|
575
|
+
)
|
|
576
|
+
)
|
|
577
|
+
|
|
578
|
+
return tuned, residual
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
def _rebuild_preview(self):
|
|
582
|
+
tuned, residual = self._build_tuned_layers()
|
|
583
|
+
if tuned is None or residual is None:
|
|
584
|
+
return
|
|
585
|
+
|
|
586
|
+
# reconstruction (keep raw version for visualization)
|
|
587
|
+
res = residual if self.residual_enabled else np.zeros_like(residual)
|
|
588
|
+
out_raw = multiscale_reconstruct(tuned, res)
|
|
589
|
+
out = np.clip(out_raw, 0.0, 1.0).astype(np.float32, copy=False)
|
|
590
|
+
|
|
591
|
+
sel = self.combo_preview.currentData()
|
|
592
|
+
if sel is None or sel == "final":
|
|
593
|
+
if not self.residual_enabled:
|
|
594
|
+
# Detail-only visualization: SAME style as detail-layer preview
|
|
595
|
+
d = out_raw.astype(np.float32, copy=False)
|
|
596
|
+
vis = 0.5 + d * 4.0 # same gain as single-layer view
|
|
597
|
+
self._preview_img = np.clip(vis, 0.0, 1.0).astype(np.float32, copy=False)
|
|
598
|
+
else:
|
|
599
|
+
self._preview_img = out
|
|
600
|
+
|
|
601
|
+
elif sel == "residual":
|
|
602
|
+
self._preview_img = np.clip(residual, 0, 1)
|
|
603
|
+
|
|
604
|
+
else:
|
|
605
|
+
# sel is int index of detail layer
|
|
606
|
+
w = tuned[int(sel)]
|
|
607
|
+
vis = np.clip(0.5 + (w * 4.0), 0.0, 1.0)
|
|
608
|
+
self._preview_img = vis.astype(np.float32, copy=False)
|
|
609
|
+
|
|
610
|
+
self._refresh_pix()
|
|
611
|
+
|
|
612
|
+
def _update_param_widgets_for_mode(self):
|
|
613
|
+
linear = (self.combo_mode.currentText() == "Linear")
|
|
614
|
+
|
|
615
|
+
# Always allow Gain in both modes
|
|
616
|
+
gain_widgets = (self.spin_gain, self.slider_gain)
|
|
617
|
+
|
|
618
|
+
# These are only meaningful in Mean mode
|
|
619
|
+
nonlin_widgets = (
|
|
620
|
+
self.spin_thr, self.slider_thr,
|
|
621
|
+
self.spin_amt, self.slider_amt,
|
|
622
|
+
self.spin_denoise, self.slider_denoise,
|
|
623
|
+
)
|
|
624
|
+
|
|
625
|
+
# For residual row we already disable everything in _load_layer_into_editor,
|
|
626
|
+
# so here we just respect the current selection.
|
|
627
|
+
idx = getattr(self, "_selected_layer", None)
|
|
628
|
+
if idx is None or idx == self.layers:
|
|
629
|
+
# Residual – handled in _load_layer_into_editor
|
|
630
|
+
return
|
|
631
|
+
|
|
632
|
+
for w in gain_widgets:
|
|
633
|
+
w.setEnabled(True)
|
|
634
|
+
|
|
635
|
+
for w in nonlin_widgets:
|
|
636
|
+
w.setEnabled(not linear)
|
|
637
|
+
|
|
638
|
+
|
|
639
|
+
def _np_to_qpix(self, img: np.ndarray) -> QPixmap:
|
|
640
|
+
arr = np.ascontiguousarray(np.clip(img * 255.0, 0, 255).astype(np.uint8))
|
|
641
|
+
h, w = arr.shape[:2]
|
|
642
|
+
if arr.ndim == 2:
|
|
643
|
+
arr = np.repeat(arr[:, :, None], 3, axis=2)
|
|
644
|
+
qimg = QImage(arr.data, w, h, 3*w, QImage.Format.Format_RGB888)
|
|
645
|
+
return QPixmap.fromImage(qimg)
|
|
646
|
+
|
|
647
|
+
def _refresh_pix(self):
|
|
648
|
+
self.pix.setPixmap(self._np_to_qpix(self._preview_img))
|
|
649
|
+
self.scene.setSceneRect(self.pix.boundingRect())
|
|
650
|
+
|
|
651
|
+
def _fit_view(self):
|
|
652
|
+
if self.pix.pixmap().isNull():
|
|
653
|
+
return
|
|
654
|
+
self.view.resetTransform()
|
|
655
|
+
self.view.fitInView(self.pix, Qt.AspectRatioMode.KeepAspectRatio)
|
|
656
|
+
|
|
657
|
+
def _one_to_one(self):
|
|
658
|
+
self.view.resetTransform()
|
|
659
|
+
|
|
660
|
+
# ---------- Table / layer editing ----------
|
|
661
|
+
def _on_gain_slider_changed(self, v: int):
|
|
662
|
+
# 0..300 -> 0.00..3.00
|
|
663
|
+
val = v / 100.0
|
|
664
|
+
self.spin_gain.blockSignals(True)
|
|
665
|
+
self.spin_gain.setValue(val)
|
|
666
|
+
self.spin_gain.blockSignals(False)
|
|
667
|
+
self._on_layer_editor_changed()
|
|
668
|
+
|
|
669
|
+
def _on_thr_slider_changed(self, v: int):
|
|
670
|
+
# 0..1000 -> 0.00..10.00 σ
|
|
671
|
+
val = v / 100.0
|
|
672
|
+
self.spin_thr.blockSignals(True)
|
|
673
|
+
self.spin_thr.setValue(val)
|
|
674
|
+
self.spin_thr.blockSignals(False)
|
|
675
|
+
self._on_layer_editor_changed()
|
|
676
|
+
|
|
677
|
+
|
|
678
|
+
def _on_amt_slider_changed(self, v: int):
|
|
679
|
+
# 0..100 -> 0.00..1.00
|
|
680
|
+
val = v / 100.0
|
|
681
|
+
self.spin_amt.blockSignals(True)
|
|
682
|
+
self.spin_amt.setValue(val)
|
|
683
|
+
self.spin_amt.blockSignals(False)
|
|
684
|
+
self._on_layer_editor_changed()
|
|
685
|
+
|
|
686
|
+
def _on_dn_slider_changed(self, v: int):
|
|
687
|
+
# 0..100 -> 0.00..1.00
|
|
688
|
+
val = v / 100.0
|
|
689
|
+
self.spin_denoise.blockSignals(True)
|
|
690
|
+
self.spin_denoise.setValue(val)
|
|
691
|
+
self.spin_denoise.blockSignals(False)
|
|
692
|
+
self._on_layer_editor_changed()
|
|
693
|
+
|
|
694
|
+
|
|
695
|
+
def _rebuild_table(self):
|
|
696
|
+
self.table.blockSignals(True)
|
|
697
|
+
try:
|
|
698
|
+
# +1 row for residual ("R")
|
|
699
|
+
self.table.setRowCount(self.layers + 1)
|
|
700
|
+
|
|
701
|
+
# detail rows
|
|
702
|
+
for i in range(self.layers):
|
|
703
|
+
cfg = self.cfgs[i]
|
|
704
|
+
|
|
705
|
+
item_on = QTableWidgetItem("")
|
|
706
|
+
item_on.setFlags(item_on.flags() | Qt.ItemFlag.ItemIsUserCheckable)
|
|
707
|
+
item_on.setCheckState(Qt.CheckState.Checked if cfg.enabled else Qt.CheckState.Unchecked)
|
|
708
|
+
self.table.setItem(i, 0, item_on)
|
|
709
|
+
|
|
710
|
+
self.table.setItem(i, 1, QTableWidgetItem(str(i + 1)))
|
|
711
|
+
self.table.setItem(i, 2, QTableWidgetItem(f"{self.base_sigma * (2**i):.2f}"))
|
|
712
|
+
self.table.setItem(i, 3, QTableWidgetItem(f"{cfg.bias_gain:.2f}"))
|
|
713
|
+
self.table.setItem(i, 4, QTableWidgetItem(f"{cfg.thr:.2f}")) # N·σ
|
|
714
|
+
self.table.setItem(i, 5, QTableWidgetItem(f"{cfg.amount:.2f}"))
|
|
715
|
+
self.table.setItem(i, 6, QTableWidgetItem(f"{cfg.denoise:.2f}"))
|
|
716
|
+
|
|
717
|
+
self.table.setItem(i, 7, QTableWidgetItem("D"))
|
|
718
|
+
|
|
719
|
+
# residual row
|
|
720
|
+
r = self.layers
|
|
721
|
+
item_on = QTableWidgetItem("")
|
|
722
|
+
item_on.setFlags(item_on.flags() | Qt.ItemFlag.ItemIsUserCheckable)
|
|
723
|
+
item_on.setCheckState(
|
|
724
|
+
Qt.CheckState.Checked if self.residual_enabled else Qt.CheckState.Unchecked
|
|
725
|
+
)
|
|
726
|
+
self.table.setItem(r, 0, item_on)
|
|
727
|
+
|
|
728
|
+
self.table.setItem(r, 1, QTableWidgetItem("R"))
|
|
729
|
+
self.table.setItem(r, 2, QTableWidgetItem("—"))
|
|
730
|
+
self.table.setItem(r, 3, QTableWidgetItem("1.00"))
|
|
731
|
+
self.table.setItem(r, 4, QTableWidgetItem("0.0000"))
|
|
732
|
+
self.table.setItem(r, 5, QTableWidgetItem("0.00"))
|
|
733
|
+
self.table.setItem(r, 6, QTableWidgetItem("0.00"))
|
|
734
|
+
self.table.setItem(r, 7, QTableWidgetItem("R"))
|
|
735
|
+
|
|
736
|
+
finally:
|
|
737
|
+
self.table.blockSignals(False)
|
|
738
|
+
|
|
739
|
+
# connect once (avoid stacking connects)
|
|
740
|
+
try:
|
|
741
|
+
self.table.itemChanged.disconnect(self._on_table_item_changed)
|
|
742
|
+
except Exception:
|
|
743
|
+
pass
|
|
744
|
+
self.table.itemChanged.connect(self._on_table_item_changed)
|
|
745
|
+
|
|
746
|
+
if self.layers > 0 and not self.table.selectedItems():
|
|
747
|
+
self.table.selectRow(0)
|
|
748
|
+
self._load_layer_into_editor(0)
|
|
749
|
+
|
|
750
|
+
def _on_table_item_changed(self, item: QTableWidgetItem):
|
|
751
|
+
r, c = item.row(), item.column()
|
|
752
|
+
|
|
753
|
+
# Residual row
|
|
754
|
+
if r == self.layers:
|
|
755
|
+
if c == 0:
|
|
756
|
+
self.residual_enabled = (item.checkState() == Qt.CheckState.Checked)
|
|
757
|
+
self._schedule_preview()
|
|
758
|
+
# ignore other edits for residual
|
|
759
|
+
return
|
|
760
|
+
|
|
761
|
+
if not (0 <= r < len(self.cfgs)):
|
|
762
|
+
return
|
|
763
|
+
|
|
764
|
+
cfg = self.cfgs[r]
|
|
765
|
+
|
|
766
|
+
if c == 0:
|
|
767
|
+
# On/off
|
|
768
|
+
cfg.enabled = (item.checkState() == Qt.CheckState.Checked)
|
|
769
|
+
self._schedule_preview()
|
|
770
|
+
return
|
|
771
|
+
|
|
772
|
+
# numeric columns: Gain(3), Thr(4), Amt(5), NR(6)
|
|
773
|
+
try:
|
|
774
|
+
text = item.text().strip()
|
|
775
|
+
val = float(text) if text else 0.0
|
|
776
|
+
except Exception:
|
|
777
|
+
return
|
|
778
|
+
|
|
779
|
+
if c == 3:
|
|
780
|
+
cfg.bias_gain = val
|
|
781
|
+
elif c == 4:
|
|
782
|
+
cfg.thr = val
|
|
783
|
+
elif c == 5:
|
|
784
|
+
cfg.amount = val
|
|
785
|
+
elif c == 6:
|
|
786
|
+
cfg.denoise = val
|
|
787
|
+
else:
|
|
788
|
+
return
|
|
789
|
+
|
|
790
|
+
# If this row is currently selected, update editor widgets too
|
|
791
|
+
if getattr(self, "_selected_layer", None) == r:
|
|
792
|
+
self._load_layer_into_editor(r)
|
|
793
|
+
|
|
794
|
+
self._schedule_preview()
|
|
795
|
+
|
|
796
|
+
|
|
797
|
+
|
|
798
|
+
def _on_table_select(self):
|
|
799
|
+
rows = {it.row() for it in self.table.selectedItems()}
|
|
800
|
+
if not rows:
|
|
801
|
+
return
|
|
802
|
+
r = min(rows)
|
|
803
|
+
self._load_layer_into_editor(r)
|
|
804
|
+
|
|
805
|
+
def _load_layer_into_editor(self, idx: int):
|
|
806
|
+
self._selected_layer = idx
|
|
807
|
+
|
|
808
|
+
if idx == self.layers:
|
|
809
|
+
self.lbl_sel.setText("Layer: R (Residual)")
|
|
810
|
+
for w in (self.spin_gain, self.spin_thr, self.spin_amt, self.spin_denoise,
|
|
811
|
+
self.slider_gain, self.slider_thr, self.slider_amt, self.slider_denoise):
|
|
812
|
+
w.setEnabled(False)
|
|
813
|
+
return
|
|
814
|
+
|
|
815
|
+
for w in (self.spin_gain, self.spin_thr, self.spin_amt, self.spin_denoise,
|
|
816
|
+
self.slider_gain, self.slider_thr, self.slider_amt, self.slider_denoise):
|
|
817
|
+
w.setEnabled(True)
|
|
818
|
+
|
|
819
|
+
cfg = self.cfgs[idx]
|
|
820
|
+
self.lbl_sel.setText(f"Layer: {idx+1} / {self.layers}")
|
|
821
|
+
|
|
822
|
+
# spins + sliders in sync
|
|
823
|
+
self.spin_gain.blockSignals(True)
|
|
824
|
+
self.spin_thr.blockSignals(True)
|
|
825
|
+
self.spin_amt.blockSignals(True)
|
|
826
|
+
self.spin_denoise.blockSignals(True)
|
|
827
|
+
|
|
828
|
+
self.slider_gain.blockSignals(True)
|
|
829
|
+
self.slider_thr.blockSignals(True)
|
|
830
|
+
self.slider_amt.blockSignals(True)
|
|
831
|
+
self.slider_denoise.blockSignals(True)
|
|
832
|
+
try:
|
|
833
|
+
self.spin_gain.setValue(cfg.bias_gain)
|
|
834
|
+
self.spin_thr.setValue(cfg.thr) # thr is N·σ now
|
|
835
|
+
self.spin_amt.setValue(cfg.amount)
|
|
836
|
+
self.spin_denoise.setValue(cfg.denoise)
|
|
837
|
+
|
|
838
|
+
self.slider_gain.setValue(int(round(cfg.bias_gain * 100.0)))
|
|
839
|
+
self.slider_thr.setValue(int(round(cfg.thr * 100.0))) # N·σ → 0..1000
|
|
840
|
+
self.slider_amt.setValue(int(round(cfg.amount * 100.0)))
|
|
841
|
+
self.slider_denoise.setValue(int(round(cfg.denoise * 100.0)))
|
|
842
|
+
finally:
|
|
843
|
+
self.spin_gain.blockSignals(False)
|
|
844
|
+
self.spin_thr.blockSignals(False)
|
|
845
|
+
self.spin_amt.blockSignals(False)
|
|
846
|
+
self.spin_denoise.blockSignals(False)
|
|
847
|
+
self.slider_gain.blockSignals(False)
|
|
848
|
+
self.slider_thr.blockSignals(False)
|
|
849
|
+
self.slider_amt.blockSignals(False)
|
|
850
|
+
self.slider_denoise.blockSignals(False)
|
|
851
|
+
self._update_param_widgets_for_mode()
|
|
852
|
+
|
|
853
|
+
|
|
854
|
+
|
|
855
|
+
def _on_layer_editor_changed(self):
|
|
856
|
+
idx = getattr(self, "_selected_layer", None)
|
|
857
|
+
if idx is None or not (0 <= idx < len(self.cfgs)):
|
|
858
|
+
return
|
|
859
|
+
cfg = self.cfgs[idx]
|
|
860
|
+
cfg.bias_gain = float(self.spin_gain.value())
|
|
861
|
+
cfg.thr = float(self.spin_thr.value())
|
|
862
|
+
cfg.amount = float(self.spin_amt.value())
|
|
863
|
+
cfg.denoise = float(self.spin_denoise.value())
|
|
864
|
+
|
|
865
|
+
# keep table in sync
|
|
866
|
+
self.table.blockSignals(True)
|
|
867
|
+
try:
|
|
868
|
+
self.table.item(idx, 3).setText(f"{cfg.bias_gain:.2f}")
|
|
869
|
+
self.table.item(idx, 4).setText(f"{cfg.thr:.2f}") # N·σ
|
|
870
|
+
self.table.item(idx, 5).setText(f"{cfg.amount:.2f}")
|
|
871
|
+
self.table.item(idx, 6).setText(f"{cfg.denoise:.2f}")
|
|
872
|
+
|
|
873
|
+
finally:
|
|
874
|
+
self.table.blockSignals(False)
|
|
875
|
+
|
|
876
|
+
self._schedule_preview()
|
|
877
|
+
|
|
878
|
+
def _on_layers_changed(self):
|
|
879
|
+
self._recompute_decomp(force=True)
|
|
880
|
+
self._schedule_preview()
|
|
881
|
+
|
|
882
|
+
def _on_global_changed(self):
|
|
883
|
+
self._recompute_decomp(force=True)
|
|
884
|
+
self._schedule_preview()
|
|
885
|
+
|
|
886
|
+
def _refresh_preview_combo(self):
|
|
887
|
+
self.combo_preview.blockSignals(True)
|
|
888
|
+
try:
|
|
889
|
+
self.combo_preview.clear()
|
|
890
|
+
self.combo_preview.addItem("Final", userData="final")
|
|
891
|
+
self.combo_preview.addItem("R (Residual)", userData="residual")
|
|
892
|
+
for i in range(self.layers):
|
|
893
|
+
self.combo_preview.addItem(f"Detail Layer {i+1}", userData=i)
|
|
894
|
+
finally:
|
|
895
|
+
self.combo_preview.blockSignals(False)
|
|
896
|
+
|
|
897
|
+
# ---------- Apply to doc ----------
|
|
898
|
+
def _commit_to_doc(self):
|
|
899
|
+
tuned, residual = self._build_tuned_layers()
|
|
900
|
+
if tuned is None or residual is None:
|
|
901
|
+
return
|
|
902
|
+
|
|
903
|
+
# --- Reconstruction (match preview behavior) ---
|
|
904
|
+
res = residual if self.residual_enabled else np.zeros_like(residual)
|
|
905
|
+
out_raw = multiscale_reconstruct(tuned, res)
|
|
906
|
+
|
|
907
|
+
if not self.residual_enabled:
|
|
908
|
+
# Detail-only result: same “mid-gray + gain” hack as preview
|
|
909
|
+
d = out_raw.astype(np.float32, copy=False)
|
|
910
|
+
out = np.clip(0.5 + d * 4.0, 0.0, 1.0).astype(np.float32, copy=False)
|
|
911
|
+
else:
|
|
912
|
+
out = np.clip(out_raw, 0.0, 1.0).astype(np.float32, copy=False)
|
|
913
|
+
|
|
914
|
+
# convert back to mono if original was mono
|
|
915
|
+
if self._orig_mono:
|
|
916
|
+
mono = out[..., 0]
|
|
917
|
+
if len(self._orig_shape) == 3 and self._orig_shape[2] == 1:
|
|
918
|
+
mono = mono[:, :, None]
|
|
919
|
+
out_final = mono.astype(np.float32, copy=False)
|
|
920
|
+
else:
|
|
921
|
+
out_final = out
|
|
922
|
+
|
|
923
|
+
try:
|
|
924
|
+
if hasattr(self._doc, "set_image"):
|
|
925
|
+
self._doc.set_image(out_final, step_name="Multiscale Decomposition")
|
|
926
|
+
elif hasattr(self._doc, "apply_numpy"):
|
|
927
|
+
self._doc.apply_numpy(out_final, step_name="Multiscale Decomposition")
|
|
928
|
+
else:
|
|
929
|
+
self._doc.image = out_final
|
|
930
|
+
except Exception as e:
|
|
931
|
+
QMessageBox.critical(self, "Multiscale Decomposition", f"Failed to write to document:\n{e}")
|
|
932
|
+
return
|
|
933
|
+
|
|
934
|
+
if hasattr(self.parent(), "_refresh_active_view"):
|
|
935
|
+
try:
|
|
936
|
+
self.parent()._refresh_active_view()
|
|
937
|
+
except Exception:
|
|
938
|
+
pass
|
|
939
|
+
|
|
940
|
+
self.accept()
|
|
941
|
+
|
|
942
|
+
def _send_detail_to_new_doc(self):
|
|
943
|
+
"""
|
|
944
|
+
Send the *final* multiscale result (same as Apply to Document)
|
|
945
|
+
to a brand-new document via DocManager.
|
|
946
|
+
|
|
947
|
+
- If residual is enabled: standard 0..1 clipped composite.
|
|
948
|
+
- If residual is disabled: uses the mid-gray detail-only hack
|
|
949
|
+
(0.5 + d*4.0), just like the preview/commit path.
|
|
950
|
+
"""
|
|
951
|
+
self._recompute_decomp(force=False)
|
|
952
|
+
|
|
953
|
+
details = self._cached_layers
|
|
954
|
+
residual = self._cached_residual
|
|
955
|
+
if details is None or residual is None:
|
|
956
|
+
return
|
|
957
|
+
|
|
958
|
+
dm = self._get_doc_manager()
|
|
959
|
+
if dm is None:
|
|
960
|
+
QMessageBox.warning(
|
|
961
|
+
self,
|
|
962
|
+
"Multiscale Decomposition",
|
|
963
|
+
"No DocManager available to create a new document."
|
|
964
|
+
)
|
|
965
|
+
return
|
|
966
|
+
|
|
967
|
+
# --- Same tuned-layer logic as _commit_to_doc -------------------
|
|
968
|
+
mode = self.combo_mode.currentText() # "μ–σ Thresholding" or "Linear"
|
|
969
|
+
|
|
970
|
+
tuned = []
|
|
971
|
+
for i, w in enumerate(details):
|
|
972
|
+
cfg = self.cfgs[i]
|
|
973
|
+
if not cfg.enabled:
|
|
974
|
+
tuned.append(np.zeros_like(w))
|
|
975
|
+
else:
|
|
976
|
+
sigma = None
|
|
977
|
+
if self._layer_noise is not None and i < len(self._layer_noise):
|
|
978
|
+
sigma = self._layer_noise[i]
|
|
979
|
+
tuned.append(
|
|
980
|
+
apply_layer_ops(
|
|
981
|
+
w,
|
|
982
|
+
cfg.bias_gain,
|
|
983
|
+
cfg.thr,
|
|
984
|
+
cfg.amount,
|
|
985
|
+
cfg.denoise,
|
|
986
|
+
sigma,
|
|
987
|
+
mode=mode,
|
|
988
|
+
)
|
|
989
|
+
)
|
|
990
|
+
|
|
991
|
+
# --- Reconstruction (match Apply-to-Document behavior) ----------
|
|
992
|
+
res = residual if self.residual_enabled else np.zeros_like(residual)
|
|
993
|
+
out_raw = multiscale_reconstruct(tuned, res)
|
|
994
|
+
|
|
995
|
+
if not self.residual_enabled:
|
|
996
|
+
# Detail-only flavor: mid-gray + gain hack
|
|
997
|
+
d = out_raw.astype(np.float32, copy=False)
|
|
998
|
+
out = np.clip(0.5 + d * 4.0, 0.0, 1.0).astype(np.float32, copy=False)
|
|
999
|
+
else:
|
|
1000
|
+
out = np.clip(out_raw, 0.0, 1.0).astype(np.float32, copy=False)
|
|
1001
|
+
|
|
1002
|
+
# --- Back to original mono/color layout -------------------------
|
|
1003
|
+
if self._orig_mono:
|
|
1004
|
+
mono = out[..., 0]
|
|
1005
|
+
if len(self._orig_shape) == 3 and self._orig_shape[2] == 1:
|
|
1006
|
+
mono = mono[:, :, None]
|
|
1007
|
+
out_final = mono.astype(np.float32, copy=False)
|
|
1008
|
+
else:
|
|
1009
|
+
out_final = out
|
|
1010
|
+
|
|
1011
|
+
title = "Multiscale Result"
|
|
1012
|
+
meta = self._build_new_doc_metadata(title, out_final)
|
|
1013
|
+
|
|
1014
|
+
try:
|
|
1015
|
+
dm.create_document(out_final, metadata=meta, name=title)
|
|
1016
|
+
except Exception as e:
|
|
1017
|
+
QMessageBox.critical(
|
|
1018
|
+
self,
|
|
1019
|
+
"Multiscale Decomposition",
|
|
1020
|
+
f"Failed to create new document:\n{e}"
|
|
1021
|
+
)
|
|
1022
|
+
|
|
1023
|
+
def _split_layers_to_docs(self):
|
|
1024
|
+
"""
|
|
1025
|
+
Create a new document for each tuned detail layer *and* the residual.
|
|
1026
|
+
|
|
1027
|
+
- Detail layers use the same mid-gray visualization as the per-layer preview:
|
|
1028
|
+
vis = 0.5 + layer*4.0
|
|
1029
|
+
- Residual layer is just the residual itself (0..1 clipped).
|
|
1030
|
+
"""
|
|
1031
|
+
self._recompute_decomp(force=False)
|
|
1032
|
+
|
|
1033
|
+
details = self._cached_layers
|
|
1034
|
+
residual = self._cached_residual
|
|
1035
|
+
if details is None or residual is None:
|
|
1036
|
+
return
|
|
1037
|
+
|
|
1038
|
+
dm = self._get_doc_manager()
|
|
1039
|
+
if dm is None:
|
|
1040
|
+
QMessageBox.warning(
|
|
1041
|
+
self,
|
|
1042
|
+
"Multiscale Decomposition",
|
|
1043
|
+
"No DocManager available to create new documents."
|
|
1044
|
+
)
|
|
1045
|
+
return
|
|
1046
|
+
|
|
1047
|
+
mode = self.combo_mode.currentText()
|
|
1048
|
+
# Build tuned layers just like everywhere else
|
|
1049
|
+
tuned = []
|
|
1050
|
+
for i, w in enumerate(details):
|
|
1051
|
+
cfg = self.cfgs[i]
|
|
1052
|
+
if not cfg.enabled:
|
|
1053
|
+
tuned.append(np.zeros_like(w))
|
|
1054
|
+
else:
|
|
1055
|
+
sigma = None
|
|
1056
|
+
if self._layer_noise is not None and i < len(self._layer_noise):
|
|
1057
|
+
sigma = self._layer_noise[i]
|
|
1058
|
+
tuned.append(
|
|
1059
|
+
apply_layer_ops(
|
|
1060
|
+
w,
|
|
1061
|
+
cfg.bias_gain,
|
|
1062
|
+
cfg.thr,
|
|
1063
|
+
cfg.amount,
|
|
1064
|
+
cfg.denoise,
|
|
1065
|
+
sigma,
|
|
1066
|
+
mode=mode,
|
|
1067
|
+
)
|
|
1068
|
+
)
|
|
1069
|
+
|
|
1070
|
+
# ---- 1) Detail layers ------------------------------------------
|
|
1071
|
+
for i, layer in enumerate(tuned):
|
|
1072
|
+
d = layer.astype(np.float32, copy=False)
|
|
1073
|
+
vis = np.clip(0.5 + d * 4.0, 0.0, 1.0).astype(np.float32, copy=False)
|
|
1074
|
+
|
|
1075
|
+
if self._orig_mono:
|
|
1076
|
+
mono = vis[..., 0]
|
|
1077
|
+
if len(self._orig_shape) == 3 and self._orig_shape[2] == 1:
|
|
1078
|
+
mono = mono[:, :, None]
|
|
1079
|
+
out_final = mono.astype(np.float32, copy=False)
|
|
1080
|
+
else:
|
|
1081
|
+
out_final = vis
|
|
1082
|
+
|
|
1083
|
+
title = f"Multiscale Detail Layer {i+1}"
|
|
1084
|
+
meta = self._build_new_doc_metadata(title, out_final)
|
|
1085
|
+
|
|
1086
|
+
try:
|
|
1087
|
+
dm.create_document(out_final, metadata=meta, name=title)
|
|
1088
|
+
except Exception as e:
|
|
1089
|
+
QMessageBox.critical(
|
|
1090
|
+
self,
|
|
1091
|
+
"Multiscale Decomposition",
|
|
1092
|
+
f"Failed to create document for layer {i+1}:\n{e}"
|
|
1093
|
+
)
|
|
1094
|
+
# Don’t bail entirely on first error if you’d rather continue;
|
|
1095
|
+
# right now we stop on first hard failure.
|
|
1096
|
+
return
|
|
1097
|
+
|
|
1098
|
+
# ---- 2) Residual layer -----------------------------------------
|
|
1099
|
+
try:
|
|
1100
|
+
res = residual.astype(np.float32, copy=False)
|
|
1101
|
+
res_img = np.clip(res, 0.0, 1.0)
|
|
1102
|
+
|
|
1103
|
+
if self._orig_mono:
|
|
1104
|
+
mono = res_img[..., 0]
|
|
1105
|
+
if len(self._orig_shape) == 3 and self._orig_shape[2] == 1:
|
|
1106
|
+
mono = mono[:, :, None]
|
|
1107
|
+
res_final = mono.astype(np.float32, copy=False)
|
|
1108
|
+
else:
|
|
1109
|
+
res_final = res_img
|
|
1110
|
+
|
|
1111
|
+
r_title = "Multiscale Residual Layer"
|
|
1112
|
+
r_meta = self._build_new_doc_metadata(r_title, res_final)
|
|
1113
|
+
|
|
1114
|
+
dm.create_document(res_final, metadata=r_meta, name=r_title)
|
|
1115
|
+
except Exception as e:
|
|
1116
|
+
QMessageBox.critical(
|
|
1117
|
+
self,
|
|
1118
|
+
"Multiscale Decomposition",
|
|
1119
|
+
f"Failed to create residual-layer document:\n{e}"
|
|
1120
|
+
)
|
|
1121
|
+
|
|
1122
|
+
|
|
1123
|
+
|
|
1124
|
+
def _get_doc_manager(self):
|
|
1125
|
+
"""
|
|
1126
|
+
Best-effort: find the DocManager that owns the source document.
|
|
1127
|
+
Prefer the doc's own _doc_manager; fall back to parent.doc_manager.
|
|
1128
|
+
"""
|
|
1129
|
+
doc = getattr(self, "_doc", None)
|
|
1130
|
+
dm = getattr(doc, "_doc_manager", None) if doc is not None else None
|
|
1131
|
+
|
|
1132
|
+
if dm is None:
|
|
1133
|
+
parent = self.parent()
|
|
1134
|
+
dm = getattr(parent, "doc_manager", None) if parent is not None else None
|
|
1135
|
+
|
|
1136
|
+
return dm
|
|
1137
|
+
|
|
1138
|
+
def _build_new_doc_metadata(self, title: str, img: np.ndarray) -> dict:
|
|
1139
|
+
"""
|
|
1140
|
+
Clone the source document's metadata and sanitize it for a brand-new doc.
|
|
1141
|
+
"""
|
|
1142
|
+
base_doc = getattr(self, "_doc", None)
|
|
1143
|
+
base_meta = getattr(base_doc, "metadata", {}) or {}
|
|
1144
|
+
meta = dict(base_meta)
|
|
1145
|
+
|
|
1146
|
+
# New display name
|
|
1147
|
+
if title:
|
|
1148
|
+
meta["display_name"] = title
|
|
1149
|
+
|
|
1150
|
+
# Drop things that make it look linked/preview/ROI
|
|
1151
|
+
imi = dict(meta.get("image_meta") or {})
|
|
1152
|
+
for k in ("readonly", "view_kind", "derived_from", "layer", "layer_index", "linked"):
|
|
1153
|
+
imi.pop(k, None)
|
|
1154
|
+
meta["image_meta"] = imi
|
|
1155
|
+
|
|
1156
|
+
# Remove any ROI-ish keys
|
|
1157
|
+
for k in list(meta.keys()):
|
|
1158
|
+
if k.startswith("_roi_") or k.endswith("_roi") or k == "roi":
|
|
1159
|
+
meta.pop(k, None)
|
|
1160
|
+
|
|
1161
|
+
# For a brand-new doc, don't keep the original file_path
|
|
1162
|
+
meta.pop("file_path", None)
|
|
1163
|
+
|
|
1164
|
+
# Normalize mono flag
|
|
1165
|
+
if isinstance(img, np.ndarray):
|
|
1166
|
+
meta["is_mono"] = (img.ndim == 2 or (img.ndim == 3 and img.shape[2] == 1))
|
|
1167
|
+
|
|
1168
|
+
# Keep bit depth / headers / WCS as-is; DocManager.open_array() will
|
|
1169
|
+
# ensure bit_depth etc. are sane.
|
|
1170
|
+
return meta
|
|
1171
|
+
|
|
1172
|
+
|
|
1173
|
+
|
|
1174
|
+
class _MultiScaleDecompPresetDialog(QDialog):
|
|
1175
|
+
"""
|
|
1176
|
+
Preset editor for Multiscale Decomposition (headless + shortcuts).
|
|
1177
|
+
"""
|
|
1178
|
+
def __init__(self, parent=None, initial: dict | None = None):
|
|
1179
|
+
super().__init__(parent)
|
|
1180
|
+
self.setWindowTitle("Multiscale Decomposition — Preset")
|
|
1181
|
+
init = dict(initial or {})
|
|
1182
|
+
|
|
1183
|
+
v = QVBoxLayout(self)
|
|
1184
|
+
|
|
1185
|
+
# ---- Global ----
|
|
1186
|
+
gb = QGroupBox("Global")
|
|
1187
|
+
form = QFormLayout(gb)
|
|
1188
|
+
|
|
1189
|
+
self.sp_layers = QSpinBox()
|
|
1190
|
+
self.sp_layers.setRange(1, 10)
|
|
1191
|
+
self.sp_layers.setValue(int(init.get("layers", 4)))
|
|
1192
|
+
|
|
1193
|
+
self.sp_sigma = QDoubleSpinBox()
|
|
1194
|
+
self.sp_sigma.setRange(0.3, 5.0)
|
|
1195
|
+
self.sp_sigma.setDecimals(2)
|
|
1196
|
+
self.sp_sigma.setSingleStep(0.1)
|
|
1197
|
+
self.sp_sigma.setValue(float(init.get("base_sigma", 1.0)))
|
|
1198
|
+
|
|
1199
|
+
self.cb_linked = QCheckBox("Linked RGB channels")
|
|
1200
|
+
self.cb_linked.setChecked(bool(init.get("linked_rgb", True)))
|
|
1201
|
+
|
|
1202
|
+
form.addRow("Layers:", self.sp_layers)
|
|
1203
|
+
form.addRow("Base sigma:", self.sp_sigma)
|
|
1204
|
+
form.addRow("", self.cb_linked)
|
|
1205
|
+
|
|
1206
|
+
v.addWidget(gb)
|
|
1207
|
+
|
|
1208
|
+
# ---- Layers ----
|
|
1209
|
+
gb_layers = QGroupBox("Per-Layer Settings")
|
|
1210
|
+
lv = QVBoxLayout(gb_layers)
|
|
1211
|
+
|
|
1212
|
+
self.table = QTableWidget(0, 6)
|
|
1213
|
+
self.table.setHorizontalHeaderLabels(
|
|
1214
|
+
["On", "Layer", "Gain", "Thr (σ)", "Amount", "Denoise"]
|
|
1215
|
+
)
|
|
1216
|
+
|
|
1217
|
+
self.table.verticalHeader().setVisible(False)
|
|
1218
|
+
lv.addWidget(self.table)
|
|
1219
|
+
|
|
1220
|
+
v.addWidget(gb_layers)
|
|
1221
|
+
|
|
1222
|
+
# ---- Buttons ----
|
|
1223
|
+
btns = QHBoxLayout()
|
|
1224
|
+
ok = QPushButton("OK")
|
|
1225
|
+
cancel = QPushButton("Cancel")
|
|
1226
|
+
btns.addStretch(1)
|
|
1227
|
+
btns.addWidget(ok)
|
|
1228
|
+
btns.addWidget(cancel)
|
|
1229
|
+
v.addLayout(btns)
|
|
1230
|
+
|
|
1231
|
+
ok.clicked.connect(self.accept)
|
|
1232
|
+
cancel.clicked.connect(self.reject)
|
|
1233
|
+
|
|
1234
|
+
self._populate_table(init)
|
|
1235
|
+
|
|
1236
|
+
def _populate_table(self, init: dict):
|
|
1237
|
+
layers = int(self.sp_layers.value())
|
|
1238
|
+
cfgs = init.get("layers_cfg", [])
|
|
1239
|
+
|
|
1240
|
+
self.table.setRowCount(layers)
|
|
1241
|
+
|
|
1242
|
+
for i in range(layers):
|
|
1243
|
+
cfg = cfgs[i] if i < len(cfgs) else {}
|
|
1244
|
+
|
|
1245
|
+
# Enabled
|
|
1246
|
+
chk = QTableWidgetItem("")
|
|
1247
|
+
chk.setFlags(chk.flags() | Qt.ItemFlag.ItemIsUserCheckable)
|
|
1248
|
+
chk.setCheckState(
|
|
1249
|
+
Qt.CheckState.Checked if cfg.get("enabled", True)
|
|
1250
|
+
else Qt.CheckState.Unchecked
|
|
1251
|
+
)
|
|
1252
|
+
self.table.setItem(i, 0, chk)
|
|
1253
|
+
|
|
1254
|
+
self.table.setItem(i, 1, QTableWidgetItem(str(i + 1)))
|
|
1255
|
+
self.table.setItem(i, 2, QTableWidgetItem(f"{float(cfg.get('gain', 1.0)):.2f}"))
|
|
1256
|
+
self.table.setItem(i, 3, QTableWidgetItem(f"{float(cfg.get('thr', 0.0)):.2f}")) # N·σ
|
|
1257
|
+
self.table.setItem(i, 4, QTableWidgetItem(f"{float(cfg.get('amount', 0.0)):.2f}"))
|
|
1258
|
+
self.table.setItem(i, 5, QTableWidgetItem(f"{float(cfg.get('denoise',0.0)):.2f}"))
|
|
1259
|
+
|
|
1260
|
+
|
|
1261
|
+
|
|
1262
|
+
def result_dict(self) -> dict:
|
|
1263
|
+
layers = int(self.sp_layers.value())
|
|
1264
|
+
out_layers = []
|
|
1265
|
+
|
|
1266
|
+
for r in range(layers):
|
|
1267
|
+
enabled = self.table.item(r, 0).checkState() == Qt.CheckState.Checked
|
|
1268
|
+
gain = float(self.table.item(r, 2).text())
|
|
1269
|
+
thr = float(self.table.item(r, 3).text())
|
|
1270
|
+
amt = float(self.table.item(r, 4).text())
|
|
1271
|
+
try:
|
|
1272
|
+
dn = float(self.table.item(r, 5).text())
|
|
1273
|
+
except Exception:
|
|
1274
|
+
dn = 0.0
|
|
1275
|
+
|
|
1276
|
+
out_layers.append({
|
|
1277
|
+
"enabled": enabled,
|
|
1278
|
+
"gain": gain,
|
|
1279
|
+
"thr": thr,
|
|
1280
|
+
"amount": amt,
|
|
1281
|
+
"denoise": dn,
|
|
1282
|
+
})
|
|
1283
|
+
|
|
1284
|
+
|
|
1285
|
+
return {
|
|
1286
|
+
"layers": layers,
|
|
1287
|
+
"base_sigma": float(self.sp_sigma.value()),
|
|
1288
|
+
"linked_rgb": bool(self.cb_linked.isChecked()),
|
|
1289
|
+
"layers_cfg": out_layers,
|
|
1290
|
+
}
|