Code reference

module level aliases

For user convenience, the following objects are available at the module level.

class qpimage.QPImage

alias of qpimage.core.QPImage

class qpimage.QPSeries

alias of qpimage.series.QPSeries

qpimage.META_KEYS

alias of qpimage.meta.META_KEYS

bg_estimate (background-estimation)

Constants

qpimage.bg_estimate.VALID_FIT_OFFSETS = ['fit', 'gauss', 'mean', 'mode']

valid values for keyword argument fit_offset in estimate()

qpimage.bg_estimate.VALID_FIT_PROFILES = ['offset', 'poly2o', 'tilt']

valid values for keyword argument fit_profile in estimate()

Methods

qpimage.bg_estimate.estimate(data, fit_offset='mean', fit_profile='tilt', border_px=0, from_mask=None, ret_mask=False)[source]

Estimate the background value of an image

Parameters:
  • data (np.ndarray) – Data from which to compute the background value
  • fit_profile (str) –

    The type of background profile to fit:

    • ”offset”: offset only
    • ”poly2o”: 2D 2nd order polynomial with mixed terms
    • ”tilt”: 2D linear tilt with offset (default)
  • fit_offset (str) –

    The method for computing the profile offset

    • ”fit”: offset as fitting parameter
    • ”gauss”: center of a gaussian fit
    • ”mean”: simple average
    • ”mode”: mode (see qpimage.bg_estimate.mode)
  • border_px (float) – Assume that a frame of border_px pixels around the image is background.
  • from_mask (boolean np.ndarray or None) – Use a boolean array to define the background area. The boolean mask must have the same shape as the input data. True elements are used for background estimation.
  • ret_mask (bool) – Return the boolean mask used to compute the background.

Notes

If both border_px and from_mask are given, the intersection of the two is used, i.e. the positions where both, the frame mask and from_mask, are True.

qpimage.bg_estimate.offset_gaussian(data)[source]

Fit a gaussian model to data and return its center

qpimage.bg_estimate.offset_mode(data)[source]

Compute Mode using a histogram with sqrt(data.size) bins

qpimage.bg_estimate.profile_tilt(data, mask)[source]

Fit a 2D tilt to data[mask]

qpimage.bg_estimate.profile_poly2o(data, mask)[source]

Fit a 2D 2nd order polynomial to data[mask]

qpimage.bg_estimate.poly2o_model(params, shape)[source]

lmfit 2nd order polynomial model

qpimage.bg_estimate.poly2o_residual(params, data, mask)[source]

lmfit 2nd order polynomial residuals

qpimage.bg_estimate.tilt_model(params, shape)[source]

lmfit tilt model

qpimage.bg_estimate.tilt_residual(params, data, mask)[source]

lmfit tilt residuals

core (QPImage)

Constants

qpimage.core.VALID_INPUT_DATA = ['field', 'hologram', 'phase', ('phase', 'amplitude'), ('phase', 'intensity')]

valid combinations for keyword argument which_data

Classes

class qpimage.core.QPImage(data=None, bg_data=None, which_data='phase', meta_data={}, holo_kw={}, h5file=None, h5mode='a', h5dtype='float32')[source]

Quantitative phase image manipulation

This class implements various tasks for quantitative phase imaging, including phase unwrapping, background correction, numerical focusing, and data export.

Parameters:
  • data (2d ndarray (float or complex) or list) – The experimental data (see which_data)
  • bg_data (2d ndarray (float or complex), list, or None) – The background data (must be same type as data)
  • which_data (str) – String or comma-separated list of strings indicating the order and type of input data. Valid values are “hologram”, “field”, “phase”, “phase,amplitude”, or “phase,intensity”, where the latter two require an indexable object with the phase data as first element.
  • meta_data (dict) – Meta data associated with the input data. see qpimage.meta.META_KEYS
  • holo_kw (dict) –

    Special keyword arguments for phase retrieval from hologram data (which_data=”hologram”). See qpimage.holo.get_field() for valid keyword arguments.

    New in version 0.1.6.

  • h5file (str, pathlib.Path, h5py.Group, h5py.File, or None) – A path to an hdf5 data file where all data is cached. If set to None (default), all data will be handled in memory using the “core” driver of the h5py’s File class. If the file does not exist, it is created. If the file already exists, it is opened with the file mode defined by hdf5_mode. If this is an instance of h5py.Group or h5py.File, then this will be used to internally store all data.
  • h5mode (str) –

    Valid file modes are (only applies if h5file is a path)

    • ”r”: Readonly, file must exist
    • ”r+”: Read/write, file must exist
    • ”w”: Create file, truncate if exists
    • ”w-” or “x”: Create file, fail if exists
    • ”a”: Read/write if exists, create otherwise (default)
  • h5dtype (str) – The datatype in which to store the image data. The default is “float32” which is sufficient for 2D image analysis and consumes only half the disk space of the numpy default “float64”.

Notes

QPImage is slicable; the following returns a new QPImage with the same meta data, but with all background corrections merged into the raw data:

qpi = QPImage(data=...)
qpi_scliced = qpi[10:20, 40:30]
bg_amp

background amplitude image

bg_pha

background phase image

amp

background-corrected amplitude image

dtype

dtype of the phase data array

field

background-corrected complex field

info

list of tuples with QPImage meta data

meta

dictionary with imaging meta data

pha

background-corrected phase image

raw_amp

raw amplitude image

raw_pha

raw phase image

shape

size of image dimensions

clear_bg(which_data=('amplitude', 'phase'), keys='fit')[source]

Clear background correction

Parameters:
  • which_data (str or list of str) – From which type of data to remove the background information. The list contains either “amplitude”, “phase”, or both.
  • keys (str or list of str) –

    Which type of background data to remove. One of:

    • ”fit”: the background data computed with qpimage.QPImage.compute_bg()
    • ”data”: the experimentally obtained background image
compute_bg(which_data='phase', fit_offset='mean', fit_profile='tilt', border_m=0, border_perc=0, border_px=0, from_mask=None, ret_mask=False)[source]

Compute background correction

Parameters:
  • which_data (str or list of str) – From which type of data to remove the background information. The list contains either “amplitude”, “phase”, or both.
  • fit_profile (str) –

    The type of background profile to fit:

    • ”offset”: offset only
    • ”poly2o”: 2D 2nd order polynomial with mixed terms
    • ”tilt”: 2D linear tilt with offset (default)
  • fit_offset (str) –

    The method for computing the profile offset

    • ”fit”: offset as fitting parameter
    • ”gauss”: center of a gaussian fit
    • ”mean”: simple average
    • ”mode”: mode (see qpimage.bg_estimate.mode)
  • border_m (float) – Assume that a frame of border_m meters around the image is background. The value is converted to pixels and rounded.
  • border_perc (float) – Assume that a frame of border_perc percent around the image is background. The value is converted to pixels and rounded. If the aspect ratio of the image is not one, then the average of the data’s shape is used to compute the percentage in pixels.
  • border_px (float) – Assume that a frame of border_px pixels around the image is background.
  • from_mask (boolean np.ndarray or None) – Use a boolean array to define the background area. The boolean mask must have the same shape as the input data. True elements are used for background estimation.
  • ret_mask (bool) – Return the boolean mask used to compute the background.

Notes

The border_* values are translated to pixel values and the largest pixel border is used to generate a mask image for background computation.

If any of the border_* arguments are non-zero and from_mask is given, the intersection of the two is used, i.e. the positions where both, the frame mask and from_mask, are True.

copy(h5file=None)[source]

Create a copy of the current instance

This is done by recursively copying the underlying hdf5 data.

Parameters:h5file (str, h5py.File, h5py.Group, or None) – see QPImage.__init__
refocus(distance, method='helmholtz', h5file=None, h5mode='a')[source]

Compute a numerically refocused QPImage

Parameters:
  • distance (float) – Focusing distance [m]
  • method (str) – Refocusing method, one of [“helmholtz”,”fresnel”]
  • h5file (str, h5py.Group, h5py.File, or None) – A path to an hdf5 data file where the QPImage is cached. If set to None (default), all data will be handled in memory using the “core” driver of the h5py’s File class. If the file does not exist, it is created. If the file already exists, it is opened with the file mode defined by hdf5_mode. If this is an instance of h5py.Group or h5py.File, then this will be used to internally store all data.
  • h5mode (str) –

    Valid file modes are (only applies if h5file is a path)

    • ”r”: Readonly, file must exist
    • ”r+”: Read/write, file must exist
    • ”w”: Create file, truncate if exists
    • ”w-” or “x”: Create file, fail if exists
    • ”a”: Read/write if exists, create otherwise (default)
