miblab-plot 0.0.4__tar.gz → 0.0.5__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.5
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.5"
10
10
  dependencies = [
11
11
  'pillow',
12
12
  'numpy',
@@ -1,6 +1,7 @@
1
1
  import os
2
2
  from pathlib import Path
3
3
  from typing import Union
4
+ import gc
4
5
 
5
6
  import numpy as np
6
7
  from tqdm import tqdm
@@ -9,6 +10,27 @@ import dbdicom as db
9
10
  import zarr
10
11
 
11
12
  import miblab_ssa as ssa
13
+ import platform
14
+
15
+
16
+ def setup_rendering_env():
17
+ current_os = platform.system().lower()
18
+ # On Linux, check for DISPLAY. On Windows/Mac, we usually assume a display exists.
19
+ is_headless = (os.environ.get("DISPLAY") is None) if current_os == "linux" else False
20
+
21
+ if is_headless:
22
+ try:
23
+ pv.start_xvfb()
24
+ except Exception:
25
+ pass
26
+
27
+ # IMPORTANT: We want to ALLOW off-screen rendering even on Windows
28
+ # So we don't force pv.OFF_SCREEN to be False just because we have a screen.
29
+ pv.OFF_SCREEN = True
30
+
31
+ print(f"OS: {current_os} | Headless: {is_headless} | Off-screen: {pv.OFF_SCREEN}")
32
+
33
+ setup_rendering_env()
12
34
 
13
35
 
14
36
  def mosaic_masks_dcm(masks, imagefile, labels=None, view_vector=(1, 0, 0)):
@@ -23,7 +45,13 @@ def mosaic_masks_dcm(masks, imagefile, labels=None, view_vector=(1, 0, 0)):
23
45
  nrows = int(np.ceil(np.sqrt((width*n_mosaics)/(aspect_ratio*height))))
24
46
  ncols = int(np.ceil(n_mosaics/nrows))
25
47
 
26
- plotter = pv.Plotter(window_size=(ncols*width, nrows*height), shape=(nrows, ncols), border=False, off_screen=True)
48
+ plotter = pv.Plotter(
49
+ window_size=(ncols*width, nrows*height),
50
+ shape=(nrows, ncols),
51
+ border=False,
52
+ # off_screen=True,
53
+ off_screen=pv.OFF_SCREEN,
54
+ )
27
55
  plotter.background_color = 'white'
28
56
 
29
57
  row = 0
@@ -80,7 +108,8 @@ def rotating_masks_grid(
80
108
  window_size=(ncols*width, nrows*height),
81
109
  shape=(nrows, ncols),
82
110
  border=False,
83
- off_screen=True,
111
+ # off_screen=True,
112
+ off_screen=pv.OFF_SCREEN,
84
113
  )
85
114
  plotter.background_color = 'white'
86
115
 
@@ -119,68 +148,6 @@ def rotating_masks_grid(
119
148
  plotter.close() # CRITICAL: Releases the GPU and RAM buffers
120
149
  del plotter
121
150
 
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
151
 
185
152
 
186
153
 
@@ -190,6 +157,7 @@ def rotating_mosaics_da(dir_output, masks:list, labels=None, chunksize=None, nvi
190
157
  labels = [str(i) for i in range(len(masks))]
191
158
  if chunksize is None:
192
159
  chunksize = len(masks)
160
+ os.makedirs(dir_output, exist_ok=True)
193
161
 
194
162
  # Split into numbered chunks
195
163
  def chunk_list(lst, size):
@@ -211,78 +179,70 @@ def rotating_mosaics_da(dir_output, masks:list, labels=None, chunksize=None, nvi
211
179
  directions = {vec: os.path.join(dir_output, name) for name, vec in zip(names, dirs)}
212
180
  multiple_mosaic_masks_da(mask_chunk[1], directions, label_chunk[1], columns=columns, rows=rows)
213
181
 
214
-
215
- def multiple_mosaic_masks_da(masks:list, directions:dict, labels, columns=None, rows=None):
216
- # masks - list of dask arrays
182
+ def multiple_mosaic_masks_da(masks: list, directions: dict, labels, columns=None, rows=None):
217
183
  # Plot settings
184
+ width, height = 150, 150
218
185
  aspect_ratio = 16/9
219
- width = 150
220
- height = 150
221
186
 
222
- # Count nr of mosaics
223
187
  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))
188
+ ncols = columns if columns else int(np.ceil(np.sqrt((height*n_mosaics)/(aspect_ratio*width))))
189
+ nrows = rows if rows else int(np.ceil(n_mosaics/ncols))
234
190
 
235
- plotters = {}
236
- for vec in directions.keys():
237
- plotters[vec] = pv.Plotter(
191
+ # We loop through DIRECTIONS first. This keeps only ONE plotter in RAM at a time.
192
+ # To avoid re-computing the Spline/RBF surface 50 times per mask,
193
+ # we pre-calculate the surfaces once.
194
+
195
+ surfaces = []
196
+ for mask_series in tqdm(masks, desc="Pre-calculating Surfaces"):
197
+ # Your Spline/RBF smoothing
198
+ #mask_norm = ssa.sdf_ft.smooth_mask(mask_series[:].astype(bool), order=16)
199
+ mask_norm = mask_series[:].astype(bool)
200
+
201
+ vol = pv.wrap(mask_norm.astype(np.float32))
202
+ vol.spacing = [1.0, 1.0, 1.0]
203
+ surf = vol.contour(isosurfaces=[0.5])
204
+ surfaces.append(surf)
205
+ del vol # Clear RAM
206
+
207
+ # Now render each view angle
208
+ for vec, file_path in tqdm(directions.items(), desc="Rendering Views"):
209
+ plotter = pv.Plotter(
238
210
  window_size=(ncols*width, nrows*height),
239
211
  shape=(nrows, ncols),
240
212
  border=False,
241
- off_screen=True,
213
+ off_screen=pv.OFF_SCREEN,
242
214
  )
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)
215
+ plotter.background_color = 'white'
251
216
 
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])
217
+ for i, surf in enumerate(surfaces):
218
+ row, col = divmod(i, ncols)
219
+ if row >= nrows: break # Safety break
255
220
 
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
221
+ # Camera Position
222
+ distance = surf.length * 2.0
223
+ center = list(surf.center)
224
+ pos = center + distance * np.array(vec)
225
+
226
+ # Using a simple up vector (0,0,1) is usually more stable across views
227
+ # unless you have a specific requirement for the _camera_up_from_direction
228
+ up = (0, 0, 1)
264
229
 
