Welcome to pyIDI’s documentation!¶
Basic usage¶
Currently the pyIDI method works with Photron .cih
and .cihx
files, however, numpy.ndarray
can
also be passed as cih_file
argument. If an array is passed, it must have a shape of: (n time points, image height, image width)
.
Setting the points¶
Displacements are computed for certain points or certain regions of interest that are represented by a point.
Points must be of shape n_ponits x 2
:
points = [[1, 2],
[1, 5],
[2, 10]]
where the first column indicates indices along axis 0, and the second column indices along axis 1.
The points must be passed to pyIDI
object:
video.set_points(points=points)
If points are not known, a helper tool can be used to select them. This can be done by first setting a method for displacement identification:
video.set_method(method='lk') # The Lucas-Kanade algorithm for translations
Now the set_points()
can be called and a selection tool is triggered.
Another option is using tools
module in pyIDI
module:
points_obj = pyidi.tools.ManualROI(video, roi_size=(11, 11))
or another tool:
points_obj = pyidi.tools.RegularROIGrid(video, roi_size=(11, 11), noverlap=0)
Points can then be accessed:
points = points_obj.points
Setting the method¶
If the method was not yet set during points selection process, the method must be selected:
video.set_method(method='sof') # Simplified optical flow method
The method arguments can be configured:
video.method.configure(*args, **kwargs)
Get displacement¶
Finally, displacements can be identified:
displacements = video.get_displacements()
Multiprocessing¶
In the case of lk
method (Lucas-Kanade translation), the parallel computation of displacements is faster. To access the multiprocessing option, simply input
the number of processes you wish to run. The points will be automatically equally split:
displacements = video.get_displacements(processes=4)
Note that the video
object must already have set method and attributes.
Documenting the code¶
Requirements¶
Sphinx (installed by default with anaconda)
pip install sphinx
Addind a new module documentaiton to the build¶
It is most likely not practical to iclude all of our apps Python modules in the build. Only the modules and classes with the most extensive documentation (docstrings), and the ones where most developer updates are expected should be included.
To add another module’s documentation to the build, add a new entry to the doc/code/modules.rst
file, with the correct relative Python path to the module. For example, the views.py
documentation is included by:
Tools
-----
.. automodule:: pyidi.tools
:members:
For more information, see the autodoc documentation.
Docstring style: reStructuredText¶
- default docstring style in PyCharm
"autoDocstring.docstringFormat": "sphinx"
in VSCode Python Docstring extenion
def function1(self, arg1, arg2, arg3):
"""returns (arg1 / arg2) + arg3
This is a longer explanation, which may include math with latex syntax
:math:`\\alpha`.
Then, you need to provide optional subsection in this order (just to be
consistent and have a uniform documentation. Nothing prevent you to
switch the order):
- parameters using ``:param <name>: <description>``
- type of the parameters ``:type <name>: <description>``
- returns using ``:returns: <description>``
- examples (doctest)
- seealso using ``.. seealso:: text``
- notes using ``.. note:: text``
- warning using ``.. warning:: text``
- todo ``.. todo:: text``
**Advantages**:
- Uses sphinx markups, which will certainly be improved in future
version
- Nice HTML output with the See Also, Note, Warnings directives
**Drawbacks**:
- Just looking at the docstring, the parameter, type and return
sections do not appear nicely
:param arg1: the first value
:param arg2: the first value
:param arg3: the first value
:type arg1: int, float,...
:type arg2: int, float,...
:type arg3: int, float,...
:returns: arg1/arg2 +arg3
:rtype: int, float
:Example:
>>> import template
>>> a = template.MainClass1()
>>> a.function1(1,1,1)
2
.. note:: can be useful to emphasize
important feature
.. seealso:: :class:`MainClass2`
.. warning:: arg2 must be non-zero.
.. todo:: check that arg2 is non zero.
"""
return arg1/arg2 + arg3
pyIDI source code¶
pyIDI base class¶
-
class
pyidi.pyidi.
pyIDI
(cih_file)[source]¶ The pyIDI base class represents the video to be analysed.
-
get_displacements
(**kwargs)[source]¶ Calculate the displacements based on chosen method.
Method docstring: — Method is not set. Please use the set_method method. —
-
save
(filename, root='')[source]¶ Save computed displacements and other basic information.
Parameters: - filename – Name of the file to save in.
- root – Root of the filename, defaults to ‘’
-
set_method
(method, **kwargs)[source]¶ Set displacement identification method on video. To configure the method, use method.configure()
Available methods: — [Available method names and descriptions go here.] —
Parameters: method (IDIMethod or str) – the method to be used for displacement identification.
-
set_points
(points=None, method=None, **kwargs)[source]¶ Set points that will be used to calculate displacements. If points is None and a method has aready been set on this pyIDI instance, the method object’s get_point is used to get method-appropriate points.
-
Displacement identification methods¶
IDIMetod base class¶
Simplified optical flow¶
-
class
pyidi.methods._simplified_optical_flow.
PickPoints
(video, subset, axis, min_grad)[source]¶ Pick the area of interest.
Select the points with highest gradient in vertical direction.
-
inside_polygon
(x, y, points)[source]¶ Return True if a coordinate (x, y) is inside a polygon defined by a list of verticies [(x1, y1), (x2, x2), … , (xN, yN)].
Reference: http://www.ariel.com.au/a/python-point-int-poly.html
-
-
class
pyidi.methods._simplified_optical_flow.
SimplifiedOpticalFlow
(video, *args, **kwargs)[source]¶ Displacmenet computation based on Simplified Optical Flow method [1].
- Literature:
- [1] Javh, J., Slavič, J., & Boltežar, M. (2017). The subpixel resolution
- of optical-flow-based modal analysis. Mechanical Systems and Signal Processing, 88, 89–99.
- [2] Lucas, B. D., & Kanade, T. (1981). An Iterative Image Registration
- Technique with an Application to Stereo Vision. In Proceedings of the 7th International Joint Conference on Artificial Intelligence - Volume 2 (pp. 674–679). San Francisco, CA, USA: Morgan Kaufmann Publishers Inc.
-
calculate_displacements
(video)[source]¶ Calculate the displacements of set points here. The result should be saved into the self.displacements attribute.
-
configure
(subset_size=3, pixel_shift=False, convert_from_px=1.0, mraw_range='all', mean_n_neighbours=0, zero_shift=False, progress_bar=True, reference_range=(0, 100))[source]¶ Set the attributes, compute reference image and gradients.
Parameters: - video (object) – ‘parent’ object
- subset_size – size of the averaging subset, defaults to 3
- subset_size – int, optional
- pixel_shift – use pixel shift or not?, defaults to False
- pixel_shift – bool, optional
- convert_from_px – distance unit per pixel, defaults to 1.
- convert_from_px – float or int, optional
- mraw_range – what range of images to calculate into displacements, defaults to ‘all’
- mraw_range – str or tuple, optional
- mean_n_neighbours – average the displacements of neighbouring points (how many points), defaults to 0
- mean_n_neighbours – int, optional
- zero_shift – shift the mean of the signal to zero?, defaults to False
- zero_shift – bool, optional
- progress_bar – show progress bar while calculating the displacements, defaults to True
- progress_bar – bool, optional
- reference_range – what range of images is averaged into reference image, defaults to (0, 100)
- reference_range – tuple, optional
-
reference
(images, subset_size)[source]¶ Calculation of the reference image, image gradients and gradient amplitudes.
Parameters: - images – Images to average. Usually the first 100 images.
- subset_size – Size of the subset to average.
Returns: Reference image, image gradient in 0 direction, image gradient in 1 direction, gradient magnitude
The Lucas-Kanade algorithm for translations¶
-
class
pyidi.methods._lucas_kanade.
LucasKanade
(video, *args, **kwargs)[source]¶ Translation identification based on the Lucas-Kanade method using least-squares iterative optimization with the Zero Normalized Cross Correlation optimization criterium.
-
calculate_displacements
(video, **kwargs)[source]¶ Calculate displacements for set points and roi size.
kwargs are passed to configure method. Pre-set arguments (using configure) are NOT changed!
-
configure
(roi_size=(9, 9), pad=2, max_nfev=20, tol=1e-08, int_order=3, verbose=1, show_pbar=True, processes=1, pbar_type='atpbar', multi_type='mantichora', resume_analysis=True, process_number=0, reference_image=0)[source]¶ Displacement identification based on Lucas-Kanade method, using iterative least squares optimization of translatory transformation parameters to determine image ROI translations.
Parameters: - video (object) – parent object
- roi_size (tuple, list, optional) – (h, w) height and width of the region of interest. ROI dimensions should be odd numbers. Defaults to (9, 9)
- pad (int, optional) – size of padding around the region of interest in px, defaults to 2
- max_nfev (int, optional) – maximum number of iterations in least-squares optimization, defaults to 20
- tol (float, optional) – tolerance for termination of the iterative optimization loop. The minimum value of the optimization parameter vector norm.
- int_order (int, optional) – interpolation spline order
- verbose (int, optional) – show text while running, defaults to 1
- show_pbar (bool, optional) – show progress bar, defaults to True
- processes (int, optional, defaults to 1.) – number of processes to run
- pbar_type (str, optional) – type of the progress bar (‘tqdm’ or ‘atpbar’), defaults to ‘atpbar’
- multi_type (str, optional) – type of multiprocessing used (‘multiprocessing’ or ‘mantichora’), defaults to ‘mantichora’
- resume_analysis – if True, the last analysis results are loaded and computation continues from last computed time point.
- process_number (int, optional) – User should not change this (for multiprocessing purposes - to indicate the process number)
- reference_image (int or tuple or ndarray) – The reference image for computation. Can be index of a frame, tuple (slice) or numpy.ndarray that is taken as a reference.
-
create_temp_files
(init_multi=False)[source]¶ Temporary files to track the solving process.
This is done in case some error occures. In this eventuality the calculation can be resumed from the last computed time point.
Parameters: init_multi (bool, optional) – when initialization multiprocessing, defaults to False
-
optimize_translations
(G, F_spline, maxiter, tol, d_subpixel_init=(0, 0))[source]¶ Determine the optimal translation parameters to align the current image subset G with the interpolated reference image subset F.
Parameters: - G (array of shape roi_size) – the current image subset.
- F_spline (scipy.interpolate.RectBivariateSpline) – interpolated referencee image subset
- maxiter (int) – maximum number of iterations
- tol (float) – convergence criterium
- d_subpixel_init – initial subpixel displacement guess, relative to the integrer position of the image subset G
Returns: the obtimal subpixel translation parameters of the current image, relative to the position of input subset G.
Return type: array of size 2
-
resume_temp_files
()[source]¶ Reload the settings written in the temporary files.
When resuming the computation of displacement, the settings are loaded from the previously created temporary files.
-
roi_size
¶ roi_size attribute getter
-
show_points
(video, figsize=(15, 5), cmap='gray', color='r')[source]¶ Shoe points to be analyzed, together with ROI borders.
Parameters: - figsize – matplotlib figure size, defaults to (15, 5)
- cmap – matplotlib colormap, defaults to ‘gray’
- color – marker and border color, defaults to ‘r’
-
temp_files_check
()[source]¶ Checking the settings of computation.
The computation can only be resumed if all the settings and data are the same as with the original analysis. This function checks that (writing all the setting to dict and comparing the json dump of the dicts).
If the settings are the same but the points are not, a new analysis is also started. To set the same points, check the temp_pyidi folder.
Returns: Whether to resume analysis or not Return type: bool
-
Tools¶
-
class
pyidi.tools.
GridOfROI
(video=None, roi_size=(7, 7), noverlap=0, verbose=0)[source]¶ Automatic simple ROI grid generation.
Different from RegularROIGrid in that it gets a regular grid and only then checks if all points are inside polygon. This yields a more regular and full grid. Does not contain sssig filter.
-
class
pyidi.tools.
ManualROI
(video, roi_size, single=False, verbose=0)[source]¶ Manual ROI selection.
-
pyidi.tools.
get_gradient
(image)[source]¶ Fast gradient computation.
Compute the gradient of image in both directions using central difference weights over 3 points.
!!! WARNING: The edges are excluded from the analysis and the returned image is smaller then original.
Parameters: image – 2d numpy array Returns: gradient in x and y direction
-
pyidi.tools.
inside_polygon
(x, y, points)[source]¶ Return True if a coordinate (x, y) is inside a polygon defined by a list of verticies [(x1, y1), (x2, x2), … , (xN, yN)].
Reference: http://www.ariel.com.au/a/python-point-int-poly.html
-
pyidi.tools.
split_points
(points, processes)[source]¶ Split the array of points to different processes.
Parameters: - points (numpy array) – Array of points (2d)
- processes (int) – number of processes
-
pyidi.tools.
update_docstring
(target_method, doc_method=None, delimiter='---', added_doc='')[source]¶ Update the docstring in target_method with the docstring from doc_method.
Parameters: - target_method (method) – The method that waits for the docstring
- doc_method (method) – The method that holds the desired docstring
- delimiter (str, optional) – insert the desired docstring between two delimiters, defaults to ‘—’