miblab-plot 0.0.3__tar.gz → 0.0.4__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.3
3
+ Version: 0.0.4
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.3"
9
+ version = "0.0.4"
10
10
  dependencies = [
11
11
  'pillow',
12
12
  'numpy',
@@ -57,72 +57,235 @@ def mosaic_masks_dcm(masks, imagefile, labels=None, view_vector=(1, 0, 0)):
57
57
 
58
58
 
59
59
  def rotating_masks_grid(
60
- dir_output:str,
61
- masks:Union[zarr.Array, np.ndarray],
62
- labels:np.ndarray=None,
63
- nviews=25,
60
+ dir_output: str,
61
+ masks: Union[zarr.Array, np.ndarray],
62
+ labels: np.ndarray = None,
63
+ nviews = 25,
64
64
  ):
65
- # masks: (cols, rows) + 3d shape
66
- # labels: (cols, rows)
67
- # Plot settings
68
- width = 150
69
- height = 150
65
+ # 1. Setup metadata
66
+ width, height = 150, 150
67
+ angles = np.linspace(0, 2*np.pi, nviews)
68
+ # View directions (Z-rotation and Y-rotation)
69
+ dirs = [(np.cos(a), np.sin(a), 0.0) for a in angles]
70
+ dirs += [(np.cos(a), 0.0, np.sin(a)) for a in angles]
71
+
72
+ ncols, nrows = masks.shape[0], masks.shape[1]
73
+ os.makedirs(dir_output, exist_ok=True)
74
+
75
+ # 2. Outer Loop: Views (The "Memory Clear" loop)
76
+ # By putting 'views' on the outside, we only ever need ONE plotter in RAM.
77
+ for i, vec in enumerate(tqdm(dirs, desc="Rendering View Angles")):
78
+
79
+ plotter = pv.Plotter(
80
+ window_size=(ncols*width, nrows*height),
81
+ shape=(nrows, ncols),
82
+ border=False,
83
+ off_screen=True,
84
+ )
85
+ plotter.background_color = 'white'
86
+
87
+ # 3. Inner Loops: Grid
88
+ for row in range(nrows):
89
+ for col in range(ncols):
90
+ # Load mask (27MB bool) -> Convert to 109MB float32 (not float64!)
91
+ mask_norm = masks[col, row, ...].astype(np.float32)
92
+
93
+ # Generate Surface Mesh (The 10x-to-Mesh conversion)
94
+ #
95
+ vol = pv.wrap(mask_norm)
96
+ vol.spacing = [1.0, 1.0, 1.0]
97
+ surf = vol.contour(isosurfaces=[0.5])
98
+
99
+ # Cleanup volume from RAM immediately
100
+ del vol
101
+
102
+ # Camera Math
103
+ distance = surf.length * 2.5
104
+ center = list(surf.center)
105
+ pos = center + distance * np.array(vec)
106
+
107
+ # Plotting
108
+ plotter.subplot(row, col)
109
+ if labels is not None:
110
+ plotter.add_text(str(labels[col, row]), font_size=6, color='black')
111
+
112
+ plotter.add_mesh(surf, color='lightblue', smooth_shading=True)
113
+ plotter.camera_position = [pos, center, (0, 0, 1)] # Simple Up-vector
114
+
115
+ # 4. Save and Destroy
116
+ # This is where the RAM resets to zero for the next angle
117
+ file = os.path.join(dir_output, f"mosaic_{i:03d}.png")
118
+ plotter.screenshot(file)
119
+ plotter.close() # CRITICAL: Releases the GPU and RAM buffers
120
+ del plotter
121
+
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
+
185
+
186
+
187
+ def rotating_mosaics_da(dir_output, masks:list, labels=None, chunksize=None, nviews=25, columns=None, rows=None):
188
+ # masks - list of numpy or dask arrays
189
+ if labels is None:
190
+ labels = [str(i) for i in range(len(masks))]
191
+ if chunksize is None:
192
+ chunksize = len(masks)
193
+
194
+ # Split into numbered chunks
195
+ def chunk_list(lst, size):
196
+ chunks = [lst[i:i+size] for i in range(0, len(lst), size)]
197
+ return list(enumerate(chunks))
198
+
199
+ mask_chunks = chunk_list(masks, chunksize)
200
+ label_chunks = chunk_list(labels, chunksize)
70
201
 
71
202
  # Define view points
72
203
  angles = np.linspace(0, 2*np.pi, nviews)
73
204
  dirs = [(np.cos(a), np.sin(a), 0.0) for a in angles] # rotate around z
74
205
  dirs += [(np.cos(a), 0.0, np.sin(a)) for a in angles] # rotate around y
75
206
 
207
+ # Save mosaics for each chunk and view
208
+ for mask_chunk, label_chunk in tqdm(zip(mask_chunks, label_chunks), total=len(label_chunks), desc='Building chunk of mosaics'):
209
+ chunk_idx = mask_chunk[0]
210
+ names = [f"group_{str(chunk_idx).zfill(2)}_{i:02d}.png" for i in range(len(dirs))]
211
+ directions = {vec: os.path.join(dir_output, name) for name, vec in zip(names, dirs)}
212
+ multiple_mosaic_masks_da(mask_chunk[1], directions, label_chunk[1], columns=columns, rows=rows)
213
+
214
+
215
+ def multiple_mosaic_masks_da(masks:list, directions:dict, labels, columns=None, rows=None):
216
+ # masks - list of dask arrays
217
+ # Plot settings
218
+ aspect_ratio = 16/9
219
+ width = 150
220
+ height = 150
221
+
76
222
  # Count nr of mosaics
77
- ncols = masks.shape[0]
78
- nrows = masks.shape[1]
223
+ 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))
79
234
 
