Created
January 23, 2025 22:27
-
-
Save kwsp/e5a104d5b5661f682c4d26968b6f0445 to your computer and use it in GitHub Desktop.
to_nrrd.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
dependencies: numpy pillow pynrrd tqdm | |
""" | |
from PIL import Image | |
from pathlib import Path | |
from tqdm import tqdm | |
import nrrd | |
import numpy as np | |
input_folder = Path.home() / ("Desktop/20240927 boxes/ARPAM123924_PLA_box") | |
image_name = "USradial.tiff" | |
output_file = input_folder / Path(image_name).with_suffix(".nrrd") | |
print(output_file) | |
def load_images(folder: Path) -> np.ndarray: | |
"""Load images from a folder and return a 3D np.ndarray""" | |
dtype = np.uint8 | |
image_files = sorted(folder.glob("**/" + image_name)) | |
if not image_files: | |
raise ValueError(f"No TIFF files found in folder {folder}") | |
first_image = Image.open(image_files[0]) | |
width, height = first_image.size | |
width //= 2 | |
height //= 2 | |
image_stack = np.zeros((len(image_files), height, width), dtype=dtype) | |
for i, image_file in enumerate(tqdm(image_files)): | |
image = Image.open(image_file) | |
image = image.resize((width, height)) | |
image_stack[i] = np.array(image) | |
return image_stack | |
def main(): | |
image_stack = load_images(input_folder) | |
nrrd.write(str(output_file), image_stack) | |
print(f"NRRD file saved as {output_file}") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment