### Applying pystackreg Transformation Matrices with skimage Source: https://github.com/glichtner/pystackreg/blob/master/docs/tutorial.rst This example illustrates how to reuse transformation matrices generated by pystackreg with the `skimage` library. It iterates through the saved `tmats`, applies each transformation to individual images in the stack using `skimage.transform.AffineTransform` and `skimage.transform.warp`, and then displays the averaged results. This highlights the interoperability of pystackreg's output. ```ipython3 f, ax = plt.subplots(2, int(np.ceil((len(transformations)+1)/2)), figsize=(20, 12)) ax = ax.ravel() ax[0].imshow(overlay_images(unreg, aggregator=np.mean), cmap='gray') ax[0].set_title('Original (overlay)') ax[0].axis('off') for i, (name, tf) in enumerate(transformations.items()): if name == 'BILINEAR': # Bilinear transformation is not an affine transformation, we can't use the transformation matrix here continue # copy the unregistered image reg = unreg.copy() for i_img in range(unreg.shape[0]): # get skimage's AffineTransform object tform = transform.AffineTransform(matrix=tmats[i][i_img, :, :]) # transform image using the saved transformation matrix reg[i_img, :, :] = transform.warp(reg[i_img, :, :], tform) ax[i+1].imshow(overlay_images(reg, aggregator=np.mean), cmap='gray') ax[i+1].set_title(name + ' (overlay)') ax[i+1].axis('off') # turn off axis in remaining plots for i in range(len(transformations), len(ax)): ax[i].axis('off') ``` -------------------------------- ### Apply Various Image Transformations with pyStackReg Source: https://github.com/glichtner/pystackreg/blob/master/README.rst This example demonstrates how to load two images and apply all five supported transformation types (translation, rigid body, scaled rotation, affine, and bilinear) using the `StackReg` class. It shows how to initialize `StackReg` with a specific transformation type and then use `register_transform` to apply it. ```python from pystackreg import StackReg from skimage import io #load reference and "moved" image ref = io.imread('some_original_image.tif') mov = io.imread('some_changed_image.tif') #Translational transformation sr = StackReg(StackReg.TRANSLATION) out_tra = sr.register_transform(ref, mov) #Rigid Body transformation sr = StackReg(StackReg.RIGID_BODY) out_rot = sr.register_transform(ref, mov) #Scaled Rotation transformation sr = StackReg(StackReg.SCALED_ROTATION) out_sca = sr.register_transform(ref, mov) #Affine transformation sr = StackReg(StackReg.AFFINE) out_aff = sr.register_transform(ref, mov) #Bilinear transformation sr = StackReg(StackReg.BILINEAR) out_bil = sr.register_transform(ref, mov) ``` -------------------------------- ### Check pystackreg Version Source: https://github.com/glichtner/pystackreg/blob/master/docs/tutorial.rst Prints the installed version of the pystackreg library to confirm its availability and version number. This is useful for debugging and ensuring compatibility. ```python print(pystackreg.__version__) ``` -------------------------------- ### Install pyStackReg via Pip Source: https://github.com/glichtner/pystackreg/blob/master/README.rst This snippet provides the command to install the pyStackReg library using the Pip package manager. ```python pip install pystackreg ``` -------------------------------- ### Install pyStackReg via Conda Source: https://github.com/glichtner/pystackreg/blob/master/README.rst This snippet provides the command to install the pyStackReg library using the Conda package manager from the conda-forge channel. ```python conda install pystackreg -c conda-forge ``` -------------------------------- ### Separate Registration from Transformation in pyStackReg Source: https://github.com/glichtner/pystackreg/blob/master/README.rst This example illustrates how to perform image registration and transformation as separate steps. It shows how to register one image to another using `sr.register()` and then implicitly use those calculated parameters for subsequent operations, which is useful for applying transformations across different image channels or complex workflows. ```python from pystackreg import StackReg from skimage import io img0 = io.imread('some_multiframe_image.tif') img1 = io.imread('another_multiframe_image.tif') # img0.shape: frames x width x height (3D) sr = StackReg(StackReg.RIGID_BODY) # register 2nd image to 1st sr.register(img0[0, :, :], img0[1,:,:]) ``` -------------------------------- ### Python Project Dependencies List Source: https://github.com/glichtner/pystackreg/blob/master/docs/requirements.txt Specifies the Python packages and their minimum required versions. These are typically installed via `pip` from a `requirements.txt` file to set up the project's development or runtime environment. ```Python sphinx>=1.3 sphinx-rtd-theme sphinx_autodoc_typehints ``` -------------------------------- ### Visualize Original Image Stack Overlay Source: https://github.com/glichtner/pystackreg/blob/master/docs/tutorial.rst Generates and displays an overlay image by averaging all frames in the original, unregistered image stack. This visualization highlights the blurriness and misalignment present across the entire stack before any registration is applied. ```python f, ax = plt.subplots(1, 1, figsize=(10, 9)) ax.imshow(overlay_images(unreg), cmap='gray') ax[0].set_title('overlay (original)') ax[0].axis('off'); ``` -------------------------------- ### Registering Image Stacks with pystackreg Transformations Source: https://github.com/glichtner/pystackreg/blob/master/docs/tutorial.rst This snippet demonstrates applying various transformation types (e.g., BILINEAR, RIGID_BODY) provided by pystackreg to register images in a stack. It iterates through predefined transformations, registers the stack using `sr.register_stack`, and visualizes the averaged registered images. The transformation matrices are saved in `tmats` for subsequent use. ```ipython3 f, ax = plt.subplots(2, int(np.ceil((len(transformations)+1)/2)), figsize=(20, 12)) ax = ax.ravel() ax[0].imshow(overlay_images(unreg, aggregator=np.mean), cmap='gray') ax[0].set_title('Original (overlay)') ax[0].axis('off') # store transformation matrices for later use in this variable tmats = [] for i, (name, tf) in enumerate(transformations.items()): sr = StackReg(tf) reference = 'first' if name == 'BILINEAR' else 'previous' tmat = sr.register_stack(unreg, axis=0, reference=reference, verbose=True) reg = sr.transform_stack(unreg) tmats.append(tmat) ax[i+1].imshow(overlay_images(reg, aggregator=np.mean), cmap='gray') ax[i+1].set_title(name + ' (overlay)') ax[i+1].axis('off') ``` -------------------------------- ### Registering and Transforming Entire Image Stacks with PyStackReg Source: https://github.com/glichtner/pystackreg/blob/master/README.rst Illustrates various methods for registering and transforming entire image stacks using `StackReg`. It covers different reference options like 'previous', 'first', 'mean', and using a subset of frames or a moving average for registration. This functionality requires the `pystackreg` and `skimage` libraries. ```Python from pystackreg import StackReg from skimage import io img0 = io.imread('some_multiframe_image.tif') # 3 dimensions : frames x width x height sr = StackReg(StackReg.RIGID_BODY) # register each frame to the previous (already registered) one # this is what the original StackReg ImageJ plugin uses out_previous = sr.register_transform_stack(img0, reference='previous') # register to first image out_first = sr.register_transform_stack(img0, reference='first') # register to mean image out_mean = sr.register_transform_stack(img0, reference='mean') # register to mean of first 10 images out_first10 = sr.register_transform_stack(img0, reference='first', n_frames=10) # calculate a moving average of 10 images, then register the moving average to the mean of # the first 10 images and transform the original image (not the moving average) out_moving10 = sr.register_transform_stack(img0, reference='first', n_frames=10, moving_average = 10) ``` -------------------------------- ### Visualize Original Reference and Shifted Images Source: https://github.com/glichtner/pystackreg/blob/master/docs/tutorial.rst Generates a matplotlib figure to visually compare the reference image, the shifted image, and an RGB composite overlay of both. This visualization clearly demonstrates the initial misalignment between the two images before any registration is applied. ```python f, ax = plt.subplots(1, 3, figsize=(20, 9)) before_reg = composite_images([ref, mov]) ax[0].imshow(ref, cmap='gray') ax[0].set_title('reference image') ax[0].axis('off') ax[1].imshow(mov, cmap='gray') ax[1].set_title('shifted image') ax[1].axis('off') ax[2].imshow(before_reg) ax[2].set_title('overlay (reference=red, shifted=green)') ax[2].axis('off'); ``` -------------------------------- ### Create and Reshape Test Data for pystackreg Source: https://github.com/glichtner/pystackreg/blob/master/docs/tutorial.rst Illustrates how to create a sample stack and then reshape it using `numpy.moveaxis` to place the frames axis at a non-default position (axis 2) for testing `pystackreg`'s axis handling. It includes verifying the initial and final shapes of the array. ```python unreg.shape ``` ```python unreg_axis = np.moveaxis(unreg, 0, 2) unreg_axis.shape ``` -------------------------------- ### Apply and Visualize Single Image Transformations Source: https://github.com/glichtner/pystackreg/blob/master/docs/tutorial.rst Iterates through various pystackreg transformation types, applying each to register the 'moved' image to the reference image. For each transformation, it displays the resulting overlay of the registered image on the reference, and for non-BILINEAR types, visualizes the effect of the transformation matrix on a rectangle. ```python f, ax = plt.subplots(5, 2, figsize=(16, 18)) for i, (name, tf) in enumerate(transformations.items()): sr = StackReg(tf) reg = sr.register_transform(ref, mov) reg = reg.clip(min=0) after_reg = composite_images([ref, reg]) ax[i][0].imshow(after_reg, cmap='gray', vmin=0, vmax=1) ax[i][0].set_title(name + ' (overlay on reference)') ax[i][0].axis('off') if name != 'BILINEAR': show_transformation(sr.get_matrix(), ax[i][1]) ax[i][1].set_title(name + ' (applied on a rectangle)') else: ax[i][1].axis('off') ``` -------------------------------- ### Convert Stack Data to uint16 Source: https://github.com/glichtner/pystackreg/blob/master/docs/tutorial.rst Demonstrates converting the data type of a registered stack to `uint16` using the `to_uint16` function and verifies the resulting data type and minimum value, showing the effect of the conversion on data range. ```python reg_int = to_uint16(reg) print(f"After using the to_uint16 function, the output has a datatype {reg_int.dtype} with a minimal value of {reg_int.min()}") ``` -------------------------------- ### Separating Registration and Transformation for Image Stacks in PyStackReg Source: https://github.com/glichtner/pystackreg/blob/master/README.rst Shows how to perform registration and transformation as separate steps, which is useful for applying transformations calculated from one image stack to another (e.g., different color channels). It also demonstrates saving and loading transformation matrices using NumPy and applying them with `skimage.transform`. This functionality requires `pystackreg`, `skimage`, and `numpy`. ```Python from pystackreg import StackReg from skimage import io img0 = io.imread('some_multiframe_image.tif') # 3 dimensions : frames x width x height img1 = io.imread('another_multiframe_image.tif') # same shape as img0 # both stacks must have the same shape assert img0.shape == img1.shape sr = StackReg(StackReg.RIGID_BODY) # register each frame to the previous (already registered) one # this is what the original StackReg ImageJ plugin uses tmats = sr.register_stack(img0, reference='previous') out = sr.transform_stack(img1) # tmats contains the transformation matrices -> they can be saved # and loaded at another time import numpy as np np.save('transformation_matrices.npy', tmats) tmats_loaded = np.load('transformation_matrices.npy') # make sure you use the correct transformation here! sr = StackReg(StackReg.RIGID_BODY) # transform stack using the tmats loaded from file sr.transform_stack(img1, tmats=tmats_loaded) # with the transformation matrices at hand you can also # use the transformation algorithms from other packages: from skimage import transform as tf out = np.zeros(img0.shape).astype(np.float) for i in range(tmats.shape[0]): out[i, :, :] = tf.warp(img1[i, :, :], tmats[i, :, :], order=3) ``` -------------------------------- ### Import pystackreg and Dependencies Source: https://github.com/glichtner/pystackreg/blob/master/docs/tutorial.rst Imports necessary libraries including os, sys, numpy, matplotlib, and skimage for general utilities, numerical operations, plotting, and image processing. It also imports the core StackReg class and the pystackreg module itself. ```python import os import sys import numpy as np from matplotlib import pyplot as plt from skimage import transform, io, exposure from pystackreg import StackReg import pystackreg ``` -------------------------------- ### Define Transformation Visualization Helper Source: https://github.com/glichtner/pystackreg/blob/master/docs/tutorial.rst Defines a helper function `show_transformation` to visualize the effect of a given transformation matrix on a simple rectangle. It plots both the original rectangle and its transformed counterpart, illustrating how the image coordinates are altered by the matrix. ```python def show_transformation(tmat, ax=None): if ax is None: _, ax = plt.subplots() p = np.array([[1,120,1], [1,1,1], [250, 1, 1], [250,120,1], [1,120,1]]) ax.plot(p[:, 0], p[:,1]) q=np.dot(p, tmat.T) ax.plot(q[:, 0], q[:,1]) ax.invert_xaxis() ax.invert_yaxis() ax.legend(['Original image', 'transformed image']) ``` -------------------------------- ### Define pystackreg Transformation Types Source: https://github.com/glichtner/pystackreg/blob/master/docs/tutorial.rst Creates a dictionary that maps descriptive string names to the corresponding transformation constants provided by the `StackReg` class. This allows for easy selection and iteration over different registration transformation models like TRANSLATION, RIGID_BODY, SCALED_ROTATION, AFFINE, and BILINEAR. ```python transformations = { 'TRANSLATION': StackReg.TRANSLATION, 'RIGID_BODY': StackReg.RIGID_BODY, 'SCALED_ROTATION': StackReg.SCALED_ROTATION, 'AFFINE': StackReg.AFFINE, 'BILINEAR': StackReg.BILINEAR } ``` -------------------------------- ### Load Sample Image Data Source: https://github.com/glichtner/pystackreg/blob/master/docs/tutorial.rst Loads a multi-frame TIFF image stack from a specified relative path ('../data/pc12-unreg.tif'). The loaded image data is then converted to a float type to prevent potential overflow issues during subsequent image processing and difference calculations. ```python data_path = os.path.join(os.getcwd(), '..', 'data') unreg = io.imread(os.path.join(data_path, 'pc12-unreg.tif')) # convert to float to prevent overflows when calculating differences images unreg = unreg.astype(np.float) ``` -------------------------------- ### Define Image Overlay Helper Function Source: https://github.com/glichtner/pystackreg/blob/master/docs/tutorial.rst Defines a utility function `overlay_images` to combine multiple images into a single overlay. It can optionally apply histogram equalization to each image and uses a specified aggregator (defaulting to numpy.mean) to combine the stacked images. ```python def overlay_images(imgs, equalize=False, aggregator=np.mean): if equalize: imgs = [exposure.equalize_hist(img) for img in imgs] imgs = np.stack(imgs, axis=0) return aggregator(imgs, axis=0) ``` -------------------------------- ### Implementing Custom Progress Callback for pystackreg Source: https://github.com/glichtner/pystackreg/blob/master/docs/tutorial.rst This snippet demonstrates how to provide a custom callback function to `pystackreg`'s registration methods (e.g., `register_transform_stack`) to monitor progress. The `show_progress` function accepts `current_iteration` and `end_iteration` parameters, allowing real-time feedback during the registration process. This is useful for long-running operations. ```ipython3 def show_progress(current_iteration, end_iteration): print(f"Registering {current_iteration} of {end_iteration} images") sr = StackReg(StackReg.RIGID_BODY) reg = sr.register_transform_stack(unreg, axis=0, progress_callback=show_progress) ``` -------------------------------- ### Converting pystackreg Output to uint16 and Handling Negative Values Source: https://github.com/glichtner/pystackreg/blob/master/docs/tutorial.rst This snippet addresses the `float` output and potential negative values from `pystackreg`'s transformation functions. It demonstrates how to use the `pystackreg.util.to_uint16()` utility function to convert the registered image stack to an unsigned 16-bit integer format, suitable for image display and storage, after ensuring non-negative values. ```ipython3 from pystackreg.util import to_uint16 sr = StackReg(StackReg.RIGID_BODY) reg = sr.register_transform_stack(unreg - unreg.min()) print(f"The output of the transform function has the datatype {reg.dtype} with a minimal value of {reg.min()}") ``` -------------------------------- ### Select Reference and Moved Images Source: https://github.com/glichtner/pystackreg/blob/master/docs/tutorial.rst Extracts two specific frames from the loaded `unreg` image stack to be used for single-image registration. The first frame (`unreg[0, :, :]`) is designated as the reference image, and the fifth frame (`unreg[4, :, :]`) is designated as the 'moved' image. ```python ref = unreg[0, :, :] mov = unreg[4, :, :] ``` -------------------------------- ### Define Image Composite Helper Function Source: https://github.com/glichtner/pystackreg/blob/master/docs/tutorial.rst Defines a utility function `composite_images` to create an RGB composite from multiple grayscale images. It normalizes pixel values to 0-1 and pads with black channels if fewer than three images are provided, making them suitable for display as an RGB image. ```python def composite_images(imgs, equalize=False, aggregator=np.mean): if equalize: imgs = [exposure.equalize_hist(img) for img in imgs] imgs = [img / img.max() for img in imgs] if len(imgs) < 3: imgs += [np.zeros(shape=imgs[0].shape)] * (3-len(imgs)) imgs = np.dstack(imgs) return imgs ``` -------------------------------- ### pystackreg.StackReg Class API Source: https://github.com/glichtner/pystackreg/blob/master/docs/reference/pystackreg.rst API documentation for the `StackReg` class, which is central to pystackreg for performing image registration and transformation operations. This class exposes methods for various registration algorithms. ```APIDOC Class: pystackreg.StackReg Description: Handles image stack registration and transformation. Members: (Detailed methods and properties would be listed here, e.g., register_stack, transform_image, etc.) ``` -------------------------------- ### Register Stack with Default pystackreg Parameters Source: https://github.com/glichtner/pystackreg/blob/master/docs/tutorial.rst Registers a stack using `pystackreg` with default parameters, demonstrating how `pystackreg` automatically identifies the frames axis and raises a warning if it differs from the expected default (axis 0). This highlights the library's axis detection capability. ```python sr = StackReg(StackReg.RIGID_BODY) sr.register_stack(unreg_axis); ``` -------------------------------- ### Transforming a Single Image Frame with PyStackReg Source: https://github.com/glichtner/pystackreg/blob/master/README.rst Demonstrates how to apply a previously calculated transformation to a single image frame using the `transform` method of a StackReg instance. This assumes `sr` (StackReg instance) and `img1` are already defined and a transformation has been registered. ```Python out = sr.transform(img1[1,:,:]) ``` -------------------------------- ### Transform Stack with Explicit Frames Axis Source: https://github.com/glichtner/pystackreg/blob/master/docs/tutorial.rst Transforms the registered stack using `pystackreg`, emphasizing the necessity of supplying the `axis` parameter again during transformation to match the axis used during registration and prevent errors. This ensures consistency across registration and transformation steps. ```python reg_axis = sr.transform_stack(unreg_axis, axis=2) ``` -------------------------------- ### Check Image Stack Length Source: https://github.com/glichtner/pystackreg/blob/master/docs/tutorial.rst Prints the total number of images (frames) present in the loaded `unreg` image stack. This confirms the dimensions of the dataset before proceeding with stack-level operations. ```python print(f"Number of images in the stack: {len(unreg)}") ``` -------------------------------- ### Register Stack with Explicit Frames Axis Source: https://github.com/glichtner/pystackreg/blob/master/docs/tutorial.rst Registers the stack using `pystackreg`, explicitly specifying the correct frames axis (axis 2) to avoid warnings and ensure proper registration when the frames axis is not the first dimension. This demonstrates how to override default axis detection. ```python sr.register_stack(unreg_axis, axis=2); ``` -------------------------------- ### pystackreg.util.to_uint16 Function API Source: https://github.com/glichtner/pystackreg/blob/master/docs/reference/pystackreg.rst API documentation for the `to_uint16` utility function within the `pystackreg.util` module. This function is typically used for converting numerical data to an unsigned 16-bit integer format, which is common in image processing. ```APIDOC Function: pystackreg.util.to_uint16 Description: Converts input data to an unsigned 16-bit integer type. Signature: to_uint16(data: numpy.ndarray) -> numpy.ndarray data: The input array to be converted. Returns: A new array with the data converted to uint16. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.