microscopy_data_analysis package

Submodules

microscopy_data_analysis.data_formats_io module

submodule focussed on dataformats

microscopy_data_analysis.data_formats_io.convert_dm4_to_png(dm4_filepaths, logscale=False)[source]
microscopy_data_analysis.data_formats_io.get_SEMtif_with_metadata(filepath)[source]
microscopy_data_analysis.data_formats_io.get_dm4_with_metadata(filepath)[source]

read a dm4-file and return the variables data and metadata as dictionaries data includes everything immediately important metadata contains all other information

Important missing parameters are electric current and only for spectra: acquisition time and acquisition date are missing

Args:
filepath (string):

relative or absolute path to the file.

Returns:
data (dict):

data[“data”] yields the data other keywords contain the most important metadata.

metadata (dict):

Dictionary containing further metadata.

microscopy_data_analysis.data_formats_io.get_emd_with_metadata(filepath)[source]

Read TEM-imgages as .emd-files

Args:
filepath (string):

relative or absolute path to the file.

Returns:
image (MxN array_like):

2D image with only one intensity-channel (gray-scale).

metadata (dict):

Dictionary containing the most important metadata.

microscopy_data_analysis.data_formats_io.h5_to_pyramidal_tiff(h5_path, dset_name, out_path, compression='lzw', max_levels=4, dtype=None)[source]

Convert a chunked HDF5 dataset to a pyramidal BigTIFF using tifffile. Memory-safe: only one tile is loaded at a time.

microscopy_data_analysis.data_formats_io.h5_to_tiff(h5_path, dset_name, out_path, compression='lzw', big_tiff=True, dtype=None)[source]

Convert a chunked HDF5 dataset to a BigTIFF (no pyramid).

microscopy_data_analysis.data_formats_io.imsave(filename, img, floatnormalize=True)[source]

writes single (grayscale), triple (RGB), quadrupel (RGBA) channel images, for uint8 and uint16 formats “.png” is used as default, for float32 “.tif” is used as default double channel images (gray,alpha) will be transformed to RGBA filename extensions (“.png”, “.jpg”, …) are optional and can be given to obtain a format differing from default

Args:
filename (string):

filename with or without extension determining the format.

img (array_like):

image matrix, either MxN, MxNx1, MxNx3 or MxNx4.

floatnormalize (bool):

transform the color range between 0 and 1 (for better compatibility with most image viewers) Defaults to True.

Returns:
success_info (bool):

True, when succesfully written.

microscopy_data_analysis.data_formats_io.imsave_multi(filename, stack, floatnormalize=True)[source]

save multiple (single channel / greyscale) images as tiff-stack (supported formats uint8, uint16, float32)

Args:
filename (string):

filename with or without .tiff extension.

stack (list of images):

grayscale images only containing one channel.

floatnormalize (bool):

transform the color range between 0 and 1 (for better compatibility with most image viewers) Defaults to True.

Returns:
success_info (bool):

True, when succesfully written.

microscopy_data_analysis.data_formats_io.readable_names(res, qtu)[source]
microscopy_data_analysis.data_formats_io.save_dm4_spectra_as_csv(spectrum_paths)[source]

microscopy_data_analysis.general_util module

submodule covering some 1D, 2D, mixed and other functions

microscopy_data_analysis.general_util.assure_multiple(*x)[source]

pass through one or more variables and check, if they are effectively iterable, meaning the format supports iteration and the variable contains more than one element. If just one element is present, this element is extracted from its iterable container.

Args:
*x (TYPE):

DESCRIPTION.

Returns:

TYPE: DESCRIPTION.

microscopy_data_analysis.general_util.bin_centering(x_bins, additional_boundary_bin_threshold=None)[source]

transform bin thresholds to x values

Args:

x_bins (list or array_like): with length N, in strictly increasing order.

additional_boundary_bin_threshold (float, optional): option to give an additional bin, in case the given values, represent only lower or upper bin boundaries. Defaults to None.

Returns:

centers (array_like): with length N-1 or length N when an additional bin is given.

microscopy_data_analysis.general_util.ccw(A, B, C)[source]
microscopy_data_analysis.general_util.circle_perimeter_points(row, col, r, image, accurate=False)[source]
microscopy_data_analysis.general_util.create_bins(x)[source]

create bin thresholds between points of x, always in the middle between two points, with mirroring boundary conditions

Args:

x (list or array_like): with length N, in strictly increasing order.

Returns:

bins (list): with length N+1.

microscopy_data_analysis.general_util.custom_colormap(img, colormap_name, number_of_colorsliders=3)[source]
microscopy_data_analysis.general_util.determine_thresh(image)[source]
microscopy_data_analysis.general_util.draw_dashed_line(img, start_point, end_point, color, thickness=1, segment_length=15, gap_length=10)[source]

draw a dashed line on a 2D rasterized image

Args:

img (array_like): DESCRIPTION. start_point (tuple or array_like): DESCRIPTION. end_point (tuple or array_like): DESCRIPTION. color (3 tupel): ( r , g, b ). thickness (int, optional): DESCRIPTION. Defaults to 1. segment_length (int, optional): DESCRIPTION. Defaults to 15. gap_length (int, optional): DESCRIPTION. Defaults to 10.

Returns:

None.

microscopy_data_analysis.general_util.fft_circ_mask(imshape, mask_radius=680, mask_sigma=0)[source]
microscopy_data_analysis.general_util.find_next_cut(func, firstcut, desired_area, tolerance_area, quad_abs_prec, max_iterations, step_size=1)[source]
microscopy_data_analysis.general_util.folder_file(path_string)[source]

split a string presenting a path with the filename into the filename and the directory-path. (works with slash, backslash or double backslash as seperator)

Args:
path_string (string):

absolute or relative path.

Returns:
directory_path (string):

folder.

filename (string):

file.

microscopy_data_analysis.general_util.get_all_files(folder='.', ending=None, start=None)[source]

searches recursively (including all subdirectories) for all files with the given start and ending within the given folder

Args:
folder (string, optional):

directory name. Defaults to ‘.’.

ending (string, optional):

typical usecase: “.png” to get all png-images. Defaults to None.

start (string, optional):

pattern in the beginning of each filename. for example use “img” here: “img1.png,img2.tif,img3.jpeg” Defaults to None.

Returns:
filepaths (list):

list of paths.

microscopy_data_analysis.general_util.get_angular_dist(image, borderdist=100, centerdist=20, plotcheck=False)[source]

angles measured in degrees starting from horizontal line counterclockwise in real space (like phi in polar coordinate)

Args:
image (TYPE):

DESCRIPTION.

borderdist (TYPE, optional):

DESCRIPTION. Defaults to 100.

centerdist (TYPE, optional):

DESCRIPTION. Defaults to 20.

plotcheck (TYPE, optional):

DESCRIPTION. Defaults to False.

Returns:
angledeg (TYPE):

DESCRIPTION.

values (TYPE):

DESCRIPTION.

microscopy_data_analysis.general_util.get_files_of_format(path, ending)[source]

searches files with the given ending within the directory

Args:
path (string):

relative or absolute path to a directory.

ending (string):

typical usecase: “.png” to get all png-images.

Returns:
pathlist (list):

list of the paths of files with the specific ending

microscopy_data_analysis.general_util.intersect(A, B, C, D)[source]
microscopy_data_analysis.general_util.isleft(P0_0, P0_1, P1_0, P1_1, P2_0, P2_1)[source]
microscopy_data_analysis.general_util.lineIntersection(a, b, c, d)[source]
microscopy_data_analysis.general_util.load_cmap(filename)[source]
microscopy_data_analysis.general_util.make_circular_mask(row, col, r, image=None, imshape=None)[source]

create a circular mask, with row , col and r either being integers or float

Args:

row (TYPE): DESCRIPTION. col (TYPE): DESCRIPTION. r (TYPE): DESCRIPTION. image (TYPE, optional): DESCRIPTION. Defaults to None. imshape (TYPE, optional): DESCRIPTION. Defaults to None.

Raises:

ValueError: DESCRIPTION.

Returns:

mask (TYPE): DESCRIPTION.

microscopy_data_analysis.general_util.make_mask(rot, d=3)[source]
microscopy_data_analysis.general_util.max_from_2d(A)[source]

get the position and value of the maximum from a matrix or image

Args:
A (MxN array_like):

input 2D-signal.

Returns:
maximum_position (tuple):

containing two integers.

maximum_value (scalar):

datatype depending on the input.

microscopy_data_analysis.general_util.peak_com2d(data, delta=None, roi=None)[source]
microscopy_data_analysis.general_util.point_in_convex_ccw_roi(xroi, yroi, xpoint, ypoint)[source]
microscopy_data_analysis.general_util.polygon_roi(directions_deg, radius)[source]
microscopy_data_analysis.general_util.rfft_circ_mask(imshape, mask_radius=680, mask_sigma=0)[source]
microscopy_data_analysis.general_util.rfft_starmask(angles, imshape, mask_sigma=0)[source]
microscopy_data_analysis.general_util.rfft_to_fft(rfft_img, fullshape)[source]
microscopy_data_analysis.general_util.save_cmap(filename, cmap_dict)[source]
microscopy_data_analysis.general_util.smoothbox_kernel(kernel_size)[source]

Gaussian Smoothing kernel approximated by integer-values obtained via binomial distribution

microscopy_data_analysis.general_util.split_function_into_equal_area_parts(func, number_of_parts, prec=1e-06, limits=None, printing=False, max_iterations=1000)[source]

calculate the split positions to divide a function into equal area parts, best suited for smooth functions

microscopy_data_analysis.general_util.stitch_1d_overlap(x1, y1, x2, y2, scale_adjustment=True, newbins=False, verbose=False)[source]

stitch two 1d-signals (x1,y1 and x2,y2) containing some overlap in x. x1 and x2 must be uniformly spaced and in increasing order. within the overlap region the finer resolution in x is kept (any interpolation in this function is done linearly).

adjust the scale of y1 and y2 such that they yield the same mean value in the overlap region, by multiplying both signals with a fixed factor

(typical use case: two spectroscopic measurements with different settings, yielding two spectra of different wavelength-regions with some overlap)

Args:

x1 (list or array_like): same length as y1.

y1 (list or array_like): same length as x1.

x2 (list or array_like): same length as y2.

y2 (list or array_like): same length as x2.

scale_adjustment (bool, optional): turn multiplicative adjustement on (True) or off (False). Defaults to True.

verbose (bool, optional): prints out the scale_adjustment factor, if set to True. Defaults to False.

Returns:

new_x (array_like): stitched signal x.

new_y (array_like): stitched signal y.

microscopy_data_analysis.general_util.take_map(mapimage, tilesize=1000, overlap=0.25)[source]

microscopy_data_analysis.stacks module

class microscopy_data_analysis.stacks.image_stack(mode='storage', no_print=False)[source]

Bases: object

class to handle stacks of images

change_source_imgs(mode='memory', no_print=False)[source]

Change source images of the stack

Args:
mode (string):

‘storage’ only single images are loaded into RAM when needed (‘storage’ supports images as .tif, .png, dm4, emd, … or as multiple files in .h5 or as datacube in .h5) The mode ‘memory’ can be used, for small image series, that are already being loaded fully into RAM Defaults to ‘storage’

no_print (bool):

set to ‘True’ for silent execution Defaults to ‘False’

check_pairs(max_transl_pix=None, sigma=1, check_data=False, dset_name=None)[source]

obtain translation vectors from pairwise phase correlation

clip(vmin=-inf, vmax=inf, dset_name='data', new_dset_name=None)[source]

clip values of a stack or a tiled image,

Args:
vmin (float):

minimum clip value Deault vmin negative infinity (no clippling)

vmax (float):

maximum clip value Deault vmax positive infinity (no clippling)

dset_name (string):

dataset name for source of data

new_dset_name (string):

dataset name for target of data if new_dset_name is None the data in dset_name will be overwritten Defaults to None

connection_groups(polygons=None, units_per_pixel=None, minimal_number_of_pixels=64, inverse=False)[source]

create connection graph of overlapping polygons and return connected groups

convert_to_uint16(real_zero=False, dset_name='data')[source]

save uint16 dataset in h5

create_h5cube_duplicate_for_modifying(filename='temp.h5', dset_name='data', new_dimensions=None, force_dtype=False)[source]

Create an h5 file containing the data as 3D-dataset

Args:
filename (string):

name of the h5-file

dset_name (string):

name or internal path to the dataset

new_dimensions (tuple):

if the original dimensions are a multiple of the new_dimensions cv2.INTER_AREA corresponds to an effective mean value if None, the original dimensions are used Defaults to None

force_dtype (bool):

set to ‘True’ to not change the datatype, otherwise Float32 is chosen for best compatibility with functions acting on the data (datatype of a created dataset can not be changed -> another duplicate dataset necessary for change) Defaults to ‘False’

crop_from_points(img, points, shape=None)[source]

crop a section of an image conating all points (bounding box around points)

Args:

img (array_like):

points (array_like,list):

shape (tuple,optional):

Returns:

cropped_img (array_like):

dust_from_flat_field(flat_field, threshold_block_size=17, morph_closing_size=5, dark_background=True, dilate=0)[source]

extract positions of dust or dead pixels from flat field image

Args:
flat_field (array_like):

flat field image

threshold_block_size (int, uneven):

block size for binarization using adaptive gaussian thresholding (cv2)

morph_closing_size (int, uneven):

dark_background (bool):

dilate (int >= 0):

Returns:
image_check:

check

dust_removal(img, mode='median')[source]
dust_removal_all(dset_name='data', new_dset_name=None)[source]

Apply dust removal on stack

flat_field_correction(flat_field=None, dset_name='data', new_dset_name=None)[source]

Apply flat field correction by division

flat_field_generation(percentile_steps=19, subdiv=4, dset_name='data')[source]

Calculate a local flat field background of a stack by averaging percentiles

Args:
percentile_steps (int > 1):

number of percentiles used

subdiv (int > 0):

subdiv=1 corresponds to no subdivsion, all data is loaded subdiv=2 loads only half of the data into RAM subdiv=3 corresponds to a third … adjust according to the size of data and RAM Defaults to 4

dset_name (string):

dataset name for source of data

Returns:
flat_field (array_like):

resulting flat field image

get_img(index, dset_name=None)[source]

Load the requested image into RAM and return it

Args:
index (int):

index of the image in ‘img_list’

Returns

img (array):

requested image

get_outer_polygon_limits(polygons)[source]

Obtain bounding box containing all polygons

Args:
polygons (list):

List of polygons

Returns:
points (array_like):

corner points of bounding box as x and y coordinates with shape (4,2)

imgs_from_datacube(dataset_name)[source]

Images are assumed to be represented by the first index (for example: 16 x 1024 x 1024)

Args:
dataset_name (string):

name (h5 internal path) of the dataset could look like for example: ‘sampleA/data’ or just ‘images’

info()[source]

print info

make_polygons(units_per_pixel=None, positions=None, dimensions=None, orientation=2)[source]

create polygon representation

map_from_polygons(polygons, blending='average', custom_mask=None, boolean_mask=False, border_value=0, dset_name=None)[source]

create image map by tiling all single images and fusing them together

Args:
polygons (list of poly):

List of polygons, used for fusing the image map if None, “moved_polygons” is used

blending (string):

blending between image tiles in overlap area, choose between: ‘average’ : for using the average value at each pixel of different tiles ‘linear’ : for a weighted average, with weights linearly decreasing from 1 to 0 going from the center towards the edge of each image ‘quadratic’ : for a weighted average, with weights decreasing from 1 to 0 like 1-x^2, going from the center towards the edge of each image ‘maximum’ : use maximum value for pixel in overlapping region ‘minimum’ : use minimum value for pixel in overlapping region ‘hard_cut’ : overwrite pixel values in overlapping regions ‘custom_single’ : give a set of custom weights to weighted average Defaults to ‘average’

custom_mask (array_like):

set of weights in the shape of a single image, only used when ‘blending’ is set to ‘custom_single’ Defaults to None

boolean_mask (bool):

set to ‘True’ to return a mask with values being ‘True’ for areas covered by the stitched image and ‘False’ for areas around it Defaults to ‘False’

border_value (float):

value used for map borders, when ‘blending’ is ‘minimum’ or ‘maximum’ Defaults to 0

map_from_polygons_h5(polygons=None, h5file=None, blending='average', custom_mask=None, boolean_mask=False, border_value=0, dset_name=None)[source]

create image map by tiling all single images and fusing them together the data is written into dataset “map” and “division_mask”, “boolean_mask”

Args:
polygons (list of poly):

List of polygons, used for fusing the image map if None, “moved_polygons” is used

h5file (string):

flie name / file path to write the new dataset to if None, “modifiable_file’ is used Defaults to None

blending (string):

blending between image tiles in overlap area, choose between: ‘average’ : for using the average value at each pixel of different tiles ‘linear’ : for a weighted average, with weights linearly decreasing from 1 to 0 going from the center towards the edge of each image ‘quadratic’ : for a weighted average, with weights decreasing from 1 to 0 like 1-x^2, going from the center towards the edge of each image ‘maximum’ : use maximum value for pixel in overlapping region ‘minimum’ : use minimum value for pixel in overlapping region ‘hard_cut’ : overwrite pixel values in overlapping regions ‘custom_single’ : give a set of custom weights to weighted average Defaults to ‘average’

custom_mask (array_like):

set of weights in the shape of a single image, only used when ‘blending’ is set to ‘custom_single’ Defaults to None

boolean_mask (bool):

set to ‘True’ to return a mask with values being ‘True’ for areas covered by the stitched image and ‘False’ for areas around it Defaults to ‘False’

border_value (float):

value used for map borders, when ‘blending’ is ‘minimum’ or ‘maximum’ Defaults to 0

normalize(old_min=None, old_max=None, new_min=0, new_max=1, dset_name='data', new_dset_name=None)[source]

clip values of a stack or a tiled image,

Args:
old_min (float):

offset subtracted from data for normalization if None -> old_min is set to global minimum Deaults to None

old_max (float):

maximum value from data, that will correspond to new_max after normalization if None -> old_max is set to global maximum Deaults to None

new_min (float):

Deaults to 0

new_max (float):

Deaults to 1

dset_name (string):

dataset name for source of data

new_dset_name (string):

dataset name for target of data if new_dset_name is None the data in dset_name will be overwritten Defaults to None

optimize_positions(verbose=True)[source]

global optimization of image positions in real space to minimize deviations from ideal image translations given by phase correlation

overwrite_modifiable_datasets(overwrite=True)[source]

set the mode for overwriting (just inside the modifiable dataset)

Args:
overwrite (bool):

set to ‘False’ to make sure that datasets in the modifiabel h5-file are conserved Defaults to ‘True’

pixel_to_real(index, points)[source]

coordinate transformation from pixel space to real space

plot_connection_network(figsize=None, relative=True)[source]

plot connection graph

real_to_pixel(index, points, orientation=2)[source]

coordinate transformation from real space to pixel space

refine_positions(moved_polygons, plot_connection=True)[source]
set_directory_path(path_string)[source]

Set the path to either an h5-file or a folder containing the images

Args:
path_string (string):

looking like, for example: ‘folderA/data.h5’ or ‘folderB’

set_img(index, img, dset_name)[source]

Exchange the image with given index in the modifiable dataset

Args:
index (int):

index corresponding to the image be changed

img (array):

new image that exchanges the old one

dsetname (string):

name of/path to the dataset inside the h5-file

set_img_list(img_list)[source]

Set the image list

Args:
img_list (list of strings or list of arrays):

corresponding to either paths within the file-system or the h5-hierachy or in case of mode=’memory’ a list containing the actual images

set_positions(positions)[source]

Set the estimated x and y positions of the images for stitching

Args:
postions (array_like or list of tuples):

postions containing x,y either as array with shape (N,2) or list of tuples

set_print_mode(no_print=False)[source]

Prevent or enable print output

Args:
no_print (bool):

set to ‘True’ for silent execution Defaults to ‘False’

set_units_per_pixel(units_per_pixel)[source]

Set the units per pixel for example (0.3 micrometer per pixel), corresponding to positions (‘set_positions’)

Args:
units_per_pixel (float):

scalar value

sniff_dimensions()[source]

Determine image dimensions from the first image

static sort_tuples_close_repetition(list_of_tuples)[source]

sort a list of 2-tuples containing integers from 0 to N, such that tuples with one identical element are in neighbouring positions

Args:
list_of_tuples (list or array_like):

shape: Lx2

Returns:
sorted_tuples (list):

shape: Lx2

stats(histogram=True, histo_levels=100, dset_name=None, mask=None, original=False)[source]

get statistics from a stack or a tiled image, obtain minimum, maximum and histogram

Args:
histogram (bool):

set to ‘False’ for faster calculation when only minimum and maximum are needed Defaults to ‘True’

histo_levels (int>1):

number of levels of the histogram (leading to histo_levels + 1 bin borders) Defaults to 100

Returns:
minimum (float):

global minimum of all images of stack or full tiled image

maximum (float):

global maximum of all images of stack or full tiled image

bins (array_like):

borders of the bins –> histo_levels +1 values

histogram (array_like):

count of each bin

subtract_dark_field(dark_field, dset_name='data', new_dset_name=None)[source]

substract value or array from whole stack

Args:
dark_field (array_like or float):

scalar value or image for subtraction

dset_name (string):

source of data

new_dset_name (string):

target of data

z_transform_images(offset_positive=True, dset_name='data', new_dset_name=None)[source]

execute a z-transfom on a stack of images (subtract mean, divide by standard deviation)

microscopy_data_analysis.image_aligning module

@author: kernke

microscopy_data_analysis.image_aligning.align(im1, im2, printing=False, _verbose=False)[source]

calculate the translational offset of image im2 relative to image im1 using phase correlation between the two image The images must have the the same shape (MxN) and some overlap

Args:
im1 (MxN array_like):

first image.

im2 (MxN array_like):

second image.

printing (bool, optional):

set to “True” for printing more information about the function execution. Defaults to False.

verbose (bool,optional):

set to “True” for additionally returning indices about the relative positioning. Defaults to False.

Returns:
offset (tuple):

containing two integers.

microscopy_data_analysis.image_aligning.align_com_precise(im1, im2, delta=None, show=False, artifacts=None)[source]
Args:
im1 (TYPE):

DESCRIPTION.

im2 (TYPE):

DESCRIPTION.

delta (TYPE, optional):

DESCRIPTION. Defaults to None.

show (TYPE, optional):

DESCRIPTION. Defaults to False.

artifacts (TYPE, optional):

DESCRIPTION. Defaults to None.

Returns:
pc (TYPE):

DESCRIPTION.

microscopy_data_analysis.image_aligning.align_image_fast1(im1, matrix1, reswidth, resheight)[source]
microscopy_data_analysis.image_aligning.align_image_fast2(im2, reswidth, resheight, width_shift, height_shift)[source]
microscopy_data_analysis.image_aligning.align_images(im1s, im2, p1s, p2, verbose=False)[source]
microscopy_data_analysis.image_aligning.align_pair(im1, im2, p1, p2, verbose=False)[source]
microscopy_data_analysis.image_aligning.align_pair_special(im1, im2, p1, p2, relative_scale_limit=None, translation_only=False)[source]
microscopy_data_analysis.image_aligning.click(event)[source]
microscopy_data_analysis.image_aligning.close_translation_by_phase_correlation(im1, im2, sigma=1, max_transl=None)[source]

calculate translation vector between images by phase correlation, assumes ‘closeness’ as translations less than half of image dimensions

Args:
im1 (array_like):

image 1

im2 (array_like):

image 2

sigma (float):

width of Gaussian smoothing of correlation matrix

max_transl (tuple):

maximal translation limit enforced by masking the correlation matrix

Returns:

translation_vector (array_like, tuple):

certainty (float):

normed signal noise ration (max-mean)/std

microscopy_data_analysis.image_aligning.img_correlation(a, b, padding_ratio=4, pad_mode='mean', pad_attenuation='linear', pad_parameters=None, cross_correlation=False)[source]

calculate the pase correlation between two images a,b (best with even dimensions) with same shape MxN

Args:
a (MxN array_like):

first image.

b (MxN array_like):

second image.

padding_ratio (float):

ratio of biggest dimension of image Defaults to 4

pad_mode (string):

same modes as in numpy.pad Defaults to ‘mean’

pad_attenuation (string):

For details see img_padding_attenuation Defaults to ‘linear’

pad_parameters (dictionary):

For details see img_padding_attenuation Defaults to None

cross_correlation (bool):

set to ‘True’ for additionally returning cross correlation matrix Defaults to ‘False’

Returns:
phase_r (MxN array_like):

phase correlation matrix.

cross_r (MxN array_like):

cross correlation matrix

microscopy_data_analysis.image_aligning.phase_correlation(a, b)[source]

calculate the pase correlation between two images a,b with same shape MxN

Args:
a (MxN array_like):

first image.

b (MxN array_like):

second image.

Returns:
r (MxN array_like):

phase correlation matrix.

microscopy_data_analysis.image_aligning.points_on_image(image)[source]
microscopy_data_analysis.image_aligning.sift_align_matches(img1, img2, ratio_threshold=0.5, verbose=False)[source]

only works with uint8 -dtype

Args:

img1 (TYPE): DESCRIPTION. img2 (TYPE): DESCRIPTION. ratio_threshold (TYPE, optional): DESCRIPTION. Defaults to 0.5.

Returns:

Matched (TYPE): DESCRIPTION. ptsA (TYPE): DESCRIPTION. ptsB (TYPE): DESCRIPTION.

microscopy_data_analysis.image_aligning.stack_align(imgs, shifts)[source]
microscopy_data_analysis.image_aligning.stack_align_com_precise(imgs, shifts)[source]
microscopy_data_analysis.image_aligning.stack_align_from_matrices(stack, metadata)[source]

Aligns a stack of images using the homographic transformation calculated by the function stack_sift_align_to_first() with argument verbose=True

Args:
stack (KxMxN array_like or list of MxN array_likes):

stack of images (different image dimensionss, e.g. one with 1024x512 and another with 234x653, are possible).

metadata (dictionary):

transformational information as given by stack_sift_align_to_first.

Returns:
imlist (list of MxN):

list of aligned images.

microscopy_data_analysis.image_aligning.stack_crop_shifts(stack, shifts)[source]
microscopy_data_analysis.image_aligning.stack_shift_precise(imgs, delta=None, show=False, artifacts=None)[source]
microscopy_data_analysis.image_aligning.stack_shifting(imgs)[source]
microscopy_data_analysis.image_aligning.stack_sift_align_to_first(stack, ratio=0.5, verbose=False)[source]
microscopy_data_analysis.image_aligning.stitch(im1, im2)[source]

stitch two images together to one, by correcting a translational offset The images must have the the same shape (MxN) and some overlap

Args:
im1 (MxN array_like):

first image.

im2 (MxN array_like):

second image.

Returns:
stitched (KxL array_like):

montage of the two images.

microscopy_data_analysis.image_aligning.stitch_given_shift(im1, im2, pc)[source]

stitch two images together to one, by correcting a translational offset The images must have the the same shape (MxN) and some overlap

Args:
im1 (MxN array_like):

first image.

im2 (MxN array_like):

second image.

Returns:
stitched (KxL array_like):

montage of the two images.

microscopy_data_analysis.image_aligning.stitch_pair(im1, im2, verbose=False)[source]

only works with uint8

Args:

im1 (TYPE): DESCRIPTION. im2 (TYPE): DESCRIPTION. verbose (TYPE, optional): DESCRIPTION. Defaults to False.

Returns:

TYPE: DESCRIPTION.

microscopy_data_analysis.image_processing module

submodule focussed completely on images, all functions with prefix “img” take an image as main input and return a processed image

microscopy_data_analysis.image_processing.img_add_weighted_gray_alpha(img1, img2)[source]
microscopy_data_analysis.image_processing.img_add_weighted_gray_alpha_numba(img1, img2, newimg)[source]
microscopy_data_analysis.image_processing.img_add_weighted_rgba(img1, img2)[source]
microscopy_data_analysis.image_processing.img_anms(img, mask, thresh_ratio=1.5, ksize=5, asympix=0, damping=5)[source]

asymmetric non maximum supppression

Args:
img (array_like):

DESCRIPTION.

mask (TYPE):

DESCRIPTION.

thresh_ratio (float, optional):

DESCRIPTION. Defaults to 1.5.

ksize (int, optional):

uneven integer. Defaults to 5.

asympix (TYPE, optional):

DESCRIPTION. Defaults to 0.

damping (TYPE, optional):

DESCRIPTION. Defaults to 5.

Returns:
processed_image (array_like):

DESCRIPTION.

microscopy_data_analysis.image_processing.img_autoclip(img, ratio=0.001)[source]

auto clipping removing small and big outliers

Args:

img (TYPE): DESCRIPTION. ratio (TYPE, optional): DESCRIPTION. Defaults to 0.001.

Returns:

TYPE: DESCRIPTION.

microscopy_data_analysis.image_processing.img_gammaCorrection(img, gamma)[source]

transformation adjusting the gamma level (gamma=1 means no change)

Args:
img (MxN array_like):

np.uint8.

gamma (float):

gamma value between 0 and ~10.

Returns:
gamma_transformed_image (MxN array_like):

np.uint8.

microscopy_data_analysis.image_processing.img_gray_to_rgba(img)[source]

transform grayscale (uint8) to rgba (uint8) image

Args:

img (TYPE): DESCRIPTION.

Returns:

rgba_img (TYPE): DESCRIPTION.

microscopy_data_analysis.image_processing.img_make_square(image, startindex=None)[source]

crops the largest square image from the original, by default from the center. The position of the cropped square can be specified via startindex, moving the frame from the upper left corner at startindex=0 to the lower right corner at startindex=abs(M-N)

Args:
image (MxN array_like):

DESCRIPTION.

startindex (int, optional):

must be within 0 <= startindex <= abs(M-N). Defaults to None.

Returns:
square_image (array_like):

either MxM or NxN array.

microscopy_data_analysis.image_processing.img_morphLaplace(image, kernel)[source]

morphological Laplace Filter

Args:
image (MxN array_like):

np.uint8.

kernel (TYPE):

DESCRIPTION.

Returns:
filtered_image (MxN array_like):

np.uint8.

microscopy_data_analysis.image_processing.img_noise_line_suppression(image, ksize)[source]

morphological opening with a horizontal line as structuring element (first erode, than dilate ; only horizotal lines with length ksize remain)

Args:
image (array_like):

input.

ksize (int):

uneven integer.

Returns:
processed_image (array_like):

output.

microscopy_data_analysis.image_processing.img_normalize(img)[source]
microscopy_data_analysis.image_processing.img_normalize_fast(img)[source]
microscopy_data_analysis.image_processing.img_normalize_numba(img, newimg)[source]
microscopy_data_analysis.image_processing.img_padding_attenuation(padded_img, pad_width, mode='linear', parameters=None, plot=False)[source]

extending the functionality of np.pad (following same syntax: pad_width) or cv2.copyMakeBorder allowing custom attenuation (value reduction towards 0) of added padding (borders)

modes: ‘linear’, ‘exponential’, ‘inverse_exponential’ and ‘sigmoid_normalCDF’

microscopy_data_analysis.image_processing.img_periodic_tiling(img, tiles=3)[source]

takes an image as a tile and creates a tiling of tiles x tiles by duplicating it.

Args:
img (MxN array_like):

2d-dataset / image.

tiles (int, optional):

number of tiles in vertical and horizontal direction. the number of tiles must be uneven. Defaults to 3.

Returns:
tiled (array_like):

with shape tiles*M x tiles*N.

orig (tuples):

containing the bounding coordinates of the center image (lower_row_limit,upper_row_limit),(lower_column_limit,upper_column_limit).

microscopy_data_analysis.image_processing.img_rebin_by_mean(image, new_shape)[source]

reduce the resolution of an image MxN to mxn by taking an average, whereby M and N must be multiples of m and n

Args:
image (MxN array_like):

image.

new_shape (tuple):

containing two integers with the new shape.

Returns:
rebinned_image (mxn array_like):

smaller image.

microscopy_data_analysis.image_processing.img_rotate_back(image, log, flag='cubic', bm=1)[source]

invert the rotation done by img_rotate_bound returning the image to its original shape MxN, cutting away padded values for the bounding box generated by img_rotate_bound

Args:
image (KxL array_like):

np.uint8.

log (list):

[M,N,inverse_rotation_matrix], contains the original shape M,N and the matrix needed to invert the rotation. log is given by the function img_rotate_bound.

flag (string, optional):

possibilities:”cubic”,”linear”; sets the method of interplation. Defaults to “cubic”.

bm (int, optional):

possibilities: 0,1; sets the border mode, extrapolating from the borders of the image. 0: continues the image by padding zeros 1: continues the image by repeating the border-pixel values. (bm=1 allows more exact back transformation, avoiding the decrease of border-pixel values due to interpolation with zeros.) Defaults to 1.

Returns:
inverse_rotated_image (MxN array_like):

np.uint8.

microscopy_data_analysis.image_processing.img_rotate_bound(image, angle, flag='cubic', bm=1)[source]

rotates an image by the given angle clockwise; The rotated image is given in a rectangular bounding box without cutting off parts of the original image.

Args:
image (MxN array_like):

np.uint8.

angle (float):

angle given in degrees.

flag (string, optional):

possibilities:”cubic”,”linear”; sets the method of interplation. Defaults to “cubic”.

bm (int, optional):

sets the border mode, extrapolating from the borders of the image. 0: continues the image by padding zeros 1: continues the image by repeating the border-pixel values. Defaults to 1.

Returns:
rotated_image (KxL array_like):

np.uint8.

log (list):

looking like [M,N,inverse_rotation_matrix], contains the original shape M,N and the matrix needed to invert the rotation for the function img_rotate_back.

microscopy_data_analysis.image_processing.img_single_to_double_channel(img)[source]
microscopy_data_analysis.image_processing.img_to_half_int16(img)[source]

transform contrast to half the range of signed integer 16bit, so values are between -16384 and 16383 for possible range -32768 to 32767

Args:
img (MxN array_like):

input image.

Returns:
datatype_conform_image (MxN array_like):

np.int16.

microscopy_data_analysis.image_processing.img_to_half_int8(img)[source]

transform contrast to half the range of signed integer 8bit, so values are between -64 and 63 for possible range -128 to 127

Args:
img (MxN array_like):

input image.

Returns:
datatype_conform_image (MxN array_like):

np.int8.

microscopy_data_analysis.image_processing.img_to_int16(img, newmax=32767, imgmin=None)[source]

transform contrast range to signed integer 16bit

Args:
img (MxN array_like):

input image.

newmax (int, optional):

optionally reduce contrast range, by setting a lower, than datatype given, threshold to the maximum value. Defaults to 32767.

imgmin (int, optional):

optionally set the lower limit, of the original image contrast, imgmin=0 preserves the original relative contrast range offset imgmin=None sets the contrast range offset to 0 Defaults to None.

Returns:
datatype_conform_image (MxN array_like):

np.int16.

microscopy_data_analysis.image_processing.img_to_int8(img, newmax=127, imgmin=None)[source]

transform contrast range to signed integer 8bit

Args:
img (MxN array_like):

input image.

newmax (int, optional):

optionally reduce contrast range, by setting a lower, than datatype given, threshold to the maximum value. Defaults to 127.

imgmin (int, optional):

optionally set the lower limit, of the original image contrast, imgmin=0 preserves the original relative contrast range offset imgmin=None sets the contrast range offset to 0 Defaults to None.

Returns:
datatype_conform_image (MxN array_like):

np.int8.

microscopy_data_analysis.image_processing.img_to_uint16(img, newmax=65535, imgmin=None)[source]

transform contrast range to unsigned integer 16bit

Args:
img (MxN array_like):

input image.

newmax (int, optional):

optionally reduce contrast range, by setting a lower, than datatype given, threshold to the maximum value. Defaults to 65535.

imgmin (int, optional):

optionally set the lower limit, of the original image contrast, imgmin=0 preserves the original relative contrast range offset imgmin=None sets the contrast range offset to 0 Defaults to None.

Returns:
datatype_conform_image (MxN array_like):

np.uint16.

microscopy_data_analysis.image_processing.img_to_uint8(img, newmax=255, imgmin=None, imgmax=None)[source]

transform contrast range to unsigned integer 8bit

Args:
img (MxN array_like):

input image.

newmax (int, optional):

optionally reduce contrast range, by setting a lower, than datatype given, threshold to the maximum value. Defaults to 255.

imgmin (float, optional):

optionally set the lower limit, of the original image contrast, imgmin=0 preserves the original relative contrast range offset imgmin=None sets the contrast range offset to 0 Defaults to None.

imgmax (float, optional):

optionally set the upper limit of the original image contrast, imgmax=None uses the biggest occuring value of the image Defaults to None.

Returns:
datatype_conform_image (MxN array_like):

np.uint8.

microscopy_data_analysis.image_processing.img_to_uint8_fast(img)[source]
microscopy_data_analysis.image_processing.img_to_uint8_numba(img, newimg)[source]
microscopy_data_analysis.image_processing.img_transform(image, imshape, rfftmask, rebin=True)[source]

special function that resizes an image to imshape, afterwards applies a Fourier-space mask given by rfftmask, and finally rebins squares of 4 pixels to 1 pixel, if rebin=True

Args:
image (MxN array_like):

DESCRIPTION.

imshape (tuple):

if rebin=True both integers of imshape must be even.

rfftmask (Mx(N/2+1) array_like):

mask in Fourier space.

rebin (bool, optional):

DESCRIPTION. Defaults to True.

Returns:
transformed_image (KxL array_like):

result.

microscopy_data_analysis.image_processing.img_transform_minimal(image, imshape, kernel)[source]

special function that resizes an image to imshape,

Args:
image (MxN array_like):

DESCRIPTION.

imshape ([int,int]):

if rebin=True both integers of imshape must be even

kernel (TYPE):

DESCRIPTION.

Returns:
transformed_image (KxL array_like):

result

microscopy_data_analysis.line_analysis module

@author: kernke

microscopy_data_analysis.line_analysis.compute_M(data)[source]
microscopy_data_analysis.line_analysis.get_connected_points(srb, minimal_points=5)[source]
microscopy_data_analysis.line_analysis.get_indices_sparse(data)[source]
class microscopy_data_analysis.line_analysis.line_analysis_object(image, singlemaps, checkmaps)[source]

Bases: object

object containing images, lines and points

all_connected_points(printing=True)[source]
check_intersection_type(deltapix=None)[source]
check_line_vars(printing=True)[source]

Check that all variables scaling with the number of lines, have the same dimensions.

check_misclassification(shortratio=3, longratio=4, test=False)[source]
eliminate_side_maxima_checkmaps(shiftrange=20, ratio_threshold=2.0, test=False)[source]
eliminate_side_maxima_image(shiftrange=20, ratio_threshold=0.75, image=None, line='dark', test=False)[source]
get_connections()[source]
get_methods()[source]

Returns a list containing all methods of this class

get_number_of_connections()[source]
make_line_overview()[source]

create an image where

merge_conpoi(ratio_stitched_to_orig_below=2, merge_below_distance=5, val_threshold=6, closeness=2, test=False)[source]
pinpoint_crossings()[source]
print_number_of_lines()[source]
shrink_extend_line(deltapix)[source]
sort_ids_out(sortoutids)[source]

Delete list of indices refering to lines

sortout_by_angle(mad_threshold=8, test=False)[source]
sortout_by_confidence(confidence_threshold=0.3, test=False)[source]
sortout_by_value(mad_threshold=4, plot=False, test=False)[source]
sortout_short(threshold=20, test=False)[source]
sortout_zero_connections(test=False)[source]
microscopy_data_analysis.line_analysis.make_line_overview(conpois, img)[source]

create an image where

microscopy_data_analysis.line_detection module

@author: kernke

microscopy_data_analysis.line_detection.line_check_angle(lines, deg_tol=1.5)[source]
microscopy_data_analysis.line_detection.line_check_angle_s(lines, rotangle, deg_tol=1.5)[source]
microscopy_data_analysis.line_detection.line_enhance_horizontal(trot, mask, ksize=None, dist=1, iterations=2, line='dark')[source]
microscopy_data_analysis.line_detection.line_process(image, rotangles, ksize_erodil=15, ksize_anms=15, damp=10, smoothsize=1, Hthreshold=50, Hminlength=5, Hmaxgap=50, line='dark', ksize=None, iterations=2, anms_threshold=2, dist=1, houghdist=1)[source]
microscopy_data_analysis.line_detection.line_process_partial(image, rotangles, masks, ksize_erodil=None, ksize_anms=None, damp=10, line='dark', ksize=None, iterations=2, db_dist=None, anms_threshold=2, dist=1, ksize_smooth=None)[source]
microscopy_data_analysis.line_detection.line_process_vis(image, rotangles, masks, ksize_erodil=None, ksize_anms=None, damp=10, line='dark', ksize=None, iterations=2, anms_threshold=2, dist=1)[source]
microscopy_data_analysis.line_detection.obtain_maps(qkeys, qline_images, qsum_images, qcheck_images, lowhigh)[source]

microscopy_data_analysis.peak_fitting module

submodule focussed completely on 1D-data

microscopy_data_analysis.peak_fitting.asym_pseudo_voigt(x, x0, A, eta, gamma_0, a)[source]

normalized asymmetric pseudo-Voigt function (area under curve equals one for amplitude A=1, meaning A can be interpreted as sample size with given probability density, also implying A can differ from peakheight)

definitions following the paper: doi:10.1016/j.vibspec.2008.02.009

Args:
x (float or array_like):

input.

x0 (float):

maximum position.

A (float):

amplitude.

eta (float):

ratio of Lorentzian to Gaussian (between 0 and 1).

gamma_0 (float):

width.

a (float):

asymmetry.

Returns:
y (like x):

output.

microscopy_data_analysis.peak_fitting.asym_pseudo_voigt_center(x0, A, eta, gamma_0, a)[source]

center position of the peak

Args:
x0 (float):

maximum position.

A (float):

amplitude.

eta (float):

ratio of Lorentzian to Gaussian mixture.

