Besides, if you want to generate the 3D volume with the downloaded slices:
import numpy as np
import tifffile
from pathlib import Path
def stack_tiff_slices_with_spacing_glob(
directory,
pattern="*.tif",
axis=1,
spacing=20,
sort_files=True
):
"""
Load 2D TIFF slices from files matching pattern in directory and create a 3D volume with each slice spaced along the axis.
Args:
directory (str or Path): Directory containing TIFF files.
pattern (str): Glob pattern for TIFF files (default: "*.tif").
axis (int): Axis along which to space slices (default: 1, y-axis).
spacing (int): Number of positions between slices (default: 20).
sort_files (bool): Whether to sort file list (default: True).
Returns:
np.ndarray: 3D volume with spaced TIFF slices.
list: List of input file paths (in order used).
"""
dir_path = Path(directory)
files = list(dir_path.glob(pattern))
if sort_files:
files = sorted(files)
if not files:
raise ValueError("No files found matching pattern.")
slices = [tifffile.imread(str(f)) for f in files]
first_shape = slices[0].shape
for i, arr in enumerate(slices):
if arr.shape != first_shape:
raise ValueError(f"Slice {i} shape {arr.shape} does not match {first_shape}")
n_slices = len(slices)
vol_shape = list(first_shape)
vol_shape.insert(axis, (n_slices - 1) * spacing + 1)
volume = np.zeros(vol_shape, dtype=slices[0].dtype)
for i, slc in enumerate(slices):
idx = [slice(None)] * len(vol_shape)
idx[axis] = i * spacing
volume[tuple(idx)] = slc
return volume, files
# Example usage:
# vol, file_list = stack_tiff_slices_with_spacing_glob("/path/to/dir", pattern="*.tif", axis=1, spacing=20)
# tifffile.imwrite("/path/to/dir/3dvolume.tif",vol)