libics.tools.trafo
coordinates
- libics.tools.trafo.coordinates.assume_coords_type(*coords, coord_type=None, names=None, **components)
Converts coordinates into a specified format.
Multidimensional arrays of multidimensional coordinates can be specified in three different formats:
“coords”: A single array whose coordinates are located in the last axis, i.e., array.shape = (…, n_dim).
“components”: A list of arrays, where each list item represents one coordinate, i.e., len(array) = n_dim.
“names”: Keyword arguments, where the keyword names specify the respective coordinate, i.e., len(kwargs) = n_dim.
- Parameters
- *coords, **componentsnp.ndarray
Coordinates (may be given in any of the above formats).
- coord_typestr or None
Format of the coordinates: “coords”, “components”, “names”. If None, uses the input format.
- nameslist(tuple(str))
Component names in the coordinate order. Each tuple contains aliases for the respective component. If coord_type == “names”, the first item of the tuple is used as key.
- Returns
- coords
Coordinates in the format specified by coord_type.
- Raises
- ValueError
If coord_type is invalid.
- IndexError, KeyError
If names is incompatible with **components.
- libics.tools.trafo.coordinates.cv_cartesian_to_cylindrical(*coords, ret_type=None, **components)
Converts cartesian to cylindrical \((\rho, \phi, z)\) coordinates.
where \(r \in [0, \infty]\) is the in-plane radial, \(\phi \in [0, 2 \pi]\) is the polar, and \(z \in [-\infty, \infty]\) is the vertical coordinate.
- libics.tools.trafo.coordinates.cv_cartesian_to_polar(*coords, ret_type=None, **components)
Converts cartesian to polar \((\rho, \phi)\) coordinates.
where \(r \in [0, \infty]\) is the radial, \(\phi \in [0, 2 \pi]\) is the polar coordinate.
- libics.tools.trafo.coordinates.cv_cartesian_to_spherical(*coords, ret_type=None, **components)
Converts cartesian to spherical \((r, \theta, \phi)\) coordinates.
where \(r \in [0, \infty]\) is the radial, \(\theta \in [0, \pi]\) is the polar, and \(\phi \in [0, 2 \pi]\) is the azimuthal coordinate.
- libics.tools.trafo.coordinates.cv_cylindrical_to_cartesian(*coords, ret_type=None, **components)
Converts cylindrical \((\rho, \phi, z)\) to cartesian coordinates.
where \(r \in [0, \infty]\) is the in-plane radial, \(\phi \in [0, 2 \pi]\) is the polar, and \(z \in [-\infty, \infty]\) is the vertical coordinate.
- libics.tools.trafo.coordinates.cv_polar_to_cartesian(*coords, ret_type=None, **components)
Converts polar \((\rho, \phi)\) to cartesian coordinates.
where \(r \in [0, \infty]\) is the radial, \(\phi \in [0, 2 \pi]\) is the polar coordinate.
- libics.tools.trafo.coordinates.cv_spherical_to_cartesian(*coords, ret_type=None, **components)
Converts spherical \((r, \theta, \phi)\) to cartesian coordinates.
where \(r \in [0, \infty]\) is the radial, \(\theta \in [0, \pi]\) is the polar, and \(\phi \in [0, 2 \pi]\) is the azimuthal coordinate.
- libics.tools.trafo.coordinates.get_coords_type(*coords, **components)
fourier
- libics.tools.trafo.fourier.fft(data, axes=None, time_range=None, frequency_start=None, norm=None)
Computes the Fast Fourier Transform of an array.
Computes the forward (time->frequency) transformation and interpretes the data transformation as continuous Fourier transform.
\[\tilde{g} (f) = \int_{-\inf}^{\inf} g (t) e^{-i 2 \pi f t} dt\]- Parameters
- dataArray[complex or float]
The array data to be Fourier transformed.
- axesint or Iter[int]
Indices of dimensions to be transformed. If None, transforms all.
- time_rangetuple(float)|str|None or Iter[thereof]
Time range which data represents. If Iter[…], specifies the time range per transformed axis. tuple(float): specifies the time range (ta, tb). None: If data is ArrayData infers time range, otherwise “zero”. “zero”: uses time range (0, N-1). N is data size in resp. dim. “center”: uses time range (-(N//2), (N+1)//2 - 1).
- frequency_startfloat|str|None or Iter[thereof]
Frequency range start of returned data. If Iter[…], uses the respective value in each axis. float: specifies the frequency-range start value. None or “zero”: uses 0. “center”: uses `-(N//2) * df.
- normstr
If data is np.ndarray, norm specifies DFT normalization. FFT: “forward”: 1/N, “ortho”: 1/√N, “backward”: 1.
- Returns
- ftArray[complex]
Fourier transformed data. Returns same data type as data.
Notes
Variable notation: data range (ta, tb), data steps dt, data span tt for time domain. (fa, fb), df, ff analogously for frequency domain.
Setting explicit time ranges and frequency ranges are important to obtain correct Fourier transformed phases and correct assignment of frequencies.
- libics.tools.trafo.fourier.ifft(data, axes=None, frequency_range=None, time_start=None, norm=None)
Computes the inverse Fast Fourier Transform of an array.
Computes the backward (frequency->time) transformation and interpretes the data transformation as continuous Fourier transform.
\[g (t) = \int_{-\inf}^{\inf} \tilde{g} (f) e^{i 2 \pi f t} df\]For parameters and return values, see
fft().Notes
- normstr
If data is np.ndarray, norm specifies DFT normalization. Inv. FFT: “forward”: 1, “ortho”: 1/√N, “backward”: 1/N.
linear
- class libics.tools.trafo.linear.AffineTrafo(matrix=array([[1., 0.], [0., 1.]]), offset=array([0., 0.]))
Bases:
libics.core.io.base.FileBase,libics.core.data.types.AttrHashBaseDefines an affine transformation in arbitrary dimensions.
- Parameters
- matrixnp.ndarray(2, float)
Transformation matrix.
- offsetnp.ndarray(1, float)
Transformation offset.
- Attributes
- fixed_point
- matrix_to_origin
- matrix_to_target
- ndim
- offset_to_origin
- offset_to_target
Methods
__call__(*args[, direction])Performs a transformation.
attributes()Default saved attributes getter.
concatenate(other)Returns an AffineTrafo object which concatenates two transformations.
coord_to_origin(target_coords)Transforms given target coordinates into origin coordinates.
coord_to_target(origin_coords)Transforms given origin coordinates into target coordinates.
cv_offset_shift_to_origin(shift)Converts an offset shift from target to origin space.
cv_offset_shift_to_target(shift)Converts an offset shift from origin to target space.
cv_to_origin(target_array, origin_shape[, ...])Convert an array in target coordinates to origin coordinates.
cv_to_target(origin_array, target_shape[, ...])Convert an array in origin coordinates to target coordinates.
fit_affine_transform(origin_coords, ...)Fits the affine transform matrix and offset vector.
Mask selecting which origin coordinates lie inside a target rectangle.
Mask selecting which target coordinates lie inside an origin rectangle.
Gets the origin unit vectors in target coordinates.
Gets the target unit vectors in origin coordinates.
invert()Returns the inverse AffineTrafo object.
load(file_path, **kwargs)Wrapper for
load()function.save(file_path, **kwargs)Wrapper for
save()function.set_matrix_by_origin_unit_vectors(unit_vecs, ...)Sets the transformation matrix by specifying the origin unit vectors.
set_matrix_by_target_unit_vectors(unit_vecs, ...)Sets the transformation matrix by specifying the target unit vectors.
copy
set_offset_by_fixed_point
set_offset_by_point_pair
- HASH_KEYS = {'matrix', 'offset'}
- LOGGER = <Logger libics.tools.trafo.linear.AffineTrafo (WARNING)>
- SER_KEYS = {'matrix', 'offset'}
- concatenate(other)
Returns an AffineTrafo object which concatenates two transformations.
First transform: other, second transform: self.
- coord_to_origin(target_coords)
Transforms given target coordinates into origin coordinates.
See
coord_to_target().
- coord_to_target(origin_coords)
Transforms given origin coordinates into target coordinates.
- Parameters
- origin_coordsnp.ndarray(float)
Coordinates in origin space. The different dimensions should be placed on the last axes (dimensions: […, ndim]).
- Returns
- target_coordsnp.ndarray(float)
Transformed coordinates in target space.
- copy()
- cv_offset_shift_to_origin(shift)
Converts an offset shift from target to origin space.
- cv_offset_shift_to_target(shift)
Converts an offset shift from origin to target space.
- cv_to_origin(target_array, origin_shape, centered=False, supersample=None, **kwargs)
Convert an array in target coordinates to origin coordinates.
See
cv_to_target().
- cv_to_target(origin_array, target_shape, centered=False, supersample=None, **kwargs)
Convert an array in origin coordinates to target coordinates.
- Parameters
- origin_arraynp.ndarray(float) or ArrayData(float)
Array in origin coordinates.
- target_shapetuple(int) or ArrayData(float)
Shape of target array. If ArrayData, loads the transformed array into this object.
- centeredbool
Only relevant if target_shape is tuple(int). If True, sets the origin zero to the center of the array. Otherwise assumes the center to be at index (0, 0).
- supersampleint
Origin array supersampling repetitions (for sharper edges).
- **kwargs
See scipy documentation for
scipy.ndimage.map_coordinates. Notable options: order : int (interpolation order).
- Returns
- target_arraynp.ndarray(float) or ArrayData(float)
Array transformed to target coordinates. Return type depends on target_shape type.
Notes
Performs subsequent transformations from image to origin to target coordinates.
Interpolates into the requested target shape.
For algorithm see
_cv_array().
- fit_affine_transform(origin_coords, target_coords)
Fits the affine transform matrix and offset vector.
- Parameters
- origin_coords, target_coordslist(np.ndarray(1, float))
List of (origin, target) coordinates in corresponding order.
- Returns
- successbool
Whether transformation fit succeeded. Matrix and offset attributes are only written in the case of success.
Notes
Following H. Späth, Math. Com. 9 (1), 27-34 (2004). Variable naming convention:
q: origin coordinates.
p: target coordinates.
m: transform matrix.
b: transform offset.
- property fixed_point
- get_mask_origin_coords_within_target_rect(coords, rect=None, center=None, size=None)
Mask selecting which origin coordinates lie inside a target rectangle.
- get_mask_target_coords_within_origin_rect(coords, rect=None, center=None, size=None)
Mask selecting which target coordinates lie inside an origin rectangle.
- get_origin_unit_vectors()
Gets the origin unit vectors in target coordinates.
- Returns
- origin_unit_vectorsnp.ndarray(2, float)
List of unit vectors, i.e., origin_unit_vectors[i] is the unit vector along the i-th dimension in origin space.
- get_target_unit_vectors()
Gets the target unit vectors in origin coordinates.
- Returns
- target_unit_vectorsnp.ndarray(2, float)
List of unit vectors, i.e., target_unit_vectors[i] is the unit vector along the i-th dimension in target space.
- invert()
Returns the inverse AffineTrafo object.
- property matrix_to_origin
- property matrix_to_target
- property ndim
- property offset_to_origin
- property offset_to_target
- set_matrix_by_origin_unit_vectors(unit_vecs, **kwargs)
Sets the transformation matrix by specifying the origin unit vectors.
- Parameters
- unit_vecsIterable[np.ndarray]
Origin unit vectors in target units.
- **kwargs
See
_get_matrix_from_unit_vectors().
- set_matrix_by_target_unit_vectors(unit_vecs, **kwargs)
Sets the transformation matrix by specifying the target unit vectors.
- Parameters
- unit_vecsIterable[np.ndarray]
Target unit vectors in origin units.
- **kwargs
See
_get_matrix_from_unit_vectors().
- set_offset_by_fixed_point(fixed_point)
- set_offset_by_point_pair(origin_point, target_point)
- class libics.tools.trafo.linear.AffineTrafo2d(matrix=array([[1., 0.], [0., 1.]]), offset=array([0., 0.]))
Bases:
libics.tools.trafo.linear.AffineTrafoMaps origin pixel positions to target pixels positions.
Convention:
target_coord = matrix * origin_coord + offset.Usage:
Take images for different single-pixel illuminations.
Calculate transformation parameters with
calc_trafo().Perform transforms with call method (or
cv_to_target(),cv_to_origin()).
- Attributes
- fixed_point
- matrix_to_origin
- matrix_to_target
- ndim
- offset_to_origin
- offset_to_target
Methods
__call__(*args[, direction])Performs a transformation.
attributes()Default saved attributes getter.
calc_trafo(origin, target[, algorithm, ...])Estimates the transformation parameters.
concatenate(other)Returns an AffineTrafo object which concatenates two transformations.
coord_to_origin(target_coords)Transforms given target coordinates into origin coordinates.
coord_to_target(origin_coords)Transforms given origin coordinates into target coordinates.
cv_offset_shift_to_origin(shift)Converts an offset shift from target to origin space.
cv_offset_shift_to_target(shift)Converts an offset shift from origin to target space.
cv_to_origin(target_array, origin_shape[, ...])Convert an array in target coordinates to origin coordinates.
cv_to_target(origin_array, target_shape[, ...])Convert an array in origin coordinates to target coordinates.
find_peak_coordinates(origin, target[, ...])Finds peak coordinates.
fit_affine_transform(origin_coords, ...)Fits the affine transform matrix and offset vector.
fit_peak_coordinates(image[, snr, max_sum_ratio])Uses a Gaussian fit to obtain the peak coordinates of an image.
get_mask_origin_coords_within_target_rect(coords)Mask selecting which origin coordinates lie inside a target rectangle.
get_mask_target_coords_within_origin_rect(coords)Mask selecting which target coordinates lie inside an origin rectangle.
- Returns
get_origin_unit_vectors()Gets the origin unit vectors in target coordinates.
- Returns
get_target_unit_vectors()Gets the target unit vectors in origin coordinates.
invert()Returns the inverse AffineTrafo object.
load(file_path, **kwargs)Wrapper for
load()function.magnify(factor)Returns an AffineTrafo object whose magnification is scaled.
rotate(angle)Returns an AffineTrafo object whose angle is shifted.
save(file_path, **kwargs)Wrapper for
save()function.set_matrix_by_origin_unit_vectors(unit_vecs, ...)Sets the transformation matrix by specifying the origin unit vectors.
set_matrix_by_target_unit_vectors(unit_vecs, ...)Sets the transformation matrix by specifying the target unit vectors.
set_origin_axes([magnification, angle, offset])Sets the origin coordinate system axes.
set_target_axes([magnification, angle, offset])Sets the target coordinate system axes.
shift(offset[, ax])Returns an AffineTrafo object whose offset is shifted.
copy
set_offset_by_fixed_point
set_offset_by_point_pair
shift_origin_axes
shift_target_axes
- LOGGER = <Logger libics.tools.trafo.linear.AffineTrafo2d (WARNING)>
- calc_trafo(origin, target, algorithm='fit', print_progress=False, **kwargs)
Estimates the transformation parameters.
Wrapper for peak coordinate finding and transformation fitting.
- Parameters
- originlist(np.ndarray(2, float) or (x, y))
List of origin images or coordinates.
- targetlist(np.ndarray(2, float) or (x, y))
List of target images or coordinates.
- algorithmstr
Algorithm to use to determine coordinates for given image. “fit”, “max”.
- print_progressbool
Whether to print a progress bar to console.
- **kwargs
Keyword arguments passed to
fit_peak_coordinates().
- Returns
- retbool
Whether calculation was successful.
Notes
Coordinate and image order must be identical.
At least two images are required. Additional data is used to obtain a more accurate map.
- find_peak_coordinates(origin, target, algorithm='fit', print_progress=False, **kwargs)
Finds peak coordinates.
See
calc_trafo().
- fit_peak_coordinates(image, snr=1.5, max_sum_ratio=0.0001)
Uses a Gaussian fit to obtain the peak coordinates of an image.
- Parameters
- imagenp.ndarray(2, float) or ArrayData
Image to be analyzed.
- snrfloat
Maximum-to-mean ratio required for fit.
- max_sum_ratiofloat
Maximum-to-sum ratio required for fit.
- Returns
- x, yfloat, None
(Fractional) image index coordinates of fit position. None: If fit failed.
- get_origin_axes()
- Returns
- magnification(float, float)
Length of unit vectors in target units.
- angle(float, float)
Angle of unit vectors with respect to target axes in radians (rad).
- offset(float, float)
Coordinate system zero position in target units.
- get_target_axes()
- Returns
- magnification(float, float)
Length of unit vectors in origin units.
- angle(float, float)
Angle of unit vectors with respect to origin axes in radians (rad).
- offset(float, float)
Coordinate system zero position in origin units.
- magnify(factor)
Returns an AffineTrafo object whose magnification is scaled.
- rotate(angle)
Returns an AffineTrafo object whose angle is shifted.
- set_origin_axes(magnification=array([1., 1.]), angle=array([0., 0.]), offset=array([0., 0.]))
Sets the origin coordinate system axes.
- Parameters
- magnification(float, float)
Length of unit vectors in target units.
- angle(float, float)
Angle of unit vectors with respect to target axes in radians (rad).
- offset(float, float)
Coordinate system zero position in target units.
- set_target_axes(magnification=array([1., 1.]), angle=array([0., 0.]), offset=array([0., 0.]))
Sets the target coordinate system axes.
- Parameters
- magnification(float, float)
Length of unit vectors in origin units.
- angle(float, float)
Angle of unit vectors with respect to origin axes in radians (rad).
- offset(float, float)
Coordinate system zero position in origin units.
- shift(offset, ax='origin')
Returns an AffineTrafo object whose offset is shifted.
- shift_origin_axes(offset)
- shift_target_axes(offset)
resize
- libics.tools.trafo.resize.center_crop(center, crop_rect, shape=None)
Centers a crop index rectangle.
- libics.tools.trafo.resize.crop_image(mask)
Crops to the smallest rectangle containing all non-masked indices. Returns the slice for cropping.
- Parameters
- masknp.ndarray(2, bool)
Mask where True corresponds to indices not to be cropped. TODO: generalize for multiple dimensions.
- Returns
- croptuple((int, int))
Cropping index rectangle (min, max). Dimensions: [ar_ndim, 2].
Notes
From https://codereview.stackexchange.com/questions/132914. Use
libics.core.util.misc.cv_index_rect_to_slice()to convert the index rectangle to slices.Examples
>>> x = y = np.arange(7) - 3 >>> X, Y = np.meshgrid(x, y, indexing="ij") >>> F = X**2 + Y**2 >>> mask = F < 4 >>> crop = crop_image(mask) >>> crop ((2, 5), (2, 5)) >>> F[misc.cv_index_rect_to_slice(crop)] array([[2, 1, 2], [1, 0, 1], [2, 1, 2]], dtype=int32)
- libics.tools.trafo.resize.find_centroid(np_array)
Finds the centroid of a multi-dimensional numpy array.
- Parameters
- np_arraynumpy.ndarray
Numpy array for which the centroid is calculated.
- Returns
- centroid_coordtuple(int)
Index coordinates of the centroid.
- libics.tools.trafo.resize.fit_to_aspect(np_array, aspect_ratio, crop, center, fit_mode='enlarge', center_mode='center')
Changes a crop position to follow an aspect ratio.
- Parameters
- np_arraynumpy.ndarray
Image data.
- aspect_ratiotuple(float)
Cropped pixel ratios between image dimensions.
- croptuple(tuple(int))
Target crop coordinates with format ((ind_min_x, ind_min_y), (ind_max_x, ind_max_y)).
- centertuple(int)
Center index coordinates.
- fit_mode“enlarge”, “reduce”
Whether the crop should be enlarged or reduced with respect to the target crop.
- center_mode“center”, “off”
Whether the given center coordinates should be in the center of the fitted crop image.
- Returns
- croptuple(tuple(int))
Fitted crop coordinates with format ((ind_min_x, ind_min_y), (ind_max_x, ind_max_y)).
- libics.tools.trafo.resize.resize_on_condition(np_array, cond='cut_all', **kwargs)
Finds the rectangle that contains/avoids all occurences of a given value.
- Parameters
- np_arraynp.ndarray
Array to be resized.
- condcallable or str
- Callable:
Condition function that returns False if the respective hypersurface should be cut. Call signature:
cond(np.array(np_array.ndim - 1)) -> bool.
- “cut_all”, “cut_any”:
Remove boundary hypersurfaces (only, partially) containing kwargs[“val”].
- “keep_all”, “keep_any”:
Remove boundary hypersurfaces not (only, partially) containing kwargs[“val”].
- val
See cond -> “cut”, “keep”.
- Returns
- cropnp.array(2, int)
Crop coordinates with format ((ind_min_x, ind_min_y, …), (ind_max_x, ind_max_y, …)).
- libics.tools.trafo.resize.resize_on_filter_maximum(np_array, min_mass=None, min_val=None, aspect_ratio=None, zero=True, factor=1)
Performs maximum filters to obtain the area around a peak.
- Parameters
- np_arraynp.ndarray
Non-negative array to be resized.
- min_massfloat
Required relative mass within resized area.
- min_valfloat
Required relative value within resized area.
- aspect_ratiofloat or None
Resizing aspect ratio (y_shape / x_shape). None keeps the aspect ratio of the array
- zerobool
Whether to shift the array minimum to zero.
- factorint
Initial base size factor used for filtering.
- Returns
- croptuple(tuple(int))
Crop coordinates with format ((ind_min_x, ind_min_y), (ind_max_x, ind_max_y)).
- libics.tools.trafo.resize.resize_on_mass(np_array, center='auto', total_mass=0.9, aspect_ratio='auto', aspect_mode='enlarge')
Finds the crop coordinates of a given numpy array for which each axis’ sum exceeds the given relative total_mass parameter.
- Parameters
- np_arraynumpy.ndarray
Numpy array to be resized.
- centertuple(int) or “auto”
Center coordinates of image. If “auto”, the centroid is used.
- total_massfloat
Relative mass to be present in the cropped array.
- aspect_ratiotuple(float) or “auto”
Aspect ratio (e.g. 16:9) of cropped image (aspect ratio is not guaranteed). If “auto”, no aspect ratio is set.
- aspect_mode“enlarge” or “reduce”
If “enlarge”, the aspect ratio resizing enlarges the total mass crop. If “reduce”, it reduces the total mass crop.
- Returns
- croptuple(tuple(int))
Crop coordinates with format ((ind_min_x, ind_min_y), (ind_max_x, ind_max_y)).