gamma_0 (float):

width.

a (float):

asymmetry.

Returns:
center (float):

center of mass.

microscopy_data_analysis.peak_fitting.asym_pseudo_voigt_normalized_asym(a, gamma_0)[source]

transform the asymmetry parameter a into a range between -1 and 1 (erases the influence of gamma_0 on a, to compare the value for different peaks)

Args:
a (float):

asymmetry parameter.

gamma_0 (float):

width parameter.

Returns:
asym (float):

asymmetry between 0 and 1.

microscopy_data_analysis.peak_fitting.asym_pseudo_voigt_parameter_bounds()[source]

retrieve global bounds for the curve parameters

Returns:
bounds (list of lists):

containing lower bounds in the first and upper bounds in the second list.

microscopy_data_analysis.peak_fitting.asym_pseudo_voigt_peakheight(A, eta, gamma0, a)[source]

transform amplitude A to peakheight using the further necessary function parameters

Args:
A (float):

amplitude.

eta (float):

ratio of Lorentzian to Gaussian (between 0 and 1).

gamma0 (float):

width.

a (float):

asymmetry.

Returns:

peakheight (float).

microscopy_data_analysis.peak_fitting.asym_pseudo_voigt_table(params, show=True, verbose=True)[source]

show the fitting results in a table (pandas-dataframe, for use within jupyter)

Args:
params (list or array_like):

fit parameter.

show (bool, optional):

set to False, to return the table only as a variable. Defaults to True.

verbose (bool, optional):

set to False, to return just the raw fit parameter. Defaults to False.

Returns:
df (dataframe):

pandas table.

microscopy_data_analysis.peak_fitting.calculate_FWHM(x_data, y_data, superres=2)[source]

calculate full width half maximum (robust to non uniform spacing and noise)

Args:
x_data (list or array_like):

input data.

y_data (list or array_like):

input data.

superres (float, optional):

DESCRIPTION. Defaults to 2.

Returns:
fwhm (float):

full width half maximum value.

fwhm_positions (tuple):

left and right peak flank positions.

peak_height (float).

peak_positon (float).

microscopy_data_analysis.peak_fitting.center_of_mass(y, x=None, bins=None, roi=None)[source]

calculate the center of mass of the given data y, within the region-of-interest. Either x or bins can be given as x-axis data, otherwise x is constructed as the indices enumerating y

Args:

y (array_like): data value array with length N.

x (array_like, optional): x-positions of the y-points with length N. Defaults to None.

bins (array_like, optional): thresholds surrounding x-positions of the y-points, with length N+1. Defaults to None.

roi (tuple, optional): two thresholds in increasing order. (thresholds of roi, cut only at the datapoints (no interpolation)) Defaults to None.

Returns:

com (float): center of mass.

maxpos (float or int): position of biggest value.

microscopy_data_analysis.peak_fitting.create_rois(y_data, peak_positions, x_data=None)[source]

create roi tuples, by using the minimas between peaks and mirror-boundary conditions

Args:

y_data (array_like): DESCRIPTION.

peak_positions (list, array_like): DESCRIPTION.

x_data (array_like, optional): DESCRIPTION. Defaults to None.

Returns:

rois (list of tuples): DESCRIPTION.

microscopy_data_analysis.peak_fitting.gaussian(x, x0, A, sigma)[source]

normalized Gaussian curve (area under curve equals one for amplitude A=1, meaning A can be interpreted as sample size with given probability density, also implying A can differ from peakheight)

Args:
x (float or array_like):

input value.

x0 (float):

maximum position.

A (float):

amplitude.

sigma (float):

width.

Returns:
y (like x):

output value.

microscopy_data_analysis.peak_fitting.gaussian_A(peakheight, sigma)[source]

calculate amplitude A from peakheight and width

Args:
peakheight (float):

positive value.

sigma (float):

width.

Returns:

amplitude (float) .

microscopy_data_analysis.peak_fitting.gaussian_parameter_bounds()[source]

retrieve global bounds for the curve parameters

Returns:
bounds (list of lists):

containing lower bounds in the first and upper bounds in the second list.

microscopy_data_analysis.peak_fitting.gaussian_peakheight(A, sigma)[source]

calculate peakheight from amplitude and width

Args:
A (float):

amplitude.

sigma (float):

width.

Returns:

peakheight (float).

microscopy_data_analysis.peak_fitting.get_n_peaks_1d(y, x=None, n=5, roi=None, noise_integration_width=7)[source]

Obtain n peaks from y in descending order with respect to peakheight Calculated by consecutively searching the maximum of y and masking it, aswell as masking the decreasing flanks of the peak, in order to find the next maximum in the following iteration to a median value of y, then repeating the process n times

Args:
y (array_like):

input data.

x (array_like, optional):

same length as y, in increasing order, if x is None, it is constructed as indices enumerating y Defaults to None.

n (int, optional):

number of peaks. Defaults to 5.

roi (tuple, optional):

lower and upper threshold of region of interest. If None the whole dataset is evaluated Defaults to None.

noise_integration_width (int, optional):

uneven integer giving the window size for determining the decreasing flanks Defaults to 7.

Returns:
n_peaks (array_like):

with length n containing the positions of the n peaks.

microscopy_data_analysis.peak_fitting.lorentzian(x, x0, A, gamma)[source]

normalized Lorentzian curve (area under curve equals one for amplitude A=1, meaning A can be interpreted as sample size with given probability density, also implying A can differ from peakheight)

Args:
x (float or array_like):

input value.

x0 (float):

maximum position.

A (float):

amplitude.

gamma (float):

width.

Returns:
y (like x):

output value.

microscopy_data_analysis.peak_fitting.lorentzian_A(peakheight, gamma)[source]

calculate amplitude A from peakheight and width

Args:
peakheight (float):

positive value.

gamma (float):

width.

Returns:

amplitude (float) .

microscopy_data_analysis.peak_fitting.lorentzian_parameter_bounds()[source]

retrieve global bounds for the curve parameters

Returns:
bounds (list of lists):

containing lower bounds in the first and upper bounds in the second list.

microscopy_data_analysis.peak_fitting.lorentzian_peakheight(A, gamma)[source]

calculate peakheight from amplitude and width

Args:
A (float):

amplitude.

gamma (float):

width.

Returns:

peakheight (float).

microscopy_data_analysis.peak_fitting.multi_ident_func_fit(func, p0_lists, x, y, single_upper_bounds=None, single_lower_bounds=None)[source]

simultaneous fit of multiple peaks/features with identical fitfunctions

Args:
func (function):

single fit function.

p0_lists (list of lists):

every list containing the single fit estimates. As given for example by the function sequential_peak_fit

x (array_like):

input data.

y (array_like):

input data.

single_upper_bounds (list or array_like, optional):

boundaries for fit-parameters applied for all peaks/features. If not given +inf is used for all parameters. Defaults to None.

single_lower_bounds (list or array_like, optional):

boundaries for fit-parameters applied for all peaks/features. If not given -inf is used for all parameters. Defaults to None.

Returns:
fit_parameter_lists (list of lists):

with one list with the fit-parameters for each peak/feature.

fit_curve_y (array_like):

fitting curve, to compare to input y.

