Skip to content

Instantly share code, notes, and snippets.

@sminot
Created November 8, 2024 17:58
Show Gist options
  • Save sminot/e30d467a1707f81d4e8391aa82a16758 to your computer and use it in GitHub Desktop.
Save sminot/e30d467a1707f81d4e8391aa82a16758 to your computer and use it in GitHub Desktop.
Convert a numpy array (.npz) to TIFF
#!/usr/bin/env python3
import click
import tifffile
import numpy as np
def convert_npz_to_tiff(input_file, output_file, pixelsize=0.05):
data = np.load(input_file)
# Convert the float64 to uint16 by dividing the float64 by the maximum value for each channel and multiplying by 65535
img = np.zeros((data["img"].shape[0], data["img"].shape[1], data["img"].shape[2]), dtype='uint16')
for i in range(data["img"].shape[2]):
img[:, :, i] = (data["img"][:, :, i] / np.max(data["img"][:, :, i]) * 65535).astype('uint16')
# Move the last dimension to the first dimension
img = np.moveaxis(img, -1, 0)
tifffile.imwrite(
output_file,
img,
shape=img.shape,
dtype='uint16',
# photometric='minisblack',
metadata={'axes': 'CYX', "Channel": {"Name": data["ch"].tolist()}},
)
@click.command()
@click.argument('input_file', type=click.Path(exists=True))
@click.argument('output_file', type=click.Path())
def main(input_file, output_file):
convert_npz_to_tiff(input_file, output_file)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment