fspi-analysis 0.2.2__tar.gz → 0.2.3__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fspi_analysis
3
- Version: 0.2.2
3
+ Version: 0.2.3
4
4
  Summary: A simple plugin to perform fspi analysis within napari
5
5
  Author: Olivier Cahn
6
6
  Author-email: oc124@ic.ac.uk
@@ -1,4 +1,4 @@
1
- __version__ = "0.2.2"
1
+ __version__ = "0.2.3"
2
2
 
3
3
  # src/fspi_analysis/__init__.py
4
4
 
@@ -1,6 +1,6 @@
1
1
  import napari
2
2
  import numpy as np
3
- from skimage import data, io, filters, color, util
3
+ from skimage import data, io, filters, color, util, transform
4
4
  from magicgui.widgets import PushButton, Container, FloatSlider, IntSlider, Label, FloatSpinBox, ComboBox, FileEdit
5
5
  import pathlib
6
6
  from qtpy.QtWidgets import QMessageBox
@@ -16,7 +16,132 @@ from matplotlib.colors import Normalize
16
16
  from vispy.color import Colormap
17
17
  from dask import delayed
18
18
 
19
+ _WORK_SIZE = 1000
20
+
21
+
22
+ def _to_gray_float(image_2d):
23
+ img = np.asarray(image_2d)
24
+ if img.ndim == 3 and img.shape[-1] in (3, 4):
25
+ img = color.rgb2gray(util.img_as_float(img[..., :3]))
26
+ else:
27
+ img = util.img_as_float(img).astype(float)
28
+ # Stretch to 0-1 so the parameters behave the same for 8 and 16 bit data
29
+ lo, hi = np.percentile(img, (0.5, 99.5))
30
+ if hi > lo:
31
+ img = np.clip((img - lo) / (hi - lo), 0, 1)
32
+ return img
33
+
34
+
35
+ def _best_path(energy, max_step):
36
+ """Column-by-column path through `energy` maximising the summed energy,
37
+ moving at most `max_step` rows between neighbouring columns."""
38
+ h, w = energy.shape
39
+ acc = np.empty_like(energy)
40
+ back = np.empty((h, w), dtype=np.int64)
41
+ acc[:, 0] = energy[:, 0]
42
+ rows = np.arange(h)
43
+ offsets = np.arange(-max_step, max_step + 1)
44
+ for x in range(1, w):
45
+ prev = acc[:, x - 1]
46
+ # candidates[k, y] = prev[y + offsets[k]] (out of range -> -inf)
47
+ idx = rows[None, :] + offsets[:, None]
48
+ valid = (idx >= 0) & (idx < h)
49
+ cand = np.where(valid, prev[np.clip(idx, 0, h - 1)], -np.inf)
50
+ k = np.argmax(cand, axis=0)
51
+ back[:, x] = rows + offsets[k]
52
+ acc[:, x] = energy[:, x] + cand[k, rows]
53
+ path = np.empty(w, dtype=np.int64)
54
+ path[-1] = int(np.argmax(acc[:, -1]))
55
+ for x in range(w - 1, 0, -1):
56
+ path[x - 1] = back[path[x], x]
57
+ return path, float(acc[path[-1], -1])
58
+
59
+
60
+ def estimate_surface_boundary(image_2d, n_nodes=25, polarity="auto",
61
+ smoothing=2.0, max_slope=1.0, margin=0.02,
62
+ return_debug=False):
63
+ """Estimate the water/sediment surface as an equally spaced polyline.
64
+
65
+ Parameters
66
+ ----------
67
+ image_2d : array (H, W) or (H, W, 3/4)
68
+ One image (a single slice for stacks). Water should be at the top.
69
+ n_nodes : int
70
+ Number of polyline nodes, equally spaced across the full width
71
+ (first node at column 0, last at column W-1).
72
+ polarity : {"auto", "dark_above", "bright_above"}
73
+ Whether the water is darker or brighter than the sediment.
74
+ smoothing : float
75
+ Gaussian sigma, in work-image pixels, applied before the Scharr filter.
76
+ max_slope : float
77
+ Largest vertical move per column allowed for the traced line
78
+ (in work-image pixels per pixel, i.e. 1.0 = 45 degrees).
79
+ margin : float
80
+ Fraction of the height ignored at the very top and bottom, so the
81
+ frame edges of the photo are never picked.
82
+
83
+ Returns
84
+ -------
85
+ nodes : ndarray (n_nodes, 2)
86
+ (row, col) coordinates in full-resolution pixels, ready to be used as
87
+ a napari 'path' shape.
88
+ """
89
+ n_nodes = int(max(2, n_nodes))
90
+ gray = _to_gray_float(image_2d)
91
+ H, W = gray.shape
92
+
93
+ scale = min(1.0, _WORK_SIZE / max(H, W))
94
+ work = transform.rescale(gray, scale, anti_aliasing=True) if scale < 1 else gray
95
+ h, w = work.shape
96
+
97
+ work = filters.gaussian(work, sigma=smoothing)
98
+ # scharr_h: horizontal edges; positive where intensity increases downwards
99
+ grad = filters.scharr_h(work)
100
+ m = max(1, int(round(margin * h)))
101
+ grad[:m] = 0
102
+ grad[-m:] = 0
103
+
104
+ candidates = []
105
+ if polarity in ("auto", "dark_above"):
106
+ candidates.append(("dark_above", np.clip(grad, 0, None)))
107
+ if polarity in ("auto", "bright_above"):
108
+ candidates.append(("bright_above", np.clip(-grad, 0, None)))
109
+
110
+ max_step = max(1, int(round(max_slope)))
111
+ best = None
112
+ for name, energy in candidates:
113
+ norm = np.percentile(energy, 99.9)
114
+ if norm > 0:
115
+ energy = np.clip(energy / norm, 0, 1)
116
+ path, score = _best_path(energy, max_step)
117
+ if best is None or score > best[1]:
118
+ best = (path, score, name)
119
+ path_work, _, chosen = best
120
+
121
+ # Back to full-resolution coordinates
122
+ path_cols = (np.arange(w) + 0.5) / scale - 0.5
123
+ path_rows = (path_work + 0.5) / scale - 0.5
124
+
125
+ node_cols = np.linspace(0, W - 1, n_nodes)
126
+ half = (W - 1) / (n_nodes - 1) / 2.0
127
+ node_rows = np.empty(n_nodes)
128
+ for i, c in enumerate(node_cols):
129
+ sel = np.abs(path_cols - c) <= half
130
+ if not np.any(sel):
131
+ sel = np.argmin(np.abs(path_cols - c))
132
+ node_rows[i] = np.median(path_rows[sel])
133
+ node_rows = np.clip(node_rows, 0, H - 1)
134
+
135
+ nodes = np.column_stack([node_rows, node_cols])
136
+ if return_debug:
137
+ return nodes, {"path_rows": path_rows, "path_cols": path_cols,
138
+ "polarity": chosen}
139
+ return nodes
140
+
141
+
19
142
  class ImageAnalysisApp:
