How to performs intensity image averaging

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

from timagetk.components.spatial_image import SpatialImage
from timagetk.io import imread
from timagetk.io.util import shared_data
from timagetk.algorithms.trsf import apply_trsf
from timagetk.algorithms.trsf import create_trsf
from timagetk.algorithms.trsf import inv_trsf
from timagetk.algorithms.averaging import images_averaging
/builds/J-gEBwyb/0/mosaic/timagetk/src/timagetk/components/labelled_image.py:31: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
  from tqdm.autonotebook import tqdm
def imshow(ax, spim, title=""):
    spim_extent = [-0.5, spim.get_extent('x') - 0.5, spim.get_extent('y') - 0.5, -0.5]
    fig = ax.imshow(spim, cmap='gray', extent=spim_extent, vmin=0, vmax=255)
    ax.xaxis.tick_top()
    if title != "":
        ax.set_title(title)
    else:
        try:
            ax.set_title(f"{spim.filename}")
        except:
            pass
    return fig

Load the reference image

ref_img = imread(shared_data('p58-t0-a0.lsm', 'p58'))
ERROR    [timagetk.io.image] Could not find file `/builds/J-gEBwyb/0/mosaic/timagetk/data/p58/p58-t0-a0.lsm`!

Create the floating image with a rigid transformation

r2f_trsf = create_trsf('random', template_img=ref_img, trsf_type='rigid', seed=12, angle_range=[0.0, 0.1])
flo_img = apply_trsf(ref_img, r2f_trsf, template_img=ref_img)
---------------------------------------------------------------------------
NotImplementedError                       Traceback (most recent call last)
Cell In[5], line 2
      1 r2f_trsf = create_trsf('random', template_img=ref_img, trsf_type='rigid', seed=12, angle_range=[0.0, 0.1])
----> 2 flo_img = apply_trsf(ref_img, r2f_trsf, template_img=ref_img)

File /builds/J-gEBwyb/0/mosaic/timagetk/src/timagetk/algorithms/trsf.py:233, in apply_trsf(image, trsf, template_img, interpolation, **kwargs)
    231 from timagetk.components.image import get_image_attributes
    232 attr = get_image_attributes(image, exclude=["shape", "voxelsize"], extra=['filename'])
--> 233 Image = image_class(image)
    235 # If a MultiChannelImage and a 'single_channel' is requested, extract the SpatialImage
    236 ch_name = ''

File /builds/J-gEBwyb/0/mosaic/timagetk/src/timagetk/components/image.py:96, in image_class(image)
     94 else:
     95     msg = "Input `image` is not an Image type: {}!"
---> 96     raise NotImplementedError(msg.format(clean_type(image)))

NotImplementedError: Input `image` is not an Image type: NoneType!

Invert the transformation to create a registered image

f2r_trsf = inv_trsf(r2f_trsf)
reg_img = apply_trsf(flo_img, f2r_trsf, template_img=ref_img)

Create the masks

ref_mask = SpatialImage(np.ones_like(ref_img))
flo_mask = apply_trsf(SpatialImage(np.ones_like(flo_img)), f2r_trsf, template_img=ref_img, interpolation='nearest')
np.unique(ref_mask)
np.unique(flo_mask)

Compute the average image without masks

unmasked_avimg = images_averaging([ref_img, reg_img], 'mean')

Compute the average image with masks

masked_avimg = images_averaging([ref_img, reg_img], 'mean', masks=[ref_mask, flo_mask])

Plot the two averaged images

import matplotlib.gridspec as gridspec
from matplotlib import colors

fig = plt.figure(figsize=(15, 9), constrained_layout=True)
fig.set_dpi(160)
fig.suptitle("Masks usage in image averaging method")
# Create two panels
gs = gridspec.GridSpec(ncols=2, nrows=1, figure=fig)
unmask_ax = fig.add_subplot(gs[0, 0])
mask_ax = fig.add_subplot(gs[0, 1])

mid_z_sl = unmasked_avimg.get_shape('z')//2.
images = []
images.append(imshow(unmask_ax, unmasked_avimg.get_slice(mid_z_sl), title="Unmasked average"))
images.append(imshow(mask_ax, masked_avimg.get_slice(mid_z_sl), title="Masked average"))

# Find the min and max of all colors for use in setting the color scale.
vmin = min(image.get_array().min() for image in images)
vmax = max(image.get_array().max() for image in images)
norm = colors.Normalize(vmin=vmin, vmax=vmax)
for im in images:
    im.set_norm(norm)
# Add a colorbar at the bottom
fig.colorbar(images[0], ax=[unmask_ax, mask_ax], orientation='horizontal', fraction=.1)