Skip to content

Instantly share code, notes, and snippets.

@Yu-AnChen
Created June 8, 2021 22:35
Show Gist options
  • Save Yu-AnChen/6c4132512362b61d2ef210444e3e059f to your computer and use it in GitHub Desktop.
Save Yu-AnChen/6c4132512362b61d2ef210444e3e059f to your computer and use it in GitHub Desktop.
Write pyramidal ome-tiff using tifffile with channel names and crop positions
import tifffile
import numpy as np
def per_channel_per_tile(img, tile=(1024, 1024)):
num_channels, num_rows, num_columns = img.shape
h, w = tile
for c in range(num_channels):
for y in range(0, num_rows, h):
for x in range(0, num_columns, w):
yield img[c, y:y+h, x:x+w]
img = (
np
.arange(1000*1000*10, dtype='uint8')
.reshape((10, 1000, 1000))
)
num_channels, _, _ = img.shape
tile_shape = (256, 256)
options = dict(
dtype=img.dtype,
tile=tile_shape
)
metadata = {
'Pixels': {'PhysicalSizeX': 0.65, 'PhysicalSizeXUnit': '\u00b5m', 'PhysicalSizeY': 0.65, 'PhysicalSizeYUnit': '\u00b5m'},
'Channel': {'Name': [f'Channel {i+1}' for i in range(num_channels)]},
'Plane': {'PositionX': [123]*num_channels, 'PositionY': [456]*num_channels}
}
with tifffile.TiffWriter('temp.ome.tif', bigtiff=True) as tif:
tif.write(
data=per_channel_per_tile(img, tile=tile_shape),
metadata=metadata,
software='Software name',
shape=img.shape,
subifds=2,
**options
)
tif.write(
data=per_channel_per_tile(img[:, ::2, ::2], tile=tile_shape),
shape=img[:, ::2, ::2].shape,
subfiletype=1,
**options
)
tif.write(
data=per_channel_per_tile(img[:, ::4, ::4], tile=tile_shape),
shape=img[:, ::4, ::4].shape,
subfiletype=1,
**options
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment