miblab-plot 0.0.12__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.12
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.12"
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
@@ -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)
@@ -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.12
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