Library for reading and writing a wide range of image, video, scientific, and volumetric data formats.
—
Support for 3D volumetric data commonly used in medical imaging, scientific visualization, microscopy, and computational modeling applications.
Read 3D volumetric data from various scientific and medical imaging formats.
def volread(uri, format=None, **kwargs):
"""
Read a volume from the specified file.
Parameters:
- uri (ImageResource): File path, URL, bytes, or file object
- format (str, optional): Format to use for reading
- **kwargs: Format-specific parameters
Returns:
- Array: 3D numpy array (NxMxL) or 4D (NxMxLxK) with metadata
Note: Volume must be 3D (grayscale) or 4D (with color/channels)
"""Usage Examples:
import imageio.v2 as imageio
import numpy as np
# Read medical imaging volume (DICOM series, NIfTI, etc.)
volume = imageio.volread('brain_scan.nii')
print(f"Volume shape: {volume.shape}") # e.g., (256, 256, 180)
print(f"Data type: {volume.dtype}")
print(f"Metadata: {volume.meta}")
# Read microscopy z-stack
z_stack = imageio.volread('cells_z_stack.tiff')
print(f"Z-stack shape: {z_stack.shape}") # e.g., (512, 512, 50)
# Read with specific format
volume = imageio.volread('data.raw', format='RAW-FI')
# Read 4D volume (with color channels)
color_volume = imageio.volread('4d_dataset.tiff')
print(f"4D shape: {color_volume.shape}") # e.g., (100, 100, 50, 3)Write 3D volumetric data to file with format-specific optimizations.
def volwrite(uri, vol, format=None, **kwargs):
"""
Write a volume to the specified file.
Parameters:
- uri (ImageResource): Output path or '<bytes>' for byte return
- vol (ArrayLike): Volume data as 3D (NxMxL) or 4D (NxMxLxK) array
- format (str, optional): Format to use for writing
- **kwargs: Format-specific parameters
Returns:
- None: When writing to file
- bytes: When uri is '<bytes>'
Raises:
- ValueError: If volume dimensions are invalid (not 3D or 4D)
"""Usage Examples:
import imageio.v2 as imageio
import numpy as np
# Create sample 3D volume
volume = np.random.randint(0, 255, (64, 64, 32), dtype=np.uint8)
# Write as TIFF stack
imageio.volwrite('volume.tiff', volume)
# Write with compression
imageio.volwrite('compressed_volume.tiff', volume, compression='lzw')
# Write as raw binary data
imageio.volwrite('volume.raw', volume)
# Write 4D volume with color channels
color_volume = np.random.randint(0, 255, (32, 32, 16, 3), dtype=np.uint8)
imageio.volwrite('color_volume.tiff', color_volume)
# Get volume as bytes
volume_bytes = imageio.volwrite('<bytes>', volume, format='TIFF')Read multiple 3D volumes with memory management for large datasets.
def mvolread(uri, format=None, memtest="1GB", **kwargs):
"""
Read multiple volumes from the specified file.
Parameters:
- uri (ImageResource): File path, URL, bytes, or file object
- format (str, optional): Format to use for reading
- memtest (bool|int|float|str): Memory limit protection
- Default is '1GB' (larger than mimread due to 3D data size)
- **kwargs: Format-specific parameters
Returns:
- List[Array]: List of 3D/4D numpy arrays with metadata
Raises:
- RuntimeError: If memory limit exceeded
"""Usage Examples:
# Read time-series of 3D volumes (4D dataset)
time_volumes = imageio.mvolread('time_series_4d.tiff')
print(f"Number of time points: {len(time_volumes)}")
for t, vol in enumerate(time_volumes):
print(f"Time {t}: {vol.shape}")
# Read multiple brain scans with custom memory limit
scans = imageio.mvolread('multiple_scans.nii', memtest='2GB')
# Read without memory protection for known small datasets
small_volumes = imageio.mvolread('small_dataset.tiff', memtest=False)Write sequences of 3D volumes for time-series or batch data.
def mvolwrite(uri, vols, format=None, **kwargs):
"""
Write multiple volumes to the specified file.
Parameters:
- uri (ImageResource): Output path or '<bytes>' for byte return
- vols (Sequence[ArrayLike]): Sequence of 3D/4D volume arrays
- format (str, optional): Format to use for writing
- **kwargs: Format-specific parameters
Returns:
- None: When writing to file
- bytes: When uri is '<bytes>'
Raises:
- ValueError: If any volume has invalid dimensions
"""Usage Examples:
import imageio.v2 as imageio
import numpy as np
# Create time series of 3D volumes
time_volumes = []
for t in range(5):
# Simulate time-varying 3D data
volume = np.random.randint(0, 255, (32, 32, 16), dtype=np.uint8)
# Add time-dependent pattern
volume[t*6:(t+1)*6, :, :] = 255
time_volumes.append(volume)
# Write as 4D TIFF (time series)
imageio.mvolwrite('time_series.tiff', time_volumes)
# Write with metadata
imageio.mvolwrite('annotated_series.tiff', time_volumes,
resolution=(1.0, 1.0, 2.0), # X, Y, Z resolution
software='ImageIO Python')Handle medical imaging DICOM files and series:
# Read DICOM volume (requires pydicom plugin)
try:
dicom_volume = imageio.volread('brain_scan.dcm', format='DICOM')
print(f"DICOM metadata: {dicom_volume.meta}")
except Exception as e:
print(f"DICOM plugin required: {e}")
# For DICOM series, typically need to read directory
# Check imageio.plugins.dicom documentation for series handlingMedical imaging standard format:
# Read NIfTI file (common in neuroimaging)
nifti_volume = imageio.volread('brain.nii.gz')
print(f"NIfTI shape: {nifti_volume.shape}")
print(f"Voxel dimensions: {nifti_volume.meta.get('voxel_size', 'Unknown')}")
# Write NIfTI volume
imageio.volwrite('output.nii.gz', processed_volume)Handle complex TIFF volumes with metadata:
# Read multi-dimensional TIFF with rich metadata
tiff_volume = imageio.volread('microscopy_3d.tiff')
print("TIFF metadata:")
for key, value in tiff_volume.meta.items():
print(f" {key}: {value}")
# Write TIFF with custom metadata
metadata_dict = {
'spacing': (0.1, 0.1, 0.2), # μm per pixel
'unit': 'micrometer',
'channels': ['DAPI', 'GFP', 'RFP']
}
imageio.volwrite('annotated.tiff', volume,
resolution=(10, 10), # pixels per unit
**metadata_dict)Common operations on 3D volumetric data:
import imageio.v2 as imageio
import numpy as np
# Load volume
volume = imageio.volread('scan.tiff')
# Volume statistics
print(f"Volume shape: {volume.shape}")
print(f"Min/Max values: {volume.min()}/{volume.max()}")
print(f"Mean intensity: {volume.mean():.2f}")
# Extract slices
xy_slice = volume[:, :, volume.shape[2]//2] # Middle Z slice
xz_slice = volume[:, volume.shape[1]//2, :] # Middle Y slice
yz_slice = volume[volume.shape[0]//2, :, :] # Middle X slice
# Save slices as 2D images
imageio.imwrite('xy_slice.png', xy_slice)
imageio.imwrite('xz_slice.png', xz_slice)
imageio.imwrite('yz_slice.png', yz_slice)
# Apply 3D operations
# Gaussian smoothing (requires scipy)
try:
from scipy import ndimage
smoothed = ndimage.gaussian_filter(volume.astype(float), sigma=1.0)
imageio.volwrite('smoothed.tiff', smoothed.astype(volume.dtype))
except ImportError:
print("scipy required for filtering operations")
# Threshold volume
threshold = np.percentile(volume, 75)
binary_volume = (volume > threshold).astype(np.uint8) * 255
imageio.volwrite('binary.tiff', binary_volume)Convert between different 3D formats:
def convert_volume_format(input_file, output_file, **kwargs):
"""Convert volume between formats."""
volume = imageio.volread(input_file)
imageio.volwrite(output_file, volume, **kwargs)
# Convert DICOM to TIFF
convert_volume_format('scan.dcm', 'scan.tiff', compression='lzw')
# Convert with data type change
volume = imageio.volread('float_volume.tiff')
# Convert float to 16-bit integer
volume_16bit = (volume * 65535).astype(np.uint16)
imageio.volwrite('volume_16bit.tiff', volume_16bit)Process 4D datasets (3D volumes over time):
# Load time series
time_volumes = imageio.mvolread('4d_dataset.tiff')
print(f"Time points: {len(time_volumes)}")
# Analyze temporal changes
mean_intensities = []
for t, volume in enumerate(time_volumes):
mean_intensity = volume.mean()
mean_intensities.append(mean_intensity)
print(f"Time {t}: mean intensity = {mean_intensity:.2f}")
# Create maximum intensity projection over time
max_projection = np.maximum.reduce(time_volumes)
imageio.volwrite('temporal_max_projection.tiff', max_projection)
# Extract and save specific time points
for t in [0, len(time_volumes)//2, -1]: # First, middle, last
imageio.volwrite(f'timepoint_{t:03d}.tiff', time_volumes[t])Volume data can be memory-intensive. Consider these strategies:
# Check expected memory usage before loading
import os
file_size = os.path.getsize('large_volume.tiff')
print(f"File size: {file_size / (1024**3):.2f} GB")
# For very large volumes, consider:
# 1. Using memtest limits
try:
volume = imageio.volread('large_volume.tiff', memtest='4GB')
except RuntimeError:
print("Volume too large, use alternative approach")
# 2. Processing in chunks (if supported by format)
# 3. Using readers for sequential access
reader = imageio.get_reader('large_volume.tiff')
# Process slice by slice if reader supports itChoose appropriate data types for memory efficiency:
# Load volume and check data type
volume = imageio.volread('volume.tiff')
print(f"Original dtype: {volume.dtype}, size: {volume.nbytes} bytes")
# Convert to smaller data type if range allows
if volume.max() <= 255:
volume_uint8 = volume.astype(np.uint8)
print(f"As uint8: {volume_uint8.nbytes} bytes")
imageio.volwrite('volume_uint8.tiff', volume_uint8)
# Use 16-bit for better precision with smaller size than float32
if volume.dtype == np.float32 and 0 <= volume.min() and volume.max() <= 1:
volume_uint16 = (volume * 65535).astype(np.uint16)
imageio.volwrite('volume_uint16.tiff', volume_uint16)Install with Tessl CLI
npx tessl i tessl/pypi-imageio