A comprehensive collection of algorithms and routines for electron microscopy data analysis and simulation.
—
Comprehensive image processing capabilities for electron microscopy data including correlation-based alignment, peak detection, Fourier operations, distortion correction, and mathematical fitting functions.
Functions for aligning images and image stacks using cross-correlation and phase-correlation techniques.
def image_cross_corr(image, reference, real_filter=1, k_filter=1):
"""
Calculate cross-correlation between two images.
Parameters:
- image: numpy.ndarray, source image to align
- reference: numpy.ndarray, reference image to align to
- real_filter: numpy.ndarray, real space filter (default=1)
- k_filter: numpy.ndarray, Fourier space filter (default=1)
Returns:
numpy.ndarray: Cross-correlation result
"""
def image_correlate(image1, image2, **kwargs):
"""
Align images using cross-correlation.
Parameters:
- image1: numpy.ndarray, reference image
- image2: numpy.ndarray, image to align
Returns:
numpy.ndarray: Aligned image
"""
def image_phase_correlate(image, reference, real_filter=1, k_filter=1, shift_func='shift', verbose=False):
"""
Align images using phase-correlation.
Parameters:
- image: numpy.ndarray, image to align
- reference: numpy.ndarray, reference image to align to
- real_filter: numpy.ndarray, real space filter (default=1)
- k_filter: numpy.ndarray, Fourier space filter (default=1)
- shift_func: str, shift method ('shift' or 'roll')
- verbose: bool, plot cross-correlation for debugging
Returns:
tuple: (aligned_image, shifts) - aligned image and applied shifts
"""
def stack_align(image_stack, **kwargs):
"""
Align stack of images using cross-correlation.
Parameters:
- image_stack: numpy.ndarray, 3D array of images (z, y, x)
Returns:
numpy.ndarray: Aligned image stack
"""Basic array manipulation and rebinning functions for data processing.
def rebin(im, f, funcType='sum'):
"""
Rebin 2D arrays with sum or mean reduction.
Parameters:
- im: numpy.ndarray, input 2D array
- f: int, factor to rebin by (must be integer)
- funcType: str, 'sum' or 'mean' reduction
Returns:
numpy.ndarray: Rebinned array
"""Functions for calculating image moments, centroids, and geometric properties.
def moments(image, order=3):
"""
Calculate raw image moments.
Parameters:
- image: numpy.ndarray, input image
- order: int, maximum moment order
Returns:
numpy.ndarray: Raw moments array
"""
def moments_central(image, center=None, order=3):
"""
Calculate central image moments.
Parameters:
- image: numpy.ndarray, input image
- center: tuple, center coordinates (y, x)
- order: int, maximum moment order
Returns:
numpy.ndarray: Central moments array
"""
def centroid(moments_raw):
"""
Find centroid from raw moments.
Parameters:
- moments_raw: numpy.ndarray, raw moments from moments()
Returns:
tuple: Centroid coordinates (y, x)
"""
def moment_angle(moments_central):
"""
Calculate orientation angle from central moments.
Parameters:
- moments_central: numpy.ndarray, central moments
Returns:
float: Orientation angle in radians
"""Precise image transformations using FFT-based operations.
def shearImage(image, shear_x=0, shear_y=0):
"""
Exact shear using FFT frequency space.
Parameters:
- image: numpy.ndarray, input image
- shear_x: float, shear factor in x direction
- shear_y: float, shear factor in y direction
Returns:
numpy.ndarray: Sheared image
"""
def shiftImage(image, shift_x=0, shift_y=0):
"""
Exact shift using FFT frequency space.
Parameters:
- image: numpy.ndarray, input image
- shift_x: float, shift in x direction (pixels)
- shift_y: float, shift in y direction (pixels)
Returns:
numpy.ndarray: Shifted image
"""
def rotateImage(image, angle):
"""
Exact rotation using three shears.
Parameters:
- image: numpy.ndarray, input image
- angle: float, rotation angle in radians
Returns:
numpy.ndarray: Rotated image
"""
def bandpass_filter(image, low_freq, high_freq):
"""
Apply bandpass filter in frequency domain.
Parameters:
- image: numpy.ndarray, input image
- low_freq: float, low frequency cutoff
- high_freq: float, high frequency cutoff
Returns:
numpy.ndarray: Filtered image
"""2D and 3D peak finding algorithms with lattice analysis capabilities.
def peakFind2D(image, sigma=1, threshold=0.1, min_distance=1):
"""
2D peak detection in images.
Parameters:
- image: numpy.ndarray, input 2D image
- sigma: float, Gaussian filter sigma
- threshold: float, peak threshold
- min_distance: int, minimum distance between peaks
Returns:
numpy.ndarray: Peak coordinates (N, 2) array
"""
def peakFind3D(volume, sigma=1, threshold=0.1, min_distance=1):
"""
3D peak detection in volumes.
Parameters:
- volume: numpy.ndarray, input 3D volume
- sigma: float, Gaussian filter sigma
- threshold: float, peak threshold
- min_distance: int, minimum distance between peaks
Returns:
numpy.ndarray: Peak coordinates (N, 3) array
"""
def enforceMinDist(peaks, min_distance):
"""
Enforce minimum distance between peaks.
Parameters:
- peaks: numpy.ndarray, peak coordinates
- min_distance: float, minimum distance
Returns:
numpy.ndarray: Filtered peak coordinates
"""
def remove_xrays(peaks, image, threshold=3.0):
"""
Remove X-ray artifacts from peak list.
Parameters:
- peaks: numpy.ndarray, peak coordinates
- image: numpy.ndarray, source image
- threshold: float, removal threshold
Returns:
numpy.ndarray: Cleaned peak coordinates
"""Functions for generating, refining, and analyzing crystal lattices from peak data.
def lattice2D(peaks, lattice_params):
"""
Generate 2D lattice from parameters.
Parameters:
- peaks: numpy.ndarray, reference peaks
- lattice_params: dict, lattice parameters
Returns:
numpy.ndarray: Generated lattice points
"""
def lattice3D(peaks, lattice_params):
"""
Generate 3D lattice from parameters.
Parameters:
- peaks: numpy.ndarray, reference peaks
- lattice_params: dict, lattice parameters
Returns:
numpy.ndarray: Generated lattice points
"""
def refineLattice2D(peaks, initial_params):
"""
Refine 2D lattice parameters.
Parameters:
- peaks: numpy.ndarray, experimental peaks
- initial_params: dict, initial lattice parameters
Returns:
dict: Refined lattice parameters
"""
def refineLattice3D(peaks, initial_params):
"""
Refine 3D lattice parameters.
Parameters:
- peaks: numpy.ndarray, experimental peaks
- initial_params: dict, initial lattice parameters
Returns:
dict: Refined lattice parameters
"""
def match_lattice_peaks(experimental_peaks, theoretical_lattice):
"""
Match experimental peaks to theoretical lattice.
Parameters:
- experimental_peaks: numpy.ndarray, detected peaks
- theoretical_lattice: numpy.ndarray, theoretical positions
Returns:
dict: Matching results and statistics
"""
def calculate_unit_cell(peaks, lattice_vectors):
"""
Calculate unit cell parameters from peaks.
Parameters:
- peaks: numpy.ndarray, lattice peaks
- lattice_vectors: numpy.ndarray, lattice vectors
Returns:
dict: Unit cell parameters
"""Multi-dimensional Gaussian functions and mathematical models for fitting.
def gauss1D(x, amplitude, center, sigma, offset=0):
"""
1D Gaussian function.
Parameters:
- x: numpy.ndarray, coordinate array
- amplitude: float, peak amplitude
- center: float, peak center
- sigma: float, standard deviation
- offset: float, baseline offset
Returns:
numpy.ndarray: Gaussian values
"""
def gauss2D(coords, amplitude, center_x, center_y, sigma_x, sigma_y, offset=0):
"""
2D Gaussian function.
Parameters:
- coords: tuple, (x, y) coordinate arrays
- amplitude: float, peak amplitude
- center_x: float, x center coordinate
- center_y: float, y center coordinate
- sigma_x: float, x standard deviation
- sigma_y: float, y standard deviation
- offset: float, baseline offset
Returns:
numpy.ndarray: 2D Gaussian values
"""
def gauss3D(coords, amplitude, center_x, center_y, center_z,
sigma_x, sigma_y, sigma_z, offset=0):
"""
3D Gaussian function.
Parameters:
- coords: tuple, (x, y, z) coordinate arrays
- amplitude: float, peak amplitude
- center_x: float, x center coordinate
- center_y: float, y center coordinate
- center_z: float, z center coordinate
- sigma_x: float, x standard deviation
- sigma_y: float, y standard deviation
- sigma_z: float, z standard deviation
- offset: float, baseline offset
Returns:
numpy.ndarray: 3D Gaussian values
"""
def voigt(x, amplitude, center, sigma, gamma):
"""
Voigt peak function for fitting.
Parameters:
- x: numpy.ndarray, coordinate array
- amplitude: float, peak amplitude
- center: float, peak center
- sigma: float, Gaussian width
- gamma: float, Lorentzian width
Returns:
numpy.ndarray: Voigt profile values
"""
def fit_peaks_gauss2d(image, peaks, fit_region_size=10):
"""
Fit 2D Gaussian peaks to image data.
Parameters:
- image: numpy.ndarray, input image
- peaks: numpy.ndarray, initial peak positions
- fit_region_size: int, region size for fitting
Returns:
dict: Fitted parameters for each peak
"""Functions for correcting lens distortions and geometric aberrations.
def optimize_center(points, initial_center):
"""
Optimize center position for distortion correction.
Parameters:
- points: numpy.ndarray, calibration points
- initial_center: tuple, initial center guess
Returns:
tuple: Optimized center coordinates
"""
def optimize_distortion(points, center, initial_params):
"""
Optimize distortion parameters.
Parameters:
- points: numpy.ndarray, calibration points
- center: tuple, distortion center
- initial_params: dict, initial distortion parameters
Returns:
dict: Optimized distortion parameters
"""
def correct_distortion(image, distortion_params):
"""
Correct image distortion.
Parameters:
- image: numpy.ndarray, input image
- distortion_params: dict, distortion correction parameters
Returns:
numpy.ndarray: Corrected image
"""Functions for analyzing radial intensity profiles in images.
def calc_radialprofile(image, center, max_radius=None):
"""
Calculate radial intensity profile.
Parameters:
- image: numpy.ndarray, input image
- center: tuple, center coordinates (y, x)
- max_radius: float, maximum radius for profile
Returns:
tuple: (radii, intensities) arrays
"""
def fit_radialprofile(radii, intensities, model_func):
"""
Fit model to radial profile.
Parameters:
- radii: numpy.ndarray, radial coordinates
- intensities: numpy.ndarray, intensity values
- model_func: callable, fitting function
Returns:
dict: Fitted parameters and statistics
"""
def run_singleImage(image, center_guess=None):
"""
Complete radial profile analysis for single image.
Parameters:
- image: numpy.ndarray, input image
- center_guess: tuple, initial center guess
Returns:
dict: Analysis results including profile and fits
"""Functions for finding local intensity maxima in images.
def local_max(image, min_distance=1, threshold_abs=None):
"""
Find local maxima in image.
Parameters:
- image: numpy.ndarray, input image
- min_distance: int, minimum distance between maxima
- threshold_abs: float, absolute intensity threshold
Returns:
numpy.ndarray: Coordinates of local maxima
"""import ncempy.algo as algo
# Align two images using cross-correlation
reference = data1['data']
moving = data2['data']
aligned = algo.image_correlate(moving, reference)
# Align entire image stack
stack = image_series # 3D array (frames, y, x)
aligned_stack = algo.stack_align(stack)import ncempy.algo as algo
# Find peaks in diffraction pattern
peaks = algo.peakFind2D(diffraction_image, sigma=2, threshold=0.1)
# Generate theoretical lattice
lattice_params = {'a': 5.0, 'b': 5.0, 'angle': 90.0}
theoretical = algo.lattice2D(peaks[:10], lattice_params)
# Refine lattice parameters
refined_params = algo.refineLattice2D(peaks, lattice_params)import ncempy.algo as algo
# Fit 2D Gaussian to peaks
fitted_peaks = algo.fit_peaks_gauss2d(image, peak_positions)
# Extract peak parameters
for i, peak in enumerate(fitted_peaks):
print(f"Peak {i}: amplitude={peak['amplitude']:.3f}")Install with Tessl CLI
npx tessl i tessl/pypi-ncempy