0
# Volume Data Handling
1
2
Support for 3D volumetric data commonly used in medical imaging, scientific visualization, microscopy, and computational modeling applications.
3
4
## Capabilities
5
6
### Single Volume Reading
7
8
Read 3D volumetric data from various scientific and medical imaging formats.
9
10
```python { .api }
11
def volread(uri, format=None, **kwargs):
12
"""
13
Read a volume from the specified file.
14
15
Parameters:
16
- uri (ImageResource): File path, URL, bytes, or file object
17
- format (str, optional): Format to use for reading
18
- **kwargs: Format-specific parameters
19
20
Returns:
21
- Array: 3D numpy array (NxMxL) or 4D (NxMxLxK) with metadata
22
23
Note: Volume must be 3D (grayscale) or 4D (with color/channels)
24
"""
25
```
26
27
**Usage Examples:**
28
29
```python
30
import imageio.v2 as imageio
31
import numpy as np
32
33
# Read medical imaging volume (DICOM series, NIfTI, etc.)
34
volume = imageio.volread('brain_scan.nii')
35
print(f"Volume shape: {volume.shape}") # e.g., (256, 256, 180)
36
print(f"Data type: {volume.dtype}")
37
print(f"Metadata: {volume.meta}")
38
39
# Read microscopy z-stack
40
z_stack = imageio.volread('cells_z_stack.tiff')
41
print(f"Z-stack shape: {z_stack.shape}") # e.g., (512, 512, 50)
42
43
# Read with specific format
44
volume = imageio.volread('data.raw', format='RAW-FI')
45
46
# Read 4D volume (with color channels)
47
color_volume = imageio.volread('4d_dataset.tiff')
48
print(f"4D shape: {color_volume.shape}") # e.g., (100, 100, 50, 3)
49
```
50
51
### Single Volume Writing
52
53
Write 3D volumetric data to file with format-specific optimizations.
54
55
```python { .api }
56
def volwrite(uri, vol, format=None, **kwargs):
57
"""
58
Write a volume to the specified file.
59
60
Parameters:
61
- uri (ImageResource): Output path or '<bytes>' for byte return
62
- vol (ArrayLike): Volume data as 3D (NxMxL) or 4D (NxMxLxK) array
63
- format (str, optional): Format to use for writing
64
- **kwargs: Format-specific parameters
65
66
Returns:
67
- None: When writing to file
68
- bytes: When uri is '<bytes>'
69
70
Raises:
71
- ValueError: If volume dimensions are invalid (not 3D or 4D)
72
"""
73
```
74
75
**Usage Examples:**
76
77
```python
78
import imageio.v2 as imageio
79
import numpy as np
80
81
# Create sample 3D volume
82
volume = np.random.randint(0, 255, (64, 64, 32), dtype=np.uint8)
83
84
# Write as TIFF stack
85
imageio.volwrite('volume.tiff', volume)
86
87
# Write with compression
88
imageio.volwrite('compressed_volume.tiff', volume, compression='lzw')
89
90
# Write as raw binary data
91
imageio.volwrite('volume.raw', volume)
92
93
# Write 4D volume with color channels
94
color_volume = np.random.randint(0, 255, (32, 32, 16, 3), dtype=np.uint8)
95
imageio.volwrite('color_volume.tiff', color_volume)
96
97
# Get volume as bytes
98
volume_bytes = imageio.volwrite('<bytes>', volume, format='TIFF')
99
```
100
101
### Multiple Volume Reading
102
103
Read multiple 3D volumes with memory management for large datasets.
104
105
```python { .api }
106
def mvolread(uri, format=None, memtest="1GB", **kwargs):
107
"""
108
Read multiple volumes from the specified file.
109
110
Parameters:
111
- uri (ImageResource): File path, URL, bytes, or file object
112
- format (str, optional): Format to use for reading
113
- memtest (bool|int|float|str): Memory limit protection
114
- Default is '1GB' (larger than mimread due to 3D data size)
115
- **kwargs: Format-specific parameters
116
117
Returns:
118
- List[Array]: List of 3D/4D numpy arrays with metadata
119
120
Raises:
121
- RuntimeError: If memory limit exceeded
122
"""
123
```
124
125
**Usage Examples:**
126
127
```python
128
# Read time-series of 3D volumes (4D dataset)
129
time_volumes = imageio.mvolread('time_series_4d.tiff')
130
print(f"Number of time points: {len(time_volumes)}")
131
for t, vol in enumerate(time_volumes):
132
print(f"Time {t}: {vol.shape}")
133
134
# Read multiple brain scans with custom memory limit
135
scans = imageio.mvolread('multiple_scans.nii', memtest='2GB')
136
137
# Read without memory protection for known small datasets
138
small_volumes = imageio.mvolread('small_dataset.tiff', memtest=False)
139
```
140
141
### Multiple Volume Writing
142
143
Write sequences of 3D volumes for time-series or batch data.
144
145
```python { .api }
146
def mvolwrite(uri, vols, format=None, **kwargs):
147
"""
148
Write multiple volumes to the specified file.
149
150
Parameters:
151
- uri (ImageResource): Output path or '<bytes>' for byte return
152
- vols (Sequence[ArrayLike]): Sequence of 3D/4D volume arrays
153
- format (str, optional): Format to use for writing
154
- **kwargs: Format-specific parameters
155
156
Returns:
157
- None: When writing to file
158
- bytes: When uri is '<bytes>'
159
160
Raises:
161
- ValueError: If any volume has invalid dimensions
162
"""
163
```
164
165
**Usage Examples:**
166
167
```python
168
import imageio.v2 as imageio
169
import numpy as np
170
171
# Create time series of 3D volumes
172
time_volumes = []
173
for t in range(5):
174
# Simulate time-varying 3D data
175
volume = np.random.randint(0, 255, (32, 32, 16), dtype=np.uint8)
176
# Add time-dependent pattern
177
volume[t*6:(t+1)*6, :, :] = 255
178
time_volumes.append(volume)
179
180
# Write as 4D TIFF (time series)
181
imageio.mvolwrite('time_series.tiff', time_volumes)
182
183
# Write with metadata
184
imageio.mvolwrite('annotated_series.tiff', time_volumes,
185
resolution=(1.0, 1.0, 2.0), # X, Y, Z resolution
186
software='ImageIO Python')
187
```
188
189
## Scientific and Medical Formats
190
191
### DICOM Volumes
192
193
Handle medical imaging DICOM files and series:
194
195
```python
196
# Read DICOM volume (requires pydicom plugin)
197
try:
198
dicom_volume = imageio.volread('brain_scan.dcm', format='DICOM')
199
print(f"DICOM metadata: {dicom_volume.meta}")
200
except Exception as e:
201
print(f"DICOM plugin required: {e}")
202
203
# For DICOM series, typically need to read directory
204
# Check imageio.plugins.dicom documentation for series handling
205
```
206
207
### NIfTI Volumes
208
209
Medical imaging standard format:
210
211
```python
212
# Read NIfTI file (common in neuroimaging)
213
nifti_volume = imageio.volread('brain.nii.gz')
214
print(f"NIfTI shape: {nifti_volume.shape}")
215
print(f"Voxel dimensions: {nifti_volume.meta.get('voxel_size', 'Unknown')}")
216
217
# Write NIfTI volume
218
imageio.volwrite('output.nii.gz', processed_volume)
219
```
220
221
### Multi-dimensional TIFF
222
223
Handle complex TIFF volumes with metadata:
224
225
```python
226
# Read multi-dimensional TIFF with rich metadata
227
tiff_volume = imageio.volread('microscopy_3d.tiff')
228
print("TIFF metadata:")
229
for key, value in tiff_volume.meta.items():
230
print(f" {key}: {value}")
231
232
# Write TIFF with custom metadata
233
metadata_dict = {
234
'spacing': (0.1, 0.1, 0.2), # μm per pixel
235
'unit': 'micrometer',
236
'channels': ['DAPI', 'GFP', 'RFP']
237
}
238
239
imageio.volwrite('annotated.tiff', volume,
240
resolution=(10, 10), # pixels per unit
241
**metadata_dict)
242
```
243
244
## Volume Processing Examples
245
246
### Basic Volume Operations
247
248
Common operations on 3D volumetric data:
249
250
```python
251
import imageio.v2 as imageio
252
import numpy as np
253
254
# Load volume
255
volume = imageio.volread('scan.tiff')
256
257
# Volume statistics
258
print(f"Volume shape: {volume.shape}")
259
print(f"Min/Max values: {volume.min()}/{volume.max()}")
260
print(f"Mean intensity: {volume.mean():.2f}")
261
262
# Extract slices
263
xy_slice = volume[:, :, volume.shape[2]//2] # Middle Z slice
264
xz_slice = volume[:, volume.shape[1]//2, :] # Middle Y slice
265
yz_slice = volume[volume.shape[0]//2, :, :] # Middle X slice
266
267
# Save slices as 2D images
268
imageio.imwrite('xy_slice.png', xy_slice)
269
imageio.imwrite('xz_slice.png', xz_slice)
270
imageio.imwrite('yz_slice.png', yz_slice)
271
272
# Apply 3D operations
273
# Gaussian smoothing (requires scipy)
274
try:
275
from scipy import ndimage
276
smoothed = ndimage.gaussian_filter(volume.astype(float), sigma=1.0)
277
imageio.volwrite('smoothed.tiff', smoothed.astype(volume.dtype))
278
except ImportError:
279
print("scipy required for filtering operations")
280
281
# Threshold volume
282
threshold = np.percentile(volume, 75)
283
binary_volume = (volume > threshold).astype(np.uint8) * 255
284
imageio.volwrite('binary.tiff', binary_volume)
285
```
286
287
### Volume Format Conversion
288
289
Convert between different 3D formats:
290
291
```python
292
def convert_volume_format(input_file, output_file, **kwargs):
293
"""Convert volume between formats."""
294
volume = imageio.volread(input_file)
295
imageio.volwrite(output_file, volume, **kwargs)
296
297
# Convert DICOM to TIFF
298
convert_volume_format('scan.dcm', 'scan.tiff', compression='lzw')
299
300
# Convert with data type change
301
volume = imageio.volread('float_volume.tiff')
302
# Convert float to 16-bit integer
303
volume_16bit = (volume * 65535).astype(np.uint16)
304
imageio.volwrite('volume_16bit.tiff', volume_16bit)
305
```
306
307
### Time-Series Volume Analysis
308
309
Process 4D datasets (3D volumes over time):
310
311
```python
312
# Load time series
313
time_volumes = imageio.mvolread('4d_dataset.tiff')
314
print(f"Time points: {len(time_volumes)}")
315
316
# Analyze temporal changes
317
mean_intensities = []
318
for t, volume in enumerate(time_volumes):
319
mean_intensity = volume.mean()
320
mean_intensities.append(mean_intensity)
321
print(f"Time {t}: mean intensity = {mean_intensity:.2f}")
322
323
# Create maximum intensity projection over time
324
max_projection = np.maximum.reduce(time_volumes)
325
imageio.volwrite('temporal_max_projection.tiff', max_projection)
326
327
# Extract and save specific time points
328
for t in [0, len(time_volumes)//2, -1]: # First, middle, last
329
imageio.volwrite(f'timepoint_{t:03d}.tiff', time_volumes[t])
330
```
331
332
## Performance Considerations
333
334
### Memory Usage
335
336
Volume data can be memory-intensive. Consider these strategies:
337
338
```python
339
# Check expected memory usage before loading
340
import os
341
file_size = os.path.getsize('large_volume.tiff')
342
print(f"File size: {file_size / (1024**3):.2f} GB")
343
344
# For very large volumes, consider:
345
# 1. Using memtest limits
346
try:
347
volume = imageio.volread('large_volume.tiff', memtest='4GB')
348
except RuntimeError:
349
print("Volume too large, use alternative approach")
350
351
# 2. Processing in chunks (if supported by format)
352
# 3. Using readers for sequential access
353
reader = imageio.get_reader('large_volume.tiff')
354
# Process slice by slice if reader supports it
355
```
356
357
### Data Type Optimization
358
359
Choose appropriate data types for memory efficiency:
360
361
```python
362
# Load volume and check data type
363
volume = imageio.volread('volume.tiff')
364
print(f"Original dtype: {volume.dtype}, size: {volume.nbytes} bytes")
365
366
# Convert to smaller data type if range allows
367
if volume.max() <= 255:
368
volume_uint8 = volume.astype(np.uint8)
369
print(f"As uint8: {volume_uint8.nbytes} bytes")
370
imageio.volwrite('volume_uint8.tiff', volume_uint8)
371
372
# Use 16-bit for better precision with smaller size than float32
373
if volume.dtype == np.float32 and 0 <= volume.min() and volume.max() <= 1:
374
volume_uint16 = (volume * 65535).astype(np.uint16)
375
imageio.volwrite('volume_uint16.tiff', volume_uint16)
376
```