265
- # Set up plotter
266
- plotter = plotters[vec]
267
- plotter.subplot(row,col)
230
+ plotter.subplot(row, col)
268
231
  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]
232
+ plotter.add_text(labels[i], font_size=6, color='black')
272
233
 
273
- # plotter.camera_position = 'iso'
274
- # plotter.view_vector(vec) # rotate 180° around vertical axis
234
+ plotter.add_mesh(surf, color='lightblue', smooth_shading=True)
235
+ plotter.camera_position = [pos, center, up]
236
+
237
+ # 1. Initialize the window in the background
238
+ plotter.show(auto_close=False, interactive=False, interactive_update=True)
239
+
240
+ # 2. Capture the pixels
241
+ plotter.screenshot(file_path)
242
+
243
+ # 3. Destroy the plotter immediately
244
+ plotter.close()
275
245
 
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
246
 
287
247
 
288
248
  def rotating_mosaics_npz(dir_output, masks:list, labels=None, chunksize=None, nviews=25, columns=None, rows=None):
@@ -338,7 +298,8 @@ def multiple_mosaic_masks_npz(masks, directions:dict, labels, columns=None, rows
338
298
  window_size=(ncols*width, nrows*height),
339
299
  shape=(nrows, ncols),
340
300
  border=False,
341
- off_screen=True,
301
+ # off_screen=True,
302
+ off_screen=pv.OFF_SCREEN,
342
303
  )
343
304
  plotters[vec].background_color = 'white'
344
305
 
@@ -443,7 +404,8 @@ def mosaic_masks_npz(masks, imagefile, labels=None, view_vector=(1, 0, 0)):
443
404
  window_size=(ncols*width, nrows*height),
444
405
  shape=(nrows, ncols),
445
406
  border=False,
446
- off_screen=True,
407
+ # off_screen=True,
408
+ off_screen=pv.OFF_SCREEN,
447
409
  )
448
410
  plotter.background_color = 'white'
449
411
 
@@ -493,7 +455,8 @@ def mosaic_features_npz(features, imagefile, labels=None, view_vector=(1, 0, 0))
493
455
  window_size=(ncols*width, nrows*height),
494
456
  shape=(nrows, ncols),
495
457
  border=False,
496
- off_screen=True,
458
+ # off_screen=True,
459
+ off_screen=pv.OFF_SCREEN,
497
460
  )
498
461
  plotter.background_color = 'white'
499
462
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: miblab-plot
3
- Version: 0.0.4
3
+ Version: 0.0.5
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