miblab-plot 0.0.4__tar.gz → 0.0.6__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.4
3
+ Version: 0.0.6
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.4"
9
+ version = "0.0.6"
10
10
  dependencies = [
11
11
  'pillow',
12
12
  'numpy',
@@ -420,7 +420,7 @@ def display_two_kidneys(kidney1, kidney2,
420
420
  centroid_1, axes_1 = compute_principal_axes(kidney1, kidney1_voxel_size)
421
421
  centroid_2, axes_2 = compute_principal_axes(kidney2, kidney2_voxel_size)
422
422
 
423
- plotter = pv.Plotter(window_size=(1000,600), shape=(1,2))
423
+ plotter = pv.Plotter(window_size=(1000,600), shape=(1,2), off_screen=False)
424
424
  plotter.background_color = 'white'
425
425
 
426
426
  # Original
@@ -1,6 +1,6 @@
1
1
  import os
2
- from pathlib import Path
3
2
  from typing import Union
3
+ import platform
4
4
 
5
5
  import numpy as np
6
6
  from tqdm import tqdm
@@ -11,6 +11,30 @@ import zarr
11
11
  import miblab_ssa as ssa
12
12
 
13
13
 
14
+ def setup_rendering_env():
15
+
16
+ # Default is no interactive rendering
17
+ pv.OFF_SCREEN = True
18
+
19
+ current_os = platform.system().lower()
20
+ if current_os == "linux":
21
+
22
+ # 1. Prefer OSMesa for headless Linux (avoids the Xvfb requirement)
23
+ # This tells PyVista to use the software-based buffer provided by the Mesa module
24
+ if hasattr(pv, 'set_jupyter_backend'):
25
+ pv.set_jupyter_backend('static')
26
+
27
+ # 2. Environment variables to bypass X11 requirements
28
+ os.environ['QT_QPA_PLATFORM'] = 'offscreen'
29
+ os.environ['PYVISTA_OFF_SCREEN'] = 'true'
30
+
31
+ print("Linux Cluster: OSMesa/Software rendering enabled.")
32
+
33
+
34
+
35
+ setup_rendering_env()
36
+
37
+
14
38
  def mosaic_masks_dcm(masks, imagefile, labels=None, view_vector=(1, 0, 0)):
15
39
 
16
40
  # Plot settings
@@ -23,7 +47,13 @@ def mosaic_masks_dcm(masks, imagefile, labels=None, view_vector=(1, 0, 0)):
23
47
  nrows = int(np.ceil(np.sqrt((width*n_mosaics)/(aspect_ratio*height))))
24
48
  ncols = int(np.ceil(n_mosaics/nrows))
25
49
 
26
- plotter = pv.Plotter(window_size=(ncols*width, nrows*height), shape=(nrows, ncols), border=False, off_screen=True)
50
+ plotter = pv.Plotter(
51
+ window_size=(ncols*width, nrows*height),
52
+ shape=(nrows, ncols),
53
+ border=False,
54
+ # off_screen=True,
55
+ off_screen=pv.OFF_SCREEN,
56
+ )
27
57
  plotter.background_color = 'white'
28
58
 
29
59
  row = 0
@@ -80,7 +110,8 @@ def rotating_masks_grid(
80
110
  window_size=(ncols*width, nrows*height),
81
111
  shape=(nrows, ncols),
82
112
  border=False,
83
- off_screen=True,
113
+ # off_screen=True,
114
+ off_screen=pv.OFF_SCREEN,
84
115
  )
85
116
  plotter.background_color = 'white'
86
117
 
@@ -119,68 +150,6 @@ def rotating_masks_grid(
119
150
  plotter.close() # CRITICAL: Releases the GPU and RAM buffers
120
151
  del plotter
121
152
 
122
- # def rotating_masks_grid(
123
- # dir_output:str,
124
- # masks:Union[zarr.Array, np.ndarray],
125
- # labels:np.ndarray=None,
126
- # nviews=25,
127
- # ):
128
- # # masks: (cols, rows) + 3d shape
129
- # # labels: (cols, rows)
130
- # # Plot settings
131
- # width = 150
132
- # height = 150
133
-
134
- # # Define view points
135
- # angles = np.linspace(0, 2*np.pi, nviews)
136
- # dirs = [(np.cos(a), np.sin(a), 0.0) for a in angles] # rotate around z
137
- # dirs += [(np.cos(a), 0.0, np.sin(a)) for a in angles] # rotate around y
138
-
139
- # # Count nr of mosaics
140
- # ncols = masks.shape[0]
141
- # nrows = masks.shape[1]
142
-
143
- # plotters = {}
144
- # for i, vec in enumerate(dirs):
145
- # plotters[i] = pv.Plotter(
146
- # window_size=(ncols*width, nrows*height),
147
- # shape=(nrows, ncols),
148
- # border=False,
149
- # off_screen=True,
150
- # )
151
- # plotters[i].background_color = 'white'
152
-
153
- # for row in tqdm(range(nrows), desc=f'Building mosaic'):
154
- # for col in range(ncols):
155
-
156
- # # Load data once
157
- # mask_norm = masks[col, row, ...]
158
-
159
- # orig_vol = pv.wrap(mask_norm.astype(float))
160
- # orig_vol.spacing = [1.0, 1.0, 1.0]
161
- # orig_surface = orig_vol.contour(isosurfaces=[0.5])
162
-
163
- # prev_up = None
164
- # for i, vec in enumerate(dirs):
165
- # # Camera position
166
- # distance = orig_surface.length * 2.0 # controls zoom
167
- # center = list(orig_surface.center)
168
- # pos = center + distance * np.array(vec) # vec = direction
169
- # up = _camera_up_from_direction(vec, prev_up)
170
- # prev_up = up
171
-
172
- # # Set up plotter
173
- # plotters[i].subplot(row, col)
174
- # if labels is not None:
175
- # plotters[i].add_text(labels[col, row], font_size=6)
176
- # plotters[i].add_mesh(orig_surface, color='lightblue', opacity=1.0, style='surface')
177
- # plotters[i].camera_position = [pos, center, up]
178
-
179
- # for i, vec in tqdm(enumerate(dirs), desc='Saving mosaics..'):
180
- # file = os.path.join(dir_output, f"mosaic_{i:03d}.png")
181
- # os.makedirs(Path(file).parent, exist_ok=True)
182
- # plotters[i].screenshot(file)
183
- # plotters[i].close()
184
153
 
185
154
 
186
155
 
@@ -190,6 +159,7 @@ def rotating_mosaics_da(dir_output, masks:list, labels=None, chunksize=None, nvi
190
159
  labels = [str(i) for i in range(len(masks))]
191
160
  if chunksize is None:
192
161
  chunksize = len(masks)
162
+ os.makedirs(dir_output, exist_ok=True)
193
163
 
194
164
  # Split into numbered chunks
195
165
  def chunk_list(lst, size):
@@ -211,78 +181,70 @@ def rotating_mosaics_da(dir_output, masks:list, labels=None, chunksize=None, nvi
211
181
  directions = {vec: os.path.join(dir_output, name) for name, vec in zip(names, dirs)}
212
182
  multiple_mosaic_masks_da(mask_chunk[1], directions, label_chunk[1], columns=columns, rows=rows)
213
183
 
214
-
215
- def multiple_mosaic_masks_da(masks:list, directions:dict, labels, columns=None, rows=None):
216
- # masks - list of dask arrays
184
+ def multiple_mosaic_masks_da(masks: list, directions: dict, labels, columns=None, rows=None):
217
185
  # Plot settings
186
+ width, height = 150, 150
218
187
  aspect_ratio = 16/9
219
- width = 150
220
- height = 150
221
188
 
222
- # Count nr of mosaics
223
189
  n_mosaics = len(masks)
224
- if columns is None:
225
- ncols = int(np.ceil(np.sqrt((height*n_mosaics)/(aspect_ratio*width))))
226
- else:
227
- ncols = columns
228
- if rows is None:
229
- nrows = int(np.ceil(n_mosaics/ncols))
230
- else:
231
- nrows = rows
232
- # nrows = int(np.ceil(np.sqrt((width*n_mosaics)/(aspect_ratio*height))))
233
- # ncols = int(np.ceil(n_mosaics/nrows))
190
+ ncols = columns if columns else int(np.ceil(np.sqrt((height*n_mosaics)/(aspect_ratio*width))))
191
+ nrows = rows if rows else int(np.ceil(n_mosaics/ncols))
234
192
 
235
- plotters = {}
236
- for vec in directions.keys():
237
- plotters[vec] = pv.Plotter(
193
+ # We loop through DIRECTIONS first. This keeps only ONE plotter in RAM at a time.
194
+ # To avoid re-computing the Spline/RBF surface 50 times per mask,
195
+ # we pre-calculate the surfaces once.
196
+
197
+ surfaces = []
198
+ for mask_series in tqdm(masks, desc="Pre-calculating Surfaces"):
199
+ # Your Spline/RBF smoothing
200
+ #mask_norm = ssa.sdf_ft.smooth_mask(mask_series[:].astype(bool), order=16)
201
+ mask_norm = mask_series[:].astype(bool)
202
+
203
+ vol = pv.wrap(mask_norm.astype(np.float32))
204
+ vol.spacing = [1.0, 1.0, 1.0]
205
+ surf = vol.contour(isosurfaces=[0.5])
206
+ surfaces.append(surf)
207
+ del vol # Clear RAM
208
+
209
+ # Now render each view angle
210
+ for vec, file_path in tqdm(directions.items(), desc="Rendering Views"):
211
+ plotter = pv.Plotter(
238
212
  window_size=(ncols*width, nrows*height),
239
213
  shape=(nrows, ncols),
240
214
  border=False,
241
- off_screen=True,
215
+ off_screen=pv.OFF_SCREEN,
242
216
  )
243
- plotters[vec].background_color = 'white'
244
-
245
- row = 0
246
- col = 0
247
- for mask_label, mask_series in tqdm(zip(labels, masks), total=len(labels), desc=f'Building mosaic'):
248
-
249
- # Load data once
250
- mask_norm = ssa.sdf_ft.smooth_mask(mask_series[:].astype(bool), order=16)
217
+ plotter.background_color = 'white'
251
218
 
252
- orig_vol = pv.wrap(mask_norm.astype(float))
253
- orig_vol.spacing = [1.0, 1.0, 1.0]
254
- orig_surface = orig_vol.contour(isosurfaces=[0.5])
219
+ for i, surf in enumerate(surfaces):
220
+ row, col = divmod(i, ncols)
221
+ if row >= nrows: break # Safety break
255
222
 
256
- prev_up = None
257
- for vec in directions.keys():
258
- # Camera position
259
- distance = orig_surface.length * 2.0 # controls zoom
260
- center = list(orig_surface.center)
261
- pos = center + distance * np.array(vec) # vec = direction
262
- up = _camera_up_from_direction(vec, prev_up)
263
- prev_up = up
223
+ # Camera Position
224
+ distance = surf.length * 2.0
225
+ center = list(surf.center)
226
+ pos = center + distance * np.array(vec)
227
+
228
+ # Using a simple up vector (0,0,1) is usually more stable across views
229
+ # unless you have a specific requirement for the _camera_up_from_direction
230
+ up = (0, 0, 1)
264
231
 
265
- # Set up plotter
266
- plotter = plotters[vec]
267
- plotter.subplot(row,col)
232
+ plotter.subplot(row, col)
268
233
  if labels is not None:
269
- plotter.add_text(mask_label, font_size=6)
270
- plotter.add_mesh(orig_surface, color='lightblue', opacity=1.0, style='surface')
271
- plotter.camera_position = [pos, center, up]
234
+ plotter.add_text(labels[i], font_size=6, color='black')
272
235
 
273
- # plotter.camera_position = 'iso'
274
- # plotter.view_vector(vec) # rotate 180° around vertical axis
236
+ plotter.add_mesh(surf, color='lightblue', smooth_shading=True)
237
+ plotter.camera_position = [pos, center, up]
238
+
239
+ # 1. Initialize the window in the background
240
+ plotter.show(auto_close=False, interactive=False, interactive_update=True)
241
+
242
+ # 2. Capture the pixels
243
+ plotter.screenshot(file_path)
244
+
245
+ # 3. Destroy the plotter immediately
246
+ plotter.close()
275
247
 
276
- if col == ncols-1:
277
- col = 0
278
- row += 1
279
- else:
280
- col += 1
281
-
282
- for vec, file in directions.items():
283
- # plotters[vec].render()
284
- plotters[vec].screenshot(file)
285
- plotters[vec].close()
286
248
 
287
249
 
288
250
  def rotating_mosaics_npz(dir_output, masks:list, labels=None, chunksize=None, nviews=25, columns=None, rows=None):
@@ -338,7 +300,8 @@ def multiple_mosaic_masks_npz(masks, directions:dict, labels, columns=None, rows
338
300
  window_size=(ncols*width, nrows*height),
339
301
  shape=(nrows, ncols),
340
302
  border=False,
341
- off_screen=True,
303
+ # off_screen=True,
304
+ off_screen=pv.OFF_SCREEN,
342
305
  )
343
306
  plotters[vec].background_color = 'white'
344
307
 
@@ -443,7 +406,8 @@ def mosaic_masks_npz(masks, imagefile, labels=None, view_vector=(1, 0, 0)):
443
406
  window_size=(ncols*width, nrows*height),
444
407
  shape=(nrows, ncols),
445
408
  border=False,
446
- off_screen=True,
409
+ # off_screen=True,
410
+ off_screen=pv.OFF_SCREEN,
447
411
  )
448
412
  plotter.background_color = 'white'
449
413
 
@@ -493,7 +457,8 @@ def mosaic_features_npz(features, imagefile, labels=None, view_vector=(1, 0, 0))
493
457
  window_size=(ncols*width, nrows*height),
494
458
  shape=(nrows, ncols),
495
459
  border=False,
496
- off_screen=True,
460
+ # off_screen=True,
461
+ off_screen=pv.OFF_SCREEN,
497
462
  )
498
463
  plotter.background_color = 'white'
499
464
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: miblab-plot
3
- Version: 0.0.4
3
+ Version: 0.0.6
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