143
+ AUTO_BOUNDARY_EDGE_WIDTH = 10 # line width of the auto-estimated surface path
144
+
20
145
  def __init__(self, viewer):
21
146
  self.viewer = viewer
22
147
 
@@ -38,12 +163,16 @@ class ImageAnalysisApp:
38
163
 
39
164
  # --- Mode Selectors ---
40
165
  self.mode_selector = ComboBox(choices=["Single Image", "Image Stack", "Single Image (RGB)", "Image Stack (RGB)"], label="Mode:")
41
- self.spi_mode_selector = ComboBox(choices=["fSPI", "tSPI"], label="SPI Mode:")
166
+ self.spi_mode_selector = ComboBox(choices=["fSPI", "SPI"], label="SPI Mode:")
42
167
 
43
168
  # Explicit Load Buttons
44
169
  self.load_image_path = FileEdit(label="Choose File:", mode="r")
45
170
  self.load_image_btn = PushButton(text="Load Selected Image")
46
171
 
172
+ # Automatic surface boundary guess (separate from alignment preview)
173
+ self.boundary_nodes_widget = IntSlider(value=25, min=5, max=100, label="Boundary Nodes:")
174
+ self.estimate_boundary_button = PushButton(text="Auto-Estimate Surface Boundary")
175
+
47
176
  # Alignment & Path controls
48
177
  self.save_contour_button = PushButton(text="Confirm Contour for Current Slice")
49
178
  self.save_contour_button.visible = False # Only for stack mode
