miblab-plot 0.0.11__tar.gz → 0.0.13__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: miblab-plot
3
- Version: 0.0.11
3
+ Version: 0.0.13
4
4
  Summary: Plotting utilities for medical images
5
5
  Author-email: Steven Sourbron <s.sourbron@sheffield.ac.uk>
6
6
  License-Expression: Apache-2.0
@@ -6,7 +6,7 @@ requires = ['setuptools>=61.2']
6
6
 
7
7
  [project]
8
8
  name = "miblab-plot"
9
- version = "0.0.11"
9
+ version = "0.0.13"
10
10
  dependencies = [
11
11
  "numpy",
12
12
  "matplotlib",
@@ -4,4 +4,8 @@ from .image_3d import (
4
4
  mosaic_checkerboard,
5
5
  db_mosaic,
6
6
  )
7
+ from .pvplot import (
8
+ rotating_mosaics_da
9
+ )
10
+
7
11
  from . import mp4, pvplot, gui
@@ -24,7 +24,7 @@ def db_mosaic(series_to_display, pngfile, title="Center slices"):
24
24
  aspect_ratio = 16/9
25
25
  nrows = int(np.ceil(np.sqrt(n_imgs / aspect_ratio)))
26
26
  ncols = int(np.ceil(aspect_ratio * nrows))
27
- fig, ax = plt.subplots(nrows=nrows, ncols=ncols, gridspec_kw = {'wspace':0, 'hspace':0}, figsize=(ncols, nrows), dpi=300)
27
+ fig, ax = plt.subplots(nrows=nrows, ncols=ncols, squeeze=False, gridspec_kw = {'wspace':0, 'hspace':0}, figsize=(ncols, nrows), dpi=300)
28
28
 
29
29
  i=0
30
30
  for row in tqdm(ax, desc='Building png'):
@@ -74,6 +74,13 @@ def get_distinct_colors(rois, colormap='jet', opacity=0.6):
74
74
  colors = [[1, 0, 0, opacity], [0, 1, 0, opacity]]
75
75
  elif len(rois)==3:
76
76
  colors = [[1, 0, 0, opacity], [0, 1, 0, opacity], [0, 0, 1, opacity]]
77
+ elif len(rois) == 4:
78
+ colors = [
79
+ [1.0, 0.0, 0.0, opacity], # red
80
+ [0.0, 1.0, 0.0, opacity], # green
81
+ [0.0, 0.4, 1.0, opacity], # blue (slightly lightened so it reads on dark grey)
82
+ [1.0, 0.9, 0.0, opacity], # yellow
83
+ ]
77
84
  else:
78
85
  n = len(rois)
79
86
  #cmap = cm.get_cmap(colormap, n)
@@ -211,19 +218,42 @@ def checkerboard(fixed: np.ndarray, coreg: np.ndarray, square_size: int) -> np.n
211
218
 
212
219
  return checker
213
220
 
214
-
221
+ def _label_to_binary_masks(label_image, background_value=0):
222
+ """
223
+ Converts a label image into a list of binary masks.
224
+
225
+ Parameters:
226
+ - label_image (np.ndarray): 2D array of labels.
227
+ - background_value (int): Value representing the background to ignore.
228
+
229
+ Returns:
230
+ - dict: A dict of label: 2D binary mask pairs.
231
+ """
232
+ # Find all unique labels excluding the background
233
+ unique_labels = np.unique(label_image)
234
+ unique_labels = unique_labels[unique_labels != background_value]
235
+
236
+ masks = {}
237
+ for label in unique_labels:
238
+ # Create a binary mask for the current label
239
+ mask = (label_image == label).astype(bool)
240
+ masks[label] = mask
241
+
242
+ return masks
215
243
 
216
244
  def mosaic_overlay(
217
- img,
218
- rois,
219
- file,
245
+ img: np.ndarray, # background greyscale image
246
+ rois: dict | np.ndarray, # Dictionary with masks or label image
247
+ file: str=None,
220
248
  colormap='tab20',
221
249
  aspect_ratio=1.8,
222
250
  margin=None,
223
251
  vmin=None,
224
252
  vmax=None,
225
253
  opacity=0.6,
226
- colors=None
254
+ colors=None,
255
+ show=False,
256
+ verbose=1,
227
257
  ):
228
258
 
229
259
  # Set defaults color window
@@ -232,6 +262,12 @@ def mosaic_overlay(
232
262
  if vmax is None:
233
263
  vmax=np.mean(img) + 2 * np.std(img)
234
264
 
265
+ # Convert label image to dictionary of masks
266
+ if not isinstance(rois, dict):
267
+ rois = _label_to_binary_masks(rois, background_value=0)
268
+ if rois == {}:
269
+ raise ValueError("Empty label image: nothing to overlay here..")
270
+
235
271
  # Define RGBA colors (R, G, B, Alpha) — alpha controls transparency
236
272
  if colors is None:
237
273
  colors = get_distinct_colors(rois, colormap=colormap, opacity=opacity)
@@ -244,7 +280,7 @@ def mosaic_overlay(
244
280
  for i in range(1, len(masks)):
245
281
  all_masks = np.logical_or(all_masks, masks[i])
246
282
  if np.sum(all_masks)==0:
247
- raise ValueError('Empty masks')
283
+ raise ValueError('Empty masks: nothing to overlay here.')
248
284
 
249
285
  # Find corners of cropped mask
250
286
  for x0 in range(all_masks.shape[0]):
@@ -303,7 +339,7 @@ def mosaic_overlay(
303
339
 
304
340
  # Build figure
305
341
  i = 0
306
- for row in tqdm(ax, desc='Building png'):
342
+ for row in tqdm(ax, desc='Building png', disable=verbose==0):
307
343
  for col in row:
308
344
 
309
345
  col.set_xticklabels([])
@@ -332,8 +368,14 @@ def mosaic_overlay(
332
368
  i += 1
333
369
 
334
370
  # fig.suptitle('Mask overlay', fontsize=14)
335
- fig.savefig(file, bbox_inches='tight', pad_inches=0)
336
- plt.close()
371
+ if file is None:
372
+ plt.show()
373
+ else:
374
+ fig.savefig(file, bbox_inches='tight', pad_inches=0)
375
+ if show:
376
+ plt.show()
377
+ else:
378
+ plt.close(fig)
337
379
 
338
380
 
339
381
 
@@ -3,6 +3,7 @@ from typing import Union
3
3
  import platform
4
4
 
5
5
  import numpy as np
6
+ from scipy.ndimage import gaussian_filter
6
7
  from tqdm import tqdm
7
8
  import pyvista as pv
8
9
  import dbdicom as db
@@ -29,6 +30,135 @@ def setup_rendering_env():
29
30
  setup_rendering_env()
30
31
 
31
32
 
33
+
34
+ def _make_surface(mask, spacing=(1.0, 1.0, 1.0), gauss=1.0, smooth_iter=20):
35
+ """Maak een glad oppervlak van een binair masker.
36
+
37
+ gauss : sigma (in voxels) van de Gaussian op het volume (0 = uit)
38
+ smooth_iter : aantal Taubin-iteraties op het oppervlak (0 = uit)
39
+ """
40
+ mask = mask.astype(np.float32)
41
+
42
+ # 1 voxel padding zodat oppervlakken aan de rand van het beeld gesloten zijn
43
+ mask = np.pad(mask, 1)
44
+
45
+ if gauss > 0 and mask.any():
46
+ mask = gaussian_filter(mask, sigma=gauss)
47
+
48
+ vol = pv.wrap(mask)
49
+ vol.spacing = list(spacing)
50
+ vol.origin = tuple(-s for s in spacing) # compenseert de padding
51
+ surf = vol.contour(isosurfaces=[0.5])
52
+
53
+ if smooth_iter > 0 and surf.n_points > 0:
54
+ surf = surf.smooth_taubin(n_iter=smooth_iter, pass_band=0.1)
55
+ return surf
56
+
57
+
58
+ def rotating_mosaics_da(dir_output, masks: list, labels=None, chunksize=None, nviews=25,
59
+ columns=None, rows=None, colors=None, gauss=1.0, smooth_iter=20):
60
+ # masks - list of numpy, zarr or dask arrays (or lazy objects supporting [:])
61
+ # colors - optional list of colors (one per mask); default is 'lightblue' for all
62
+ # gauss - sigma (voxels) of Gaussian smoothing on the volume (0 = off)
63
+ # smooth_iter - Taubin smoothing iterations on the surface (0 = off)
64
+ if labels is None:
65
+ labels = [str(i) for i in range(len(masks))]
66
+ if chunksize is None:
67
+ chunksize = len(masks)
68
+ os.makedirs(dir_output, exist_ok=True)
69
+
70
+ # Split into numbered chunks
71
+ def chunk_list(lst, size):
72
+ chunks = [lst[i:i+size] for i in range(0, len(lst), size)]
73
+ return list(enumerate(chunks))
74
+
75
+ mask_chunks = chunk_list(masks, chunksize)
76
+ label_chunks = chunk_list(labels, chunksize)
77
+ color_chunks = chunk_list(colors, chunksize) if colors is not None else [(i, None) for i, _ in mask_chunks]
78
+
79
+ # Define view points
80
+ angles = np.linspace(0, 2*np.pi, nviews)
81
+ dirs = [(np.cos(a), np.sin(a), 0.0) for a in angles] # rotate around z
82
+ dirs += [(np.cos(a), 0.0, np.sin(a)) for a in angles] # rotate around y
83
+
84
+ # Save mosaics for each chunk and view
85
+ for mask_chunk, label_chunk, color_chunk in tqdm(
86
+ zip(mask_chunks, label_chunks, color_chunks),
87
+ total=len(label_chunks),
88
+ desc='Building chunk of mosaics',
89
+ ):
90
+ chunk_idx = mask_chunk[0]
91
+ names = [f"group_{str(chunk_idx).zfill(2)}_{i:02d}.png" for i in range(len(dirs))]
92
+ directions = {vec: os.path.join(dir_output, name) for name, vec in zip(names, dirs)}
93
+ multiple_mosaic_masks_da(
94
+ mask_chunk[1], directions, label_chunk[1],
95
+ columns=columns, rows=rows, colors=color_chunk[1],
96
+ gauss=gauss, smooth_iter=smooth_iter,
97
+ )
98
+
99
+
100
+ def multiple_mosaic_masks_da(masks: list, directions: dict, labels, columns=None, rows=None,
101
+ colors=None, gauss=1.0, smooth_iter=20):
102
+ # Plot settings
103
+ width, height = 150, 150
104
+ aspect_ratio = 16/9
105
+
106
+ n_mosaics = len(masks)
107
+ ncols = columns if columns else int(np.ceil(np.sqrt((height*n_mosaics)/(aspect_ratio*width))))
108
+ nrows = rows if rows else int(np.ceil(n_mosaics/ncols))
109
+
110
+ # Surfaces één keer berekenen; daarna per kijkhoek renderen (1 plotter tegelijk in RAM)
111
+ surfaces = []
112
+ for mask_series in tqdm(masks, desc="Pre-calculating Surfaces"):
113
+ mask_norm = mask_series[:].astype(bool)
114
+ spacing = getattr(mask_series, 'spacing', (1.0, 1.0, 1.0))
115
+ surfaces.append(_make_surface(mask_norm, spacing, gauss, smooth_iter))
116
+ del mask_norm
117
+
118
+ # Now render each view angle
119
+ for vec, file_path in tqdm(directions.items(), desc="Rendering Views"):
120
+ plotter = pv.Plotter(
121
+ window_size=(ncols*width, nrows*height),
122
+ shape=(nrows, ncols),
123
+ border=False,
124
+ off_screen=pv.OFF_SCREEN,
125
+ )
126
+ plotter.background_color = 'white'
127
+
128
+ for i, surf in enumerate(surfaces):
129
+ row, col = divmod(i, ncols)
130
+ if row >= nrows:
131
+ break # Safety break
132
+
133
+ # A simple up vector (0,0,1) is usually more stable across views
134
+ up = (0, 0, 1)
135
+
136
+ plotter.subplot(row, col)
137
+ if labels is not None:
138
+ plotter.add_text(labels[i], font_size=6, color='black')
139
+
140
+ # Catch empty masks
141
+ if surf.n_points > 0:
142
+ distance = surf.length * 2.5
143
+ center = list(surf.center)
144
+ pos = center + distance * np.array(vec)
145
+
146
+ color = colors[i] if colors is not None else 'lightblue'
147
+ plotter.add_mesh(surf, color=color, smooth_shading=True)
148
+ plotter.camera_position = [pos, center, up]
149
+ else:
150
+ plotter.add_text("Empty Mask", font_size=5, color='gray')
151
+
152
+ # 1. Initialize the window in the background
153
+ plotter.show(auto_close=False, interactive=False, interactive_update=True)
154
+
155
+ # 2. Capture the pixels
156
+ plotter.screenshot(file_path)
157
+
158
+ # 3. Destroy the plotter immediately
159
+ plotter.close()
160
+
161
+
32
162
  def mosaic_masks_dcm(masks, imagefile, labels=None, view_vector=(1, 0, 0)):
33
163
 
34
164
  # Plot settings
@@ -154,112 +284,6 @@ def rotating_masks_grid(
154
284
  plotter.close() # CRITICAL: Releases the GPU and RAM buffers
155
285
  del plotter
156
286
 
157
-
158
-
159
-
160
- def rotating_mosaics_da(dir_output, masks:list, labels=None, chunksize=None, nviews=25, columns=None, rows=None):
161
- # masks - list of numpy or dask arrays
162
- if labels is None:
163
- labels = [str(i) for i in range(len(masks))]
164
- if chunksize is None:
165
- chunksize = len(masks)
166
- os.makedirs(dir_output, exist_ok=True)
167
-
168
- # Split into numbered chunks
169
- def chunk_list(lst, size):
170
- chunks = [lst[i:i+size] for i in range(0, len(lst), size)]
171
- return list(enumerate(chunks))
172
-
173
- mask_chunks = chunk_list(masks, chunksize)
174
- label_chunks = chunk_list(labels, chunksize)
175
-
176
- # Define view points
177
- angles = np.linspace(0, 2*np.pi, nviews)
178
- dirs = [(np.cos(a), np.sin(a), 0.0) for a in angles] # rotate around z
179
- dirs += [(np.cos(a), 0.0, np.sin(a)) for a in angles] # rotate around y
180
-
181
- # Save mosaics for each chunk and view
182
- for mask_chunk, label_chunk in tqdm(zip(mask_chunks, label_chunks), total=len(label_chunks), desc='Building chunk of mosaics'):
183
- chunk_idx = mask_chunk[0]
184
- names = [f"group_{str(chunk_idx).zfill(2)}_{i:02d}.png" for i in range(len(dirs))]
185
- directions = {vec: os.path.join(dir_output, name) for name, vec in zip(names, dirs)}
186
- multiple_mosaic_masks_da(mask_chunk[1], directions, label_chunk[1], columns=columns, rows=rows)
187
-
188
- def multiple_mosaic_masks_da(masks: list, directions: dict, labels, columns=None, rows=None):
189
- # Plot settings
190
- width, height = 150, 150
191
- aspect_ratio = 16/9
192
-
193
- n_mosaics = len(masks)
194
- ncols = columns if columns else int(np.ceil(np.sqrt((height*n_mosaics)/(aspect_ratio*width))))
195
- nrows = rows if rows else int(np.ceil(n_mosaics/ncols))
196
-
197
- # We loop through DIRECTIONS first. This keeps only ONE plotter in RAM at a time.
198
- # To avoid re-computing the Spline/RBF surface 50 times per mask,
199
- # we pre-calculate the surfaces once.
200
-
201
- surfaces = []
202
- for mask_series in tqdm(masks, desc="Pre-calculating Surfaces"):
203
-
204
- mask_norm = mask_series[:].astype(bool)
205
-
206
- vol = pv.wrap(mask_norm.astype(np.float32))
207
- vol.spacing = [1.0, 1.0, 1.0]
208
- surf = vol.contour(isosurfaces=[0.5])
209
- surfaces.append(surf)
210
- del vol # Clear RAM
211
-
212
- # Now render each view angle
213
- for vec, file_path in tqdm(directions.items(), desc="Rendering Views"):
214
- plotter = pv.Plotter(
215
- window_size=(ncols*width, nrows*height),
216
- shape=(nrows, ncols),
217
- border=False,
218
- off_screen=pv.OFF_SCREEN,
219
- )
220
- plotter.background_color = 'white'
221
-
222
- for i, surf in enumerate(surfaces):
223
- row, col = divmod(i, ncols)
224
- if row >= nrows: break # Safety break
225
-
226
- # Camera Position
227
- distance = surf.length * 2.0
228
- center = list(surf.center)
229
- pos = center + distance * np.array(vec)
230
-
231
- # Using a simple up vector (0,0,1) is usually more stable across views
232
- # unless you have a specific requirement for the _camera_up_from_direction
233
- up = (0, 0, 1)
234
-
235
- plotter.subplot(row, col)
236
- if labels is not None:
237
- plotter.add_text(labels[i], font_size=6, color='black')
238
-
239
- # Catch empty masks
240
- if surf.n_points > 0:
241
- # Only calculate camera and add mesh if points exist
242
- distance = surf.length * 2.5
243
- center = list(surf.center)
244
- pos = center + distance * np.array(vec)
245
-
246
- plotter.add_mesh(surf, color='lightblue', smooth_shading=True)
247
- plotter.camera_position = [pos, center, up]
248
- else:
249
- # Optional: Add placeholder text so you know it was empty
250
- plotter.add_text("Empty Mask", font_size=5, color='gray')
251
-
252
- # 1. Initialize the window in the background
253
- plotter.show(auto_close=False, interactive=False, interactive_update=True)
254
-
255
- # 2. Capture the pixels
256
- plotter.screenshot(file_path)
257
-
258
- # 3. Destroy the plotter immediately
259
- plotter.close()
260
-
261
-
262
-
263
287
  def rotating_mosaics_npz(dir_output, masks:list, labels=None, chunksize=None, nviews=25, columns=None, rows=None):
264
288
 
265
289
  if labels is None:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: miblab-plot
3
- Version: 0.0.11
3
+ Version: 0.0.13
4
4
  Summary: Plotting utilities for medical images
5
5
  Author-email: Steven Sourbron <s.sourbron@sheffield.ac.uk>
6
6
  License-Expression: Apache-2.0
File without changes
File without changes
File without changes