Returns:

qpi – Refocused phase and amplitude data

Return type:

qpimage.QPImage

See also

nrefocus
library used for numerical focusing
set_bg_data(bg_data, which_data=None)[source]

Set background amplitude and phase data

Parameters:
  • bg_data (2d ndarray (float or complex), list, QPImage, or None) – The background data (must be same type as data). If set to None, the background data is reset.
  • which_data (str) – String or comma-separated list of strings indicating the order and type of input data. Valid values are “field”, “phase”, “phase,amplitude”, or “phase,intensity”, where the latter two require an indexable object for bg_data with the phase data as first element.

Methods

qpimage.core.copyh5(inh5, outh5)[source]

Recursively copy all hdf5 data from one group to another

Parameters:
  • inh5 (str, h5py.File, or h5py.Group) – The input hdf5 data. This can be either a file name or an hdf5 object.
  • outh5 (str, h5py.File, h5py.Group, or None) – The output hdf5 data. This can be either a file name or an hdf5 object. If set to None, a new hdf5 object is created in memory.

Notes

All data in outh5 are overridden by the inh5 data.

holo (hologram analysis)

Methods

qpimage.holo.find_sideband(ft_data, which=1, copy=True)[source]

Find the side band position of a hologram

The hologram is Fourier-transformed and the side band is determined by finding the maximum amplitude in Fourier space.

Parameters:
  • ft_data (2d ndarray) – Fourier transform of the hologram image
  • which (+1 or -1) –

    which sideband to search for:

    • +1: upper half
    • -1: lower half
  • copy (bool) – copy ft_data before modification
Returns:

fsx, fsy – coordinates of the side band in Fourier space frequencies

Return type:

tuple of floats

qpimage.holo.fourier2dpad(data, zero_pad=True)[source]

Compute the 2D Fourier transform with zero padding

Parameters:
  • data (2d fload ndarray) – real-valued image data
  • zero_pad (bool) – perform zero-padding to next order of 2
qpimage.holo.get_field(hologram, sideband=1, filter_name='disk', filter_size=0.3333333333333333, subtract_mean=True, zero_pad=True, copy=True)[source]

Compute the complex field from a hologram using Fourier analysis

Parameters:
  • hologram (real-valued 2d ndarray) – hologram data
  • sideband (+1, -1, or tuple of (float, float)) –

    specifies the location of the sideband:

    • +1: sideband in the upper half in Fourier space, exact location is found automatically
    • -1: sideband in the lower half in Fourier space, exact location is found automatically
    • (float, float): sideband coordinates in frequencies in interval [1/”axes size”, .5]
  • filter_name (str) –

    specifies the filter to use, one of

    • ”disk”: binary disk with radius filter_size
    • ”smooth disk”: disk with radius filter_size convolved with a radial gaussian (sigma=filter_size/5)
    • ”gauss”: radial gaussian (sigma=0.6*filter_size)
    • ”square”: binary square with side length filter_size
    • ”smooth square”: square with side length filter_size convolved with square gaussian (sigma=filter_size/5)
    • ”tukey”: a square tukey window of width 2*filter_size and alpha=0.1
  • filter_size (float) – Size of the filter in Fourier space in fractions of the distance between central band and sideband. See filter_shape for interpretation of filter_size.
  • subtract_mean (bool) – If True, remove the mean of the hologram before performing the Fourier transform. This setting is recommended as it can reduce artifacts from frequencies around the central band.
  • zero_pad (bool) – Perform zero-padding before applying the FFT. Setting zero_pad to False increases speed but might introduce image distortions such as tilts in the phase and amplitude data or dark borders in the amplitude data.
  • copy (bool) – If set to True, input data is not edited.
  • and y0 are center of the filter (x0) –
  • is factor for "radius" of filter (sqrt(x0² + y0²)/np.pi) (R) –
  • can be "disk" or "gauss" (filter_type) –

Notes

Even though the size of the “gauss” filter approximately matches the frequencies of the “disk” filter, it takes into account higher frequencies as well and thus suppresses ringing artifacts for data that contain jumps in the phase image.

image_data (basic image management)

Constants

qpimage.image_data.COMPRESSION = {'compression': 'gzip', 'compression_opts': 9}

default hdf5 compression keyword arguments

qpimage.image_data.VALID_BG_KEYS = ['data', 'fit']

valid background data identifiers

Classes

class qpimage.image_data.Amplitude(h5, h5dtype='float32')[source]

Bases: qpimage.image_data.ImageData

Dedicated class for amplitude image data

For amplitude image data, background correction is defined by dividing the raw image by the background image.

Parameters:
  • h5 (h5py.Group) – HDF5 group where all data is kept
  • h5dtype (str) – The datatype in which to store the image data. The default is “float32” which is sufficient for 2D image analysis and consumes only half the disk space of the numpy default “float64”.
class qpimage.image_data.Phase(h5, h5dtype='float32')[source]

Bases: qpimage.image_data.ImageData

Dedicated class for phase image data

For phase image data, background correction is defined by subtracting the background image from the raw image.

Parameters:
  • h5 (h5py.Group) – HDF5 group where all data is kept
  • h5dtype (str) – The datatype in which to store the image data. The default is “float32” which is sufficient for 2D image analysis and consumes only half the disk space of the numpy default “float64”.
class qpimage.image_data.ImageData(h5, h5dtype='float32')[source]

Base class for image management

See also

Amplitude
ImageData with amplitude background correction
Phase
ImageData with phase background correction
Parameters:
  • h5 (h5py.Group) – HDF5 group where all data is kept
  • h5dtype (str) – The datatype in which to store the image data. The default is “float32” which is sufficient for 2D image analysis and consumes only half the disk space of the numpy default “float64”.
bg

combined background image data

image

background corrected image data

info

list of background correction parameters

raw

raw (uncorrected) image data

del_bg(key)[source]

Remove the background image data

Parameters:key (str) – One of VALID_BG_KEYS
estimate_bg(fit_offset='mean', fit_profile='tilt', border_px=0, from_mask=None, ret_mask=False)[source]

Estimate image background

Parameters:
  • fit_profile (str) –

    The type of background profile to fit:

    • ”offset”: offset only
    • ”poly2o”: 2D 2nd order polynomial with mixed terms
    • ”tilt”: 2D linear tilt with offset (default)
  • fit_offset (str) –

    The method for computing the profile offset

    • ”fit”: offset as fitting parameter
    • ”gauss”: center of a gaussian fit
    • ”mean”: simple average
    • ”mode”: mode (see qpimage.bg_estimate.mode)
  • border_px (float) – Assume that a frame of border_px pixels around the image is background.
  • from_mask (boolean np.ndarray or None) – Use a boolean array to define the background area. The mask image must have the same shape as the input data.`True` elements are used for background estimation.
  • ret_mask (bool) – Return the mask image used to compute the background.

Notes

If both border_px and from_mask are given, the intersection of the two resulting mask images is used.

The arguments passed to this method are stored in the hdf5 file self.h5 and are used for optional integrity checking using qpimage.integrity_check.check.

get_bg(key=None, ret_attrs=False)[source]

Get the background data

Parameters:
  • key (None or str) – A user-defined key that identifies the background data. Examples are “data” for experimental data, or “fit” for an estimated background correction (see VALID_BG_KEYS). If set to None, returns the combined background image (ImageData.bg).
  • ret_attrs (bool) – Also returns the attributes of the background data.
set_bg(bg, key='data', attrs={})[source]

Set the background data

Parameters:
  • bg (numbers.Real, 2d ndarray, ImageData, or h5py.Dataset) – The background data. If bg is an h5py.Dataset object, it must exist in the same hdf5 file (a hard link is created). If set to None, the data will be removed.
  • key (str) – One of VALID_BG_KEYS)
  • attrs (dict) – List of background attributes

See also

del_bg()
removing background data

Methods

qpimage.image_data.write_image_dataset(group, key, data, h5dtype=None)[source]

Write an image to an hdf5 group as a dataset

This convenience function sets all attributes such that the image can be visualized with HDFView, sets the compression and fletcher32 filters, and sets the chunk size to the image shape.

Parameters:
  • group (h5py.Group) – HDF5 group to store data to
  • key (str) – Dataset identifier
  • data (np.ndarray of shape (M,N)) – Image data to store
  • h5dtype (str) – The datatype in which to store the image data. The default is the datatype of data.
Returns:

dataset – The created HDF5 dataset object

Return type:

h5py.Dataset

integrity_check (check QPImage data)

Exceptions

exception qpimage.integrity_check.IntegrityCheckError[source]

Raised when a QPImage data set is incomplete or corrupt

Methods

qpimage.integrity_check.check(qpi_or_h5file, checks=['attributes', 'background'])[source]

Checks various properties of a qpimage.core.QPImage instance

Parameters:
  • qpi_or_h5file (qpimage.core.QPImage or str) – A QPImage object or a path to an hdf5 file
  • checks (list of str) – Which checks to perform (“attributes” and/or “background”)
Raises:

IntegrityCheckError – if the checks fail

qpimage.integrity_check.check_attributes(qpi)[source]

Check QPimage attributes

Parameters:qpi (qpimage.core.QPImage) –
Raises:IntegrityCheckError – if the check fails
qpimage.integrity_check.check_background(qpi)[source]

Check QPimage background data

Parameters:qpi (qpimage.core.QPImage) –
Raises:IntegrityCheckError – if the check fails

meta (definitions for QPImage meta data)

Constants

qpimage.meta.META_KEYS = ['medium index', 'pixel size', 'time', 'wavelength', 'identifier', 'qpimage version', 'sim center', 'sim index', 'sim model', 'sim radius']

valid qpimage.core.QPImage meta data keys

Exceptions

exception qpimage.meta.MetaDataMissingError[source]

Raised when meta data is missing

Classes

class qpimage.meta.MetaDict(*args, **kwargs)[source]

Bases: dict

Management of meta data variables

Valid key names are combined in the qpimage.meta.META_KEYS variable.

series (QPSeries)

Classes

class qpimage.series.QPSeries(qpimage_list=[], meta_data={}, h5file=None, h5mode='a', identifier=None)[source]

Quantitative phase image series

Parameters:
  • qpimage_list (list) – A list of instances of qpimage.QPImage.
  • meta_data (dict) – Meta data associated with the input data (see qpimage.META_KEYS). This overrides the meta data of the QPImages in qpimage_list and, if h5file is given and h5mode is not “r”, overrides the meta data in h5file.
  • h5file (str, h5py.Group, h5py.File, or None) – A path to an hdf5 data file where all data is cached. If set to None (default), all data will be handled in memory using the “core” driver of the h5py’s File class. If the file does not exist, it is created. If the file already exists, it is opened with the file mode defined by hdf5_mode. If this is an instance of h5py.Group or h5py.File, then this will be used to internally store all data. If h5file is given and qpimage_list is not empty, all QPImages in qpimage_list are appended to h5file in the given order.
  • h5mode (str) –

    Valid file modes are (only applies if h5file is a path):

    • ”r”: Readonly, file must exist
    • ”r+”: Read/write, file must exist
    • ”w”: Create file, truncate if exists
    • ”w-” or “x”: Create file, fail if exists
    • ”a”: Read/write if exists, create otherwise (default)
identifier

unique identifier of the series

add_qpimage(qpi, identifier=None, bg_from_idx=None)[source]

Add a QPImage instance to the QPSeries

Parameters:
  • qpimage (qpimage.QPImage) – The QPImage that is added to the series
  • identifier (str) – Identifier key for qpi
  • bg_from_idx (int or None) – Use the background data from the data stored in this index, creating hard links within the hdf5 file. (Saves memory if e.g. all qpimages is corrected with the same data)
get_qpimage(index)[source]

Return a single QPImage of the series

Parameters:index (int or str) – Index or identifier of the QPImage

Notes

Instead of qps.get_qpimage(index), it is possible to use the short-hand qps[index].