microscopy_data_analysis.peak_fitting.peak_fit(y_data, x_data=None, roi=None, plot=False, orders_of_deviation=2, verbose=False)[source]

peak fitting routine, that contains 4 peak functions: Gaussian, Lorentzian, Pseudo-Voigt, Asymmetric-Pseudo-Voigt

Args:
y_data (array_like):

DESCRIPTION.

x_data (array_like, optional):

if x_data is None, it is constructed as the indices enumerating y_data. Defaults to None.

roi (tuple, optional):

lower and upper threshold limiting the maximum position of the peak. Defaults to None.

plot (bool, optional):

show the input data and the 4 fit-routines compare to each other Defaults to False.

orders_of_deviation (int, optional):

abbrevated as ood. For robustness, the optimization range Delta is limited by thresholds relative to an estimate p like this: p*10^(-ood) < Delta < p*10^(ood) Defaults to 2.

verbose (bool, optional):

print estimated values for parameters before optmization. Defaults to False.

Returns:
gparams (list):

Gaussian fit-parameters.

lparams (list):

Lorentzian fit-parameters.

pVparams (list):

pseudo-Voigt fit-parameters.

apVparams (list):

asymmetric-pseudo-Voigt fit-parameters.

microscopy_data_analysis.peak_fitting.pseudo_voigt(x, x0, A, eta, gamma, sigma)[source]

calculates a normalized pseudo-Voigt profile (area under curve equals one for amplitude A=1, meaning A can be interpreted as sample size with given probability density, also implying A can differ from peakheight)

pseudo-Voigt is a linear combination of Lorentzian and Gaussian, instead of a convolution in case of the real Voigt-profile

definitions here following: http://dx.doi.org/10.5286/SOFTWARE/MANTID#.#

Args:
x (float or array_like):

input.

x0 (float):

maximum position.

A (float):

amplitude.

eta (float):

ratio of Lorentzian to Gaussian (between 0 and 1).

gamma (float):

Lorentzian width (full width half maximum) .

sigma (float):

Gaussian width (full width half maximum)/2.355 .

Returns:
y (like x):

output.

microscopy_data_analysis.peak_fitting.pseudo_voigt_parameter_bounds()[source]

retrieve global bounds for the curve parameters

Returns:
bounds (list of lists):

containing lower bounds in the first and upper bounds in the second list.

microscopy_data_analysis.peak_fitting.pseudo_voigt_peakheight(A, eta, gamma, sigma)[source]

transform amplitude A to peakheight using the further necessary function parameters

Args:
A (float):

amplitude.

eta (float):

ratio of Lorentzian to Gaussian (between 0 and 1).

gamma (float):

Lorentzian width.

sigma (TYPE):

Gaussian width.

Returns:

peakheight (float).

microscopy_data_analysis.peak_fitting.sequential_peak_fit(y_data, x_data=None, regions_of_interest=None, plot=False, verbose=False)[source]

fit multiple peaks succesively in descending order with respect to their peakheight. the number of peaks is given by the number of tuples for regions_of_interest

Args:
y_data (array_like):

input data.

x_data (array_like, optional):

if x_data is None, it is constructed as the indices enumerating y_data. Defaults to None.

regions_of_interest (list of tuples, optional):

with each tuple containing the lower and upper threshold limiting the maximum position of one peak. if no region is specified, the global maximum is fitted Defaults to [].

plot (bool, optional):

create one plot per peak, showing each single fit. Defaults to False.

verbose (bool, optional):

print out information about each single fit. Defaults to False.

Returns:
params (list of lists):

with one list with the fit-parameters for each peak.

newy (array_like):

fitting curve, using asym_pseudo_voigt for all peaks.

microscopy_data_analysis.peak_fitting.snip(y_data, m, x_data=None)[source]

statistics-sensitive non-linear iterative peak-clipping (with smoothing width = 1, more robust to noise) following the paper: doi:10.1016/j.nima.2008.11.132 (data points should be uniformly spaced)

Args:
y_data (array_like):

uniformly spaced points recommended.

m (int, float if x_data is given):

optimal m should be half the width w of features (w=2m+1).

x_data (array_like,optional):

if x_data is None, it is constructed as the indices enumerating y_data. Defaults to None

Returns:

background_curve (array_like): signal without peaks.

microscopy_data_analysis.peak_fitting.snip_pure(y_data, m, x_data=None)[source]

statistics-sensitive non-linear iterative peak-clipping (without smoothing, vulnerable to noise) following the paper: doi:10.1016/j.nima.2008.11.132 (data points should be uniformly spaced)

Args:
y_data (array_like):

uniformly spaced points recommended.

m (int, float if x_data is given):

optimal m should be half the width w of features (w=2m+1).

x_data (array_like,optional):

if x_data is None, it is constructed as the indices enumerating y_data. Defaults to None

Returns:
background_curve (array_like):

signal without peaks.

microscopy_data_analysis.visualisation module

Created on Mon May 8 15:32:54 2023

@author: kernke

class microscopy_data_analysis.visualisation.image_plotting(images, image_counter=0)[source]

Bases: object

add_keyboard()[source]
addfunc_endpoint_details()[source]

pick lines by left clicking to unpick a line press ‘i’ to delete a line, pick it and press ‘d’ to undo the last change to a line, pick it and press ‘u’ to either show or hide the line overlay press ‘l’

addfunc_image_series(times=None)[source]

navigate multiple images with ‘b’ and ‘n’ press ‘b’: go to image before ; ‘n’ go to next image

addfunc_img_overlays(orig_points, overlay_imgs, overlay_points)[source]

overlay the image with other images corresponding points in all images are needed cycle through data with ‘c’

addfunc_line_features(line_objs=None, line_set=None)[source]

create lines by right clicking pick lines by left clicking to unpick a line press ‘i’ to delete a line, pick it and press ‘d’ to undo the last change to a line, pick it and press ‘u’ to either show or hide the line overlay press ‘l’

addfunc_save_as_json(filepath)[source]

save lines and shifts as .json with ‘s’ filepath needed

addfunc_shifts(shifts=None)[source]

move overlays with the arrow keys after activating this function with ‘m’ deactivating with ‘m’ saves the shift

addfunc_text_input()[source]
static get_next_line_index(line_set)[source]
static get_shift(image_counter, shifts)[source]
show()[source]
class microscopy_data_analysis.visualisation.line_object(x, y, image_counter)[source]

Bases: object

changed
length
x
y
microscopy_data_analysis.visualisation.read_in_json(filepath)[source]
microscopy_data_analysis.visualisation.read_in_json_old(filepath)[source]
microscopy_data_analysis.visualisation.save_as_json(filepath, line_objs, shifts, line_set)[source]
microscopy_data_analysis.visualisation.vis_make_mp4(filename, images, fps)[source]
microscopy_data_analysis.visualisation.vis_make_scale_bar(images, pixratios, lengthperpix, barlength, org, thickness=4, color=(255, 0, 0))[source]
microscopy_data_analysis.visualisation.vis_plot_line_ids(image, sortout, legend=True, alpha=0.5, markersize=0.5)[source]
microscopy_data_analysis.visualisation.vis_zoom(img, zoom_center, final_height, steps, gif_resolution_to_final=1)[source]