@@ -85,6 +214,7 @@ class ImageAnalysisApp:
85
214
  self.control_container = Container(widgets=[
86
215
  self.mode_selector, self.spi_mode_selector, self.load_image_path, self.load_image_btn,
87
216
  Label(value="--- Alignment & Contours ---"),
217
+ self.boundary_nodes_widget, self.estimate_boundary_button,
88
218
  self.save_contour_button, self.align_button, self.clear_paths_button,
89
219
  self.load_ann_path, self.load_ann_btn, self.save_ann_button,
90
220
  Label(value="--- Custom Depth ---"),
@@ -102,6 +232,7 @@ class ImageAnalysisApp:
102
232
  def connect_events(self):
103
233
  self.mode_selector.changed.connect(self.on_mode_change)
104
234
  self.load_image_btn.clicked.connect(self.load_new_image)
235
+ self.estimate_boundary_button.clicked.connect(self.estimate_boundary)
105
236
  self.save_contour_button.clicked.connect(self.save_contour_for_slice)
106
237
  self.align_button.clicked.connect(self.manual_align_trigger)
107
238
  self.clear_paths_button.clicked.connect(self.clear_paths)
@@ -227,6 +358,44 @@ class ImageAnalysisApp:
227
358
  else: break
228
359
  return self.saved_paths[best_z]
229
360
 
361
+ def estimate_boundary(self):
362
+ """Put an automatic first guess of the water/sediment surface on the
363
+ 'alignment_path' layer as an equally spaced, editable polyline.
364
+ It only replaces the drawn path; nothing is aligned or saved."""
365
+ if 'original_image' not in self.viewer.layers or 'alignment_path' not in self.viewer.layers:
366
+ self.status_label.value = "Load an image first."
367
+ return
368
+ try:
369
+ self.status_label.value = "Estimating surface boundary..."
370
+ data = self.viewer.layers['original_image'].data
371
+ is_stack = "Stack" in self.mode
372
+ is_rgb_layer = getattr(self.viewer.layers['original_image'], 'rgb', False)
373
+ if is_stack and data.ndim >= (4 if is_rgb_layer else 3):
374
+ z_val = self.viewer.dims.current_step[0]
375
+ image_2d = np.asarray(data[z_val])
376
+ else:
377
+ image_2d = np.asarray(data)
378
+
379
+ nodes = estimate_surface_boundary(image_2d, n_nodes=self.boundary_nodes_widget.value)
380
+
381
+ shapes_layer = self.viewer.layers['alignment_path']
382
+ original_mode = shapes_layer.mode
383
+ shapes_layer.mode = 'pan_zoom'
384
+ shapes_layer.data = [nodes]
385
+ shapes_layer.shape_type = ['path']
386
+ # Thicker default line for the generated path (also kept when the
387
+ # path is redrawn on slice changes in stack mode)
388
+ shapes_layer.current_edge_width = self.AUTO_BOUNDARY_EDGE_WIDTH
389
+ shapes_layer.edge_width = [self.AUTO_BOUNDARY_EDGE_WIDTH]
390
+ shapes_layer.mode = original_mode
391
+
392
+ msg = f"Boundary estimated ({len(nodes)} nodes). Adjust nodes if needed"
393
+ msg += ", then Confirm Contour for this slice." if is_stack else ", then Preview Alignment."
394
+ self.status_label.value = msg
395
+ except Exception as e:
396
+ self.status_label.value = f"Boundary estimation error: {e}"
397
+ traceback.print_exc()
398
+
230
399
  def save_contour_for_slice(self):
231
400
  try:
232
401
  shapes_layer = self.viewer.layers['alignment_path']
@@ -608,7 +777,7 @@ class ImageAnalysisApp:
608
777
 
609
778
  # Dynamic Column Naming
610
779
  spi_mode = self.spi_mode_selector.value
611
- al_suffix = "_aL" if spi_mode == "tSPI" else ""
780
+ al_suffix = "_aL" if spi_mode == "SPI" else ""
612
781
 
613
782
  p_diff = getattr(self, 'single_path_y_diff', None)
614
783
  path_diff_scaled = p_diff * pixel_size_cm if p_diff is not None else np.nan
@@ -752,7 +921,7 @@ class ImageAnalysisApp:
752
921
 
753
922
  # Determine Mode and Suffix for dynamic column naming
754
923
  spi_mode = self.spi_mode_selector.value
755
- al_suffix = "_aL" if spi_mode == "tSPI" else ""
924
+ al_suffix = "_aL" if spi_mode == "SPI" else ""
756
925
 
757
926
  pixel_size_cm = self.real_core_size_widget.value / self.core_width_px_widget.value
758
927
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fspi_analysis
3
- Version: 0.2.2
3
+ Version: 0.2.3
4
4
  Summary: A simple plugin to perform fspi analysis within napari
5
5
  Author: Olivier Cahn
6
6
  Author-email: oc124@ic.ac.uk
File without changes
File without changes
File without changes
File without changes