80
235
  plotters = {}
81
- for i, vec in enumerate(dirs):
82
- plotters[i] = pv.Plotter(
236
+ for vec in directions.keys():
237
+ plotters[vec] = pv.Plotter(
83
238
  window_size=(ncols*width, nrows*height),
84
239
  shape=(nrows, ncols),
85
240
  border=False,
86
241
  off_screen=True,
87
242
  )
88
- plotters[i].background_color = 'white'
89
-
90
- for row in tqdm(range(nrows), desc=f'Building mosaic'):
91
- for col in range(ncols):
92
-
93
- # Load data once
94
- mask_norm = masks[col, row, ...]
243
+ plotters[vec].background_color = 'white'
95
244
 
96
- orig_vol = pv.wrap(mask_norm.astype(float))
97
- orig_vol.spacing = [1.0, 1.0, 1.0]
98
- orig_surface = orig_vol.contour(isosurfaces=[0.5])
245
+ row = 0
246
+ col = 0
247
+ for mask_label, mask_series in tqdm(zip(labels, masks), total=len(labels), desc=f'Building mosaic'):
99
248
 
100
- prev_up = None
101
- for i, vec in enumerate(dirs):
102
- # Camera position
103
- distance = orig_surface.length * 2.0 # controls zoom
104
- center = list(orig_surface.center)
105
- pos = center + distance * np.array(vec) # vec = direction
106
- up = _camera_up_from_direction(vec, prev_up)
107
- prev_up = up
249
+ # Load data once
250
+ mask_norm = ssa.sdf_ft.smooth_mask(mask_series[:].astype(bool), order=16)
108
251
 
109
- # Set up plotter
110
- plotters[i].subplot(row, col)
111
- if labels is not None:
112
- plotters[i].add_text(labels[col, row], font_size=6)
113
- plotters[i].add_mesh(orig_surface, color='lightblue', opacity=1.0, style='surface')
114
- plotters[i].camera_position = [pos, center, up]
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])
115
255
 
116
- for i, vec in tqdm(enumerate(dirs), desc='Saving mosaics..'):
117
- file = os.path.join(dir_output, f"mosaic_{i:03d}.png")
118
- os.makedirs(Path(file).parent, exist_ok=True)
119
- plotters[i].screenshot(file)
120
- plotters[i].close()
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
121
264
 
265
+ # Set up plotter
266
+ plotter = plotters[vec]
267
+ plotter.subplot(row,col)
268
+ 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]
272
+
273
+ # plotter.camera_position = 'iso'
274
+ # plotter.view_vector(vec) # rotate 180° around vertical axis
122
275
 
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()
123
286
 
124
287
 
125
- def rotating_mosaics_npz(dir_output, masks, labels=None, chunksize=None, nviews=25, columns=None, rows=None):
288
+ def rotating_mosaics_npz(dir_output, masks:list, labels=None, chunksize=None, nviews=25, columns=None, rows=None):
126
289
 
127
290
  if labels is None:
128
291
  labels = [str(i) for i in range(len(masks))]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: miblab-plot
3
- Version: 0.0.3
3
+ Version: 0.0.4
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