Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Reduce and stitch Operetta microscope images
#!/usr/bin/env python
"""
Max-reduce and stitch microscopy images into one stitched one.
Requirements:
`pip install numpy matplotlib tifffile`
"""
from pathlib import Path
import numpy as np
import tifffile
import matplotlib.pyplot as plt
_dir = Path("data") / "experiment_5"
well = "r02c02"
h, w = 2113, 2117
rois = np.asarray([
np.asarray([
tifffile.imread(
_dir / f"{well}f0{f}p{str(z).zfill(2)}-ch1sk1fk1fl1.tiff"
)
for z in range(1, 12)]).max(axis=0) # iterate over z-stack]
for f in range(1, 5) # iterate over fields of view
]
) # shape: (field, X, Y)
# reorder rois
rois = rois[(0, 1, 3, 2), :, :]
# stitch and mean normalize ROIs
means = rois.mean((1, 2))
stitched = np.empty((h * 2, w * 2))
stitched[:h, :w] = (rois[0][:h, :w]) - means[0]
stitched[:h, w:] = (rois[1][:h, :w]) - means[1]
stitched[h:, :w] = (rois[2][:h, :w]) - means[2]
stitched[h:, w:] = (rois[3][:h, :w]) - means[3]
stitched += abs(stitched.min())
# write stitched as tiff
tifffile.imsave(_dir / f"{well}_max_stitched.tiff", stitched)
# plot
fig, axes = plt.subplots(
2, 3,
gridspec_kw=dict(width_ratios=(0.25, 0.25, 0.5), height_ratios=(0.5, 0.5)),
tight_layout=True,
)
gs = fig.axes[0].get_gridspec()
axes[0, -1].remove()
axes[1, -1].remove()
bigax = fig.add_subplot(gs[:, 2])
for i, (ax, arr) in enumerate(zip(axes[:2, :2].flat, rois)):
ax.imshow(arr, cmap="binary_r", rasterized=True)
ax.set(title=f"ROI {i}")
for ax in axes.flatten().tolist() + [bigax]:
ax.axis("off")
bigax.imshow(stitched, cmap="binary_r", rasterized=True)
bigax.set(title="Stitched")
fig.savefig(f"stitching_demo.{well}.pdf", bbox_inches="tight", dpi=300)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment