Function Reference

Classes

Holo()

Provides object-oriented access to core functionality of PyHoloscope. See Holo class for details.

FocusStack(img, depthRange, nDepths)

Stores a refocus stack, allowing convenient acccess to each image and ability to write stack to a file. See FocusStack class for details.

PropLUT(imgSize, wavelength, pixelSize, depthRange, nDepths)

Stores a propagator look up table for faster refocusing across multple depths. See PropLUT class for details.

Roi(x, y, width, height)

Region of interest, a rectangle with top left co-ordinates (x, y) with width width and height height. crop method is used to extract the ROI from an image and constrain method is used to limit co-ordinates to adjust the ROI to fit within an image. See Roi class for details.

General Functions

pyholoscope.fourier_plane_display(img)

Returns a log-scale Fourier plane for display purposes.

Returns a 2D numpy array, real.

Parameters:
imgndarray

2D numpy array, real or complex.

pyholoscope.pre_process(img, background=None, normalise=None, window=None, downsample=1.0, numba=False, precision='single')

Carries out steps required prior to refocusing. This includes background correction, normalisation and windowing and downsampling It also coverts image to either to a float64 (if input img is real) or complex float (if input img is complex).

Parameters:
imgndarray

raw hologram, 2D numpy array, real or complex

Keyword Arguments:
backgroundndaarray

2D numpy array (real), backround hologram to be subtracted (default = None)

normalisendarray

2D numpy array (real), background hologram to be divided (default = None)

windowndarray

2D numpy array (real), window to smooth edges. Will be resized to match size of img if necessary. (default = None)

downsamplefloat

factor to downsample image by (default = 1)

Off-axis Holography

pyholoscope.off_axis_demod(hologram, cropCentre, cropRadius, returnFull=False, returnFFT=False, mask=None, cuda=False)

Removes spatial modulation from off-axis hologram to obtain complex field.

By default, returns the complex field as a 2D numpy array of size 2 * cropRadius. If returnFull is True, the returned array will instead by the same size as the input hologram. If returnFFT is True, function returns a tuple (field, FFT) where FFT is a log scaled image of the FFT of the hologram (2D numpy array, real).

Parameters:
hologramndarray

2D numpy array, real, raw hologram

cropCentretuple of (int, int).

pixel location in FFT of modulation frequency

cropRadiusint or (int, int)

semi-diameter of sqaure or rectangle to extract around modulation frequency. Provide a single int for a sqaure area or a tuple of (w,h) for a rectangle.

Keyword Arguments:
returnFullboolean

if true, the returned reconstruction will be the same size as the input hologram, otherwise it will be the 2 * cropRadius. (Default is False)

returnFFTboolean

if True will return a tuple of (demod image, log scaled FFT) for display purposes (Default is False)

maskndarray

2D numpy array, complex. Custom mask to use around demodulation frequency. Must match size of (cropRadiusX, cropRadiusY)

cudaboolean

if True GPU will be used if available.

Returns:

ndarray, reconstructed field as complex numpy array or tuple of (ndarray, ndarray) if returnFFT is True

pyholoscope.off_axis_find_mod(hologram, maskFraction=0.1)

Finds the location of the off-axis holography modulation peak in the FFT.

Parameters:
hologramndarray

2D numpy array, real, raw hologram

Keyword Arguments:
maskFractionfloat

between 0 and 1, fraction of image around d.c. to mask to avoid the d.c. peak being detected (default = 0.1).

Returns:

tuple of (int, int), modulation location in FFT (y location, x location)

pyholoscope.off_axis_find_crop_radius(hologram, maskFraction=0.1)

Estimates the off axis crop radius based on modulation peak position. If the hologram is square, this is the radius of a circle, otherwise if it is rectangular than the crop radius is a tuple of (y radius, x radius), corresponding to to the half the lengths of the two axes of an ellipse.

Parameters:
hologramndarray

2D numpy array, real, raw hologram

Keyword Arguments:
maskFractionfloat

between 0 and 1, fraction of image around d.c. to mask to avoid the d.c. peak being detected (default = 0.1).

Returns:

tuple of (int, int) = (y radius, x radius)

pyholoscope.off_axis_predict_mod(wavelength, pixelSize, numPixels, tiltAngle, rotation=0)

Predicts the location of the modulation peak in the FFT.

Parameters:
wavelegnthfloat

light wavelength in metres

pixelSizefloat

hologram physical pixel size in metres

numPixelsint or (int, int)

hologram size in pixels,

tiltAnglefloat

angle of reference beam on camera in radians

Keyword Arguments:
rotationfloat

rotation of tilt with respect to x axis, in radians (default is 0)

Returns:

tuple of (int, int), location of modulation (x pixel, y pixel)

pyholoscope.off_axis_predict_tilt_angle(hologram, wavelength, pixelSize, maskFraction=0.1)

Returns the reference beam tilt based on the hologram modulation. The angle is returned in radians.

Arguments:
hologramndarray

2D numpy array, real, hologram

wavelengthfloat

light wavelength in metres

pixelSizefloat

hologram physical pixel size in metres

Optional Keyword Arguments:
maskFractionfloat

between 0 and 1, fraction of image around d.c. to mask to avoid the d.c. peak being detected (default = 0.1).

Returns:

float, tilt angle in radians

Numerical Refocusing

An initial check for approximate location of good focus depths prior to a finer search. Used by findFocus, see this function for arguments.

Parameters:
nIntervalsint

number of intervals to divide depth range into.

pyholoscope.focus_score(img, method)

Returns score of how ‘in focus’ an amplitude image is. Score is returned as a float, the lower the better the focus.

Parameters:
imgndarray

2D numpy array, real, image

methodstr

scoring method, options are: Brenner, Sobel, SobelVariance, Var, DarkFcous or Peak

pyholoscope.find_focus(img, wavelength, pixelSize, depthRange, method, **kwargs)

Determine the refocus depth which maximises the focus metric on image. To depth score using only a subset of the image, provide an instance of Roi in scoreROI. Note that the entire image will still be refocused, i.e. this does not provide a speed improvement. To refocus only a small region of the image around the ROI (which is faster), provide a margin in margin, a region with this margin around the ROI will then be refocused. A pre-computed propagator LUT, an instance of PropLUT can be provided in propLUT. Note that if margin is specified, the propagator LUT must be of the correct size, i.e. the same size as the area to be refocused. To perform an initial coarse search to identify the region likely to have the best focus, provide the number of search regions to split the search range into in coarseSearchInterval.

Parameters:
pixelSizefloat

real pixel size of hologram

wavelengthfloat

wavelength of light source

depthRangetuple of (float, float)

min and max depths to search between

methodstr

scoring method (see focus_score for list)

Keyword Arguments:
backgroundndarray or None

background image (default is None)

windowndarray or None

spatial window (default is None)

scoreROIROI or None

region of image to apply scoring to (default is None, in which case it applies to whole image.)

marginint or None

if not none, only a region with this margin around the scoreROI will be refocused prior to scoring

propLUTpropLUT or None

propagator look up table (default is None)

coarseSearchIntervalint or None

number of intervals to divide depth range into for initial search. Default is None, i.e. no initial search.

useNumbaboolean

if True, uses Numba version of functions (default is False)

useCudaboolean

if True, uses GPU where available

pyholoscope.focus_score_curve(img, wavelength, pixelSize, depthRange, nPoints, method, **kwargs)

Produces a plot of focus score against depth, mainly useful for debugging erroneous focusing.

pyholoscope.propagator(gridSize, wavelength, pixelSize, depth, geometry='plane', precision='single', cascade=1)

Creates Fourier domain propagator for angular spectrum method. Returns the propagator as a complex 2D numpy array. Generation is sped up by only calculating top left quadrant and then duplicating (with flips) to create the other quadrants.

Parameters:
gridSizefloat or (float, float)

size of square image (in pixels) to refocus, or if tuple of (float, float), size of rectangular image.

pixelSizefloat

physical size of pixels

wavelengthfloat

in same units as pixelSize

depthfloat

refocus depth in same units as pixelSize

Keyword Arguments:
geometrystr

‘plane’ (default) or ‘point’

precisionstr

numerical precision of ouptut, ‘single’ (defualt) or ‘double’

cascadeint

for use with cascade method, depth will be dividing by by this number

pyholoscope.propagator_numba(gridSize, wavelength, pixelSize, depth, geometry='plane', precision='single')

Numba optimised version of propagator(). Creates Fourier domain propagator for angular spectrum method. Returns the propagator as a complex 2D numpy array. Generation is sped up by only calculating top left quadrant and then duplicating (with flips) to create the other quadrants.

Note that ‘precision’ is currently not implemented in the numba version.

Parameters:
gridSizefloat or (float, float)

size of square image (in pixels) to refocus, or if tuple of (float, float), size of rectangular image.

pixelSizefloat

physical size of pixels

wavelengthfloat

in same units as pixelSize

depthfloat

refocus depth in same units as pixelSize

Keyword Arguments:
geometrystr

‘plane’ (default) or ‘point’

precisionstr

numerical precision of ouptut, ‘single’ (defualt) or ‘double’ [NOT IMPLEMENTED]

cascadeint

for use with cascade method, depth will be dividing by by this number

pyholoscope.refocus(img, propagator, **kwargs)

Refocuses a hologram using the angular spectrum method. Takes a hologram ‘hologram’ wich may be a real or complex 2D numpy array (with any pre-processing such as background removal already performed) and a pre-computed ‘propagator’ which can be generated using the function ‘propagator()’.

Parameters:
imgndarray

2D numpy arrayraw hologram.

propagatorndarray

2D numpy array, as returned from propagator().

Keyword Arguments:
FourierDomainboolean

if True then img is assumed to be already the FFT of the hologram, useful for speed when performing multiple refocusing of the same hologram. (default = False)

cudaboolean

if True GPU will be used if available.

otherspass any keyword arguments from pre_process() to

apply this pre-processing prior to refocusing

pyholoscope.refocus_and_score(depth, imgFFT, pixelSize, wavelength, method, scoreROI=None, propLUT=None, useNumba=False, useCuda=False, precision='single')

Refocuses an image to specificed depth and returns focus score, used by findFocus.

Parameters:
depthfloat

depth to focus to

imgFFTndarray, complex

FFT of hologram

pixelSizefloat

real pixel size of hologram

wavelength: float

wavelength of light source

methodstr,

scoring method (see focus_score for list)

Keyword Arguments:
scoreROIROI or None

region of image to apply scoring to (default is None, in which case it applies to whole image.)

propLUpropLUT or None

propgator look-up table (default is None, propagator is calculate for each depth)

useNumbaboolean

if True, uses Numba version of functions (default is False)

useCudaboolean

if True, uses GPU where available

precisionstr

‘single’ (default) or ‘double’, precision of calculated propagator

pyholoscope.refocus_stack(img, wavelength, pixelSize, depthRange, nDepths, **kwargs)

Numerical refocusing of a hologram to produce a depth stack.

Parameters:
pixelSizefloat

real pixel size of hologram

wavelength: float

wavelength of light source

depthRange: tuple of (float, float)

min and max depths of stack

nDepthsint

number of depths to refocus to within depthRange

Keyword Arguments:
backgroundndarray or None

background image (default is None)

windowndarray or None

spatial window (default is None)

scoreROIROI or None

region of image to apply scoring to (default is None, in which case it applies to whole image.)

coarseSearchIntervalint or None

number of intervals to divide depth range into for initial search. Default is None, i.e. no initial search.

useNumbaboolean

if True, uses Numba version of functions (default is False)

useCudaboolean

if True, uses GPU where available

Phase Functions

pyholoscope.mean_phase(img)

Returns the mean phase of a field or phase map.

Parameters:
imgndarray

2D numpy array, real or complex, the field or phase map

pyholoscope.obtain_tilt(img)

Estimates the global tilt in the 2D unwrapped phase.

This can be used to correcte tilts in the phase due to, for example, a tilt in the coverglass. Returns a phase map approximating the tilt as a 2D real numpy array.

Parameters:
imgndarray

2D numpy array, real. Unwrapped phase.

pyholoscope.phase_gradient(img)

Returns the amplitude of the phase gradient of an image.

This function is able to handle wrapped phase without finding an edge at the wrap points. Returns a 2D numpy array, real containing the amplitude of the gradient at each point.

Parameters:
imgndarray

2D numpy array, real or complex, the field or phase map

pyholoscope.phase_gradient_amp(img)

Returns the amplitude of the phase gradient of an image.

This isn’t very useful by itself if applied to wrapped phase as it find an edge whenever the phase is wrapped, phase_gradient avoids this problem.

Parameters:
imgndarray

2D numpy array, real or complex, the field or phase map

pyholoscope.phase_gradient_dir(img)

Returns the directional phase gradient of an image.

The output is a complex 2D numpy array, with the horizontal and vertical gradients encoded in the real and imaginary parts.

Parameters:
imgndarray

2D numpy array, real or complex, the field or phase map

pyholoscope.phase_unwrap(img)

Returns unwrapped version of 2D phase map.

Parameters:
imgndarray

2D numpy array, real. Wrapped phase.

pyholoscope.relative_phase(img, background)

Removes global phase from image using reference (background) field.

The function works on both fields (complex arrays) and phase maps (real arrays), and returns a corrected field/phase map of the same type.

Parameters:
imgndarray

2D numpy array, real or complex. If real it is taken to be phase map, otherwise if complex it is the field.

backgroundndarray

2D numpy array, real or complex. Backround phase/field to subtract. Must be same type and size as img.

pyholoscope.relative_phase_self(img, roi=None)

Makes the phase in an image relative to the mean phase in either the whole image or a specified ROI of the image.

The function works on both fields (complex arrays) and phase maps (real arrays), and returns a corrected field/phase map of the same type.

Parameters:
imgndarray

2D numpy array, real or complex. If real it is taken to be phase map, otherwise if complex it is the field.

Keyword Arguments:
roipyholoscope.Roi

region of interest to make phase relative to. In the output image the mean phase in this region will be zero. (default = None)

pyholoscope.synthetic_DIC(img, shearAngle=3.141592653589793)

Generates a simple, non-rigorous DIC-style image for display.

The ouput should appear similar to a relief map, with dark and light regions correspnding to positive and negative phase gradients along the shear angle direction (default is horizontal = 0 rad). The input must be the complex field, not a phase map.

Parameters:
imgndarray

2D numpy array, complex, the field.

Keyword Arguments:
shearAnglefloat

angle in radians of the shear direction. (default = pi)

Utility Functions : Loading and Saving

pyholoscope.load_image(file, square=False)

Loads an image from a file and returns as numpy array.

Parameters:
filestr

filename to load image from, including exension.

Keyword Arguments:
squareboolean

if True, non-square will be made square by taking the largest possible central square, default is False.

Returns:

ndarray, 2D image

pyholoscope.save_image(img, file)

Saves an image stored as numpy array to an 8 bit tif.

Parameters:
imgndarray

image to save

filestr

filename to load image from, including extension.

pyholoscope.save_amplitude_image8(img, filename)

Saves amplitude information as an 8 bit tif.

Parameters:
imgndarray

image to save

filestr

filename to load image from, including extension.

pyholoscope.save_amplitude_image16(img, filename)

Saves amplitude information as a 16 bit tif.

Parameters:
imgndarray

image to save

filestr

filename to load image from, including extension.

pyholoscope.save_phase_image(img, filename)

Saves phase as 16 bit tif. The phase is scaled so that 2pi = 65536.

Parameters:
imgndarray

2D numpy array, either complex field or real (phase map)

filenamestr

path to file to save to. If exists will be over-written.

Utility Functions : Image Types

pyholoscope.get8bit(img)

Returns 8 bit representation of amplitude and phase of field.

Returns a tuple of amplitude and phase, both real 2D numpy arrays of type uint8. Amplitude is scaled between 0 and 255, phase is mapped to between 0 and 255, with 0 = 0 radians and 255 = 2pi radians.

Parameters:
imgndarray

2D numpy array, complex or real

Returns:

tuple of (ndarray, ndarray), 8 bit amplitude and phase maps

pyholoscope.get16bit(img)

Returns 16 bit representation of amplitude and phase of field.

Returns a tuple of amplitude and phase, both real 2D numpy arrays of type uint16. Amplitude is scaled between 0 and 2^16 -1, phase is mapped to between 0 and 2^16 - 1, with 0 = 0 radians and 2^16 - 1 = 2pi radians.

Parameters:
imgndarray

2D numpy array, complex or real

Returns:

tuple of (ndarray, ndarray), 16 bit amplitude and phase maps

pyholoscope.magnitude(img)

Returns magnitude of complex image.

Parameters:
imgndarray

complex image

Returns:

ndarray, magnitude image

pyholoscope.amplitude(img)

Returns amplitude of complex image.

Parameters:
imgndarray

complex image

Returns:

ndarray, amplitude image

pyholoscope.phase(img)

Returns phase of complex image, between 0 and 2pi.

Parameters:
imgndarray

complex image

Returns:

ndarray, phase map

Utility Functions : Windowing

pyholoscope.extract_central(img, boxSize=None)

Extracts square of size boxSize*2 from centre of img. If boxSize is not specified, the largest possible square will be extracted.

Parameters:
imgndarray

complex or real image

Keyword Arguments:
boxSizeint or None

size of square to be extracted

Returns:

ndarray, central square from image

pyholoscope.circ_window(imgSize, circleRadius, dataType='float32')

Produces a circular or elipitcal mask on grid of imgSize.

Parameters:
imgSizeint or (int, int)

size of output image. Provide a single int to generate a square image of that size, otherwise provide (w,h) to produce a rectangular image.

circleRadiusfloat or (float, float)

Pixel values inside this radius will be 1. Provide a tuple of (x,y) to have different x and y radii.

Keyword Arguments:
dataTypestr

data type of returned array (default is ‘float32’)

Returns:

ndarray, 2D numpy array containing mask

pyholoscope.circ_cosine_window(imgSize, circleRadius, skinThickness, dataType='float32')

Produces a circular or elliptical cosine window mask on grid of imgSize.

Parameters:
imgSizeint or (int, int)

size of output image. Provide a single int to generate a square image of that size, otherwise provide (w,h) to produce a rectangular image.

circleRadiusfloat or (float, float)

Pixel values inside this radius will be 1. Provide a tuple of (x,y) to have different x and y radii.

skinThicknessfloat

size of smoothed area inside circle/ellipse

Keyword Arguments:
dataTypestr

data type of returned array (default is ‘float32’)

Returns:

ndarray, 2D numpy array containing mask

pyholoscope.square_cosine_window(imgSize, radius, skinThickness, dataType='float32')

Produces a square cosine window mask on grid of imgSize * imgSize. Mask is 0 for radius > circleSize and 1 for radius < (circleSize - skinThickness). The intermediate region is a smooth squared cosine function.

Parameters:
imgSizeint or (int, int)

size of output image. Provide a single int to generate a square image of that size, otherwise provide (w,h) to produce a rectangular image.

circleRadiusfloat or (float, float)

Pixel values inside this radius will be 1. Provide a tuple of (x,y) to have different x and y radii.

skinThicknessfloat

size of smoothed area inside circle/ellipse

Keyword Arguments:
dataTypestr

data type of returned array (default is ‘float32’)

Returns:

ndarray, 2D numpy array containing mask

pyholoscope.invert(img)

Inverts an image, largest value becomes smallest and vice versa.

Parameters:
imgndarray

numpy array, input image

Returns:

ndarray, inverted image

pyholoscope.dimensions(inp)

Helper to obtain width and height in functions which accept multiple ways to send this information. The input may either be a single value, for a square image, a tuple of (h, w) or a 2D array.

Parameters:

inp : int or (int, int) or ndarray

Returns:

tuple of (int, int), width and height

Simulation

pyholoscope.sim.off_axis(objectField, wavelength, pixelSize, tiltAngle, rotation=0.7853981633974483, OPD=0)

Generates simulated off-axis hologram.

Arguments:
objectFieldndarray, complex

complex field representing object

wavelengthfloat

wavelength of simulated light source

pixelSizefloat

real size of pixels in hologram

tiltAnglefloat

angle of reference beam on camera in radians

Keyword Arguments:
rotationfloat

rotation of the tilt with respect to x axis in rad (Default is pi/4 = 45 deg)

OPD : optical path difference between beams (Default is 0)