pyCRT package

pyCRT.arrayOperations module

Simple functions for manipulating arrays (pyCRT.arrayOperations)

This module is mostly functions that receive two arrays as input and returns two arrays, intended to be used with the timeScds and avgInten arrays.

pyCRT.arrayOperations.findValueIndex(arr: ndarray[Any, dtype[float64]], value: Any) int

Returns the index of the first element in arr which is greater than valuea.

pyCRT.arrayOperations.minMaxNormalize(array: ndarray[Any, dtype[float64]]) ndarray

Performs min-max normalization on array.

pyCRT.arrayOperations.sliceByTime(timeArr: ndarray[Any, dtype[float64]], fromTime: float | int | float64 | int64 | None = None, toTime: float | int | float64 | int64 | None = None) slice

Creates a slice object specifying timeArr’s section which is between fromTime and toTime.

Parameters:
  • timeArr (np.ndarray) – The array whose slice is to be calculated

  • fromTime (real number or None, default=None) – The slice’s “start” argument will be the index of the first element of timeArr whose value is greater or equal to fromTime. If None, -np.inf will be used.

  • toTime (real number or None, default=None) – The slice’s “stop” argument will be the index of the first element of timeArr whose value is less or equal to fromTime. If None, np.inf will be used.

Return type:

A slice object specifying the slice between fromTime to toTime in arr.

pyCRT.arrayOperations.sliceFromLocalMax(timeArr: ndarray[Any, dtype[float64]], intenArr: ndarray[Any, dtype[float64]], fromTime: float | int | float64 | int64 | None = None, toTime: float | int | float64 | int64 | None = None) slice

Applies sliceByTime and sliceFromMaxToEnd (in this order) to the input arrays with fromTime and toTime as arguments, such that the resulting slice starts at intenArr’s maximum value and ends at toTime.

pyCRT.arrayOperations.sliceFromMaxToEnd(intenArr: ndarray[Any, dtype[float64]]) slice

Returns a slice object that slices the input array from the index of its absolute maximum to its end. It’s literally just slice(intenArr.argmax(), -1)

pyCRT.arrayOperations.stripArr(timeArr: ndarray[Any, dtype[float64]], arr: ndarray[Any, dtype[float64]]) tuple[numpy.ndarray[Any, numpy.dtype[numpy.float64]], numpy.ndarray[Any, numpy.dtype[numpy.float64]]]

Ridiculous workaround for mp4 files. Simply removes the trailing zeros from timeArr and the corresponding arr elements.

pyCRT.arrayOperations.subtractMinimum(arr: ndarray[Any, dtype[float64]]) ndarray[Any, dtype[float64]]

Subtracts the array’s elements by the array’s minimum value. What else did you expect?

pyCRT.arrayPlotting module

Functions related to curve fitting (pyCRT.curveFitting)

This module implements the operations necessary to calculate the pCRT from the average intensities array and the frame times array, namely fitting a polynomial and two exponential curves on the data.

pyCRT.arrayPlotting.addTextToLabel(ax: Axes, text: str, **kwargs: Any) None

Adds some text to the axes’ legend and redraws the legend.

pyCRT.arrayPlotting.figVisualizationFunctions(func: Callable[[...], tuple[matplotlib.figure.Figure, matplotlib.axes._axes.Axes]]) tuple[Callable[..., NoneType], Callable[..., NoneType]]

Creates two functions for easily showing, saving the plot created by the ‘func’ function, and closing the plot afterwards.

Parameters:

func (Callable) – The function that actually makes the plot the data. Can be any function that takes in any number of arguments and returns a tuple with mpl.Figure and mpl.Axes

Returns:

  • showPlot(args, kwargs) (function) – Shows the plot created by func(args, kwargs) and formatted by makeFigAxes.

  • saveFig(figPath (str, args, kwargs) : function) – Saves the plot created by func(args, kwargs) and formatted by makeFigAxes on the specified path.

Notes

This module defines four functions created through figVisualizationFactory: showAvgIntensPlot and saveAvgIntensPlot are wrappers for makeAvgIntensPlot, and showPCRTPlot and savePCRTPlot are wrappers for makePCRTPlot. .

pyCRT.arrayPlotting.makeAvgIntensPlot(timeScdsArr: ndarray[Any, dtype[float64]], channelsAvgIntensArr: ndarray[Any, dtype[float64]]) tuple[matplotlib.figure.Figure, matplotlib.axes._axes.Axes]

Creates and formats a plot for the average intensities of all channels over all the capture’s duration, and returns the Figure and Axes tuple. Not much to see here, check out makeFigAxes and plotAvgIntens for more information.

pyCRT.arrayPlotting.makeFigAxes(axisLabels: tuple[str, str], figTitle: str | None = None, figSizePx: tuple[int, int] = (960, 600), dpi: float | int | float64 | int64 = 100) tuple[matplotlib.figure.Figure, matplotlib.axes._axes.Axes]

Creates and formats the figure and axes. To be used with plotFunction, plotPCRT and plotAvgIntens.

Parameters:
  • axisLabels (tuple of str) – The labels for the X and Y axis respectively.

  • figTitle (str or None, default=None) – Self explanatory. If None, the figure will just have no title.

  • figSizePx (tuple of int, default=(960, 600)) – Figure dimensions in pixels. More adequate for primarily digital figures than matplotlib’s default of specifying everything in inches.

  • dpi (real number, default=100) – The figure’s resolution in pixels per inch.

Returns:

  • fig (plt.Figure)

  • ax (plt.Axes)

pyCRT.arrayPlotting.makePCRTPlot(timeScdsArr: ndarray[Any, dtype[float64]], avgIntensArr: ndarray[Any, dtype[float64]], funcParamsTuples: dict[str, tuple[Union[Sequence[float], numpy.ndarray[Any, numpy.dtype[numpy.float64]]], Union[Sequence[float], numpy.ndarray[Any, numpy.dtype[numpy.float64]]]]], criticalTime: float | None = None, channel: str | None = None, funcOptions: dict[str, Any] | None = None) tuple[matplotlib.figure.Figure, matplotlib.axes._axes.Axes]

Creates and formats the plot for the exponential, polynomial and pCRT exponential functions applied over the array of a channel’s intensities since the release of the compression on the skin.

Parameters:
  • timeScdsArr (np.ndarray) – The array of time instants since the release of the compression from the skin.

  • avgIntenArr (np.ndarray) – The array of average intensities for the channel used for fitting the functions.

  • funcParamsTuples (dict with str keys tuple of 2 sequences of float as values) – The dictionary containing the polynomial, exponential and pCRT exponential functions’ optimized parameters and their respective standard deviations. The keys should be ‘exponential’, ‘polynomial’ and ‘pCRT’ respectively, and the values the tuples returned by scipy.optimize.curve_fit. See curveFitting.fitExponential or curveFitting.fitPolynomial for more information. If either the ‘polynomial’ or ‘exponential’ keys are lacking, these functions just won’t be plotted, but the ‘pCRT’ key is requred.

  • criticalTime (float or None, default=None) – The critical time. A vertical dashed line will be drawn to mark this instant. If None, no such line will be drawm.

  • channel (str or None, default=None) – Which channel to use. This will only be used for the line’s color and legend, as avgIntenArr is already expected to be of s single channel. If None, the legend will be unspecific and the line will be gray.

  • funcOptions (dict with str keys and any value or None, default=None) – Additional options that will be passed to the plotting functions (plotFunction and plotAvgIntens). The same key naming scheme as with the funcParamsTuples parameter is used, but with the addition of the optional ‘intensities’ key.

Returns:

  • fig (matplotlib Figure) – The figure. It is 960x600 pixels by default.

  • ax (matplotlib Axes) – The Axes, in which everything is plotted.

pyCRT.arrayPlotting.plotAvgIntens(figAxTuple: tuple[matplotlib.figure.Figure, matplotlib.axes._axes.Axes], timeScdsArr: ndarray[Any, dtype[float64]], channelsAvgIntensArr: ndarray[Any, dtype[float64]], channels: str | None = None, **kwargs: Any) None

Plots the average intensities array on the given mpl.Figure and mpl.Axes tuple. This can plot a set of channels or all three, depending on channelsAvgIntensArr’s dimentions and the channels argument.

Parameters:
  • figAxTuple (tuple of mpl.Figure and mpl.Axes respectively) – The figure and axes on which to plot. In practice this function only utilizes the Axes instance, not the Figure.

  • timeScdsArr (np.ndarray) – The arrays of seconds and average intensities corresponding to each frame, respectively. This is typically the output of videoReading.readVideo.

  • channelsAvgIntensArr (np.ndarray) – The arrays of seconds and average intensities corresponding to each frame, respectively. This is typically the output of videoReading.readVideo.

  • channels (str or None, default=None) – Which channels to plot, and also used to set the color of each line in the plot and its label. Should be a string with some combination of “r”, “g” and “b”. If it is None and channelsAvgIntensArr is one-dimensional, then it’ll plot that channel in gray, and if channelsAvgIntensArr is not one-dimensional, then channels will be set as “bgr”.

  • **kwargs (dict of Any) – The keyword arguments that may be passed to mpl.Axes.plot.

pyCRT.arrayPlotting.plotFunction(figAxTuple: tuple[matplotlib.figure.Figure, matplotlib.axes._axes.Axes], timeScdsArr: ndarray[Any, dtype[float64]], func: Callable[[...], ndarray[Any, dtype[float64]]], funcParams: Sequence[float] | ndarray[Any, dtype[float64]], **kwargs: Any) None

Applies the given function with the given parameters over timeScdsArr and plots the resulting array as the Y axis.

Parameters:
  • figAxTuple (tuple of mpl.Figure and mpl.Axes respectively) – The figure and axes on which to plot. In practice this function only utilizes the Axes instance, not the Figure.

  • timeScdsArr (np.ndarray) – The array of seconds corresponding to each frame. This is typically the first output of videoReading.readVideo

  • func (callable that returns a np.ndarray) – The function that will be applied to timeScdsArr with funcParams as its parameters. This is typically the polynomial or exponential functions from curveFitting.

  • funcParams (sequence of float) – This sequence will be unpacked and used as func’s positional arguments. Again, see curveFitting.exponential or curveFitting.polynomial for an example.

  • **kwargs (dict of Any) – The keyword arguments that may be passed to mpl.Axes.plot.

pyCRT.arrayPlotting.plotPCRT(figAxTuple: tuple[matplotlib.figure.Figure, matplotlib.axes._axes.Axes], timeScdsArr: ndarray[Any, dtype[float64]], pCRTParams: Sequence[float] | ndarray[Any, dtype[float64]], criticalTime: float | None = None, **kwargs: Any) None

Basically a special case of curveFitting.plotFunction that specifically plots an exponential function with the given parameters, and a vertical line on timeScdsArr[maxDiv] (the critical time ‘tc’), and sets the line’s legend to be about pCRT. See the documentation the aforementioned function for more information.

pyCRT.arrayPlotting.saveAvgIntensPlot(figPath: str, *args, **kwargs) None
pyCRT.arrayPlotting.savePCRTPlot(figPath: str, *args, **kwargs) None
pyCRT.arrayPlotting.showAvgIntensPlot(*args, **kwargs) None
pyCRT.arrayPlotting.showPCRTPlot(*args, **kwargs) None

pyCRT.curveFitting module

Functions related to curve fitting (pyCRT.curveFitting)

This module implements the operations necessary to calculate the pCRT from the average intensities array and the frame times array, namely fitting a polynomial and two exponential curves on the data.

pyCRT.curveFitting.calcPCRT(timeScdsArr: ndarray[Any, dtype[float64]], avgIntensArr: ndarray[Any, dtype[float64]], criticalTime: float | Iterable[float] | None = None, expTuple: tuple[Union[Sequence[float], numpy.ndarray[Any, numpy.dtype[numpy.float64]]], Union[Sequence[float], numpy.ndarray[Any, numpy.dtype[numpy.float64]]]] | None = None, polyTuple: tuple[Union[Sequence[float], numpy.ndarray[Any, numpy.dtype[numpy.float64]]], Union[Sequence[float], numpy.ndarray[Any, numpy.dtype[numpy.float64]]]] | None = None, pCRTInitialGuesses: Sequence[float] | ndarray[Any, dtype[float64]] | None = None, exclusionMethod: str = 'best fit', exclusionCriteria: float = inf) Tuple[tuple[numpy.ndarray[Any, numpy.dtype[numpy.float64]], numpy.ndarray[Any, numpy.dtype[numpy.float64]]], float]

Fits the pCRT exponential on the f(timeScds)=avgIntens data given by timeScdsArr and avgIntensArr respectively on each value of criticalTime, returning the fitted pCRT parameters and their standard deviations chosen according to the exlucion method and criteria (see Parameters below).

Parameters:
  • timeScdsArr (np.ndarray of float) – An array of time instants in seconds. Typically corresponding to the timestamp of each frame in a video recording.

  • avgIntensArr (np.ndarray of float) – The array of average intensities for a given channel inside the region of interest (ROI), with respect to timeScdsArr.

  • criticalTime (float, iterable of float, or None, default=None) – The critical time, up until which the pCRT function will be optimized on the timeScdsArr and avgIntensArr. If a list of float, this function will try fitting the pCRT exponential function on each criticalTime and return the optimized parameters chosen according to exclusionMethod and exclusionCriteria. If None, curveFitting.findMaxDivergencePeaks will be called on timeScdsArr and avgIntensArr to find a list of candidate criticalTimes.

  • expTuple (tuple of np.ndarray of float, default=None) – Tuples with the exponential and polynomial function parameters and standard deviations fitted over f(timeScds)=avgIntens. These arguments will be used to find the list of candidate critical times if expTuple and polyTuple are not None, and criticalTime is None.

  • polyTuple (tuple of np.ndarray of float, default=None) – Tuples with the exponential and polynomial function parameters and standard deviations fitted over f(timeScds)=avgIntens. These arguments will be used to find the list of candidate critical times if expTuple and polyTuple are not None, and criticalTime is None.

  • pCRTInitialGuesses (sequence of float or None, default=None) – The initial guesses for the rRCT exponential fitting. If None, p0=[1.0, -0.3, 0.0] will be used by default (see curveFitting.fitPCRT and curveFitting.fitExponential).

  • exclusionMethod (str, default='best fit') – Which criticalTime and its associated fitted pCRT parameters and standard deviations are to be returned. Possible values are ‘best fit’, ‘strict’ and ‘first that works’ (consult the documentation for the calcPCRTBestFit, calcPCRTStrict and calcPCRTFirstThatWorks functions for a description of the effect of these possible values). Of course, this parameter has no effect if a single criticalTime is provided (instead of a list of candidate criticalTimes or none at all)

  • exclusionCriteria (float, default=np.inf) – The maximum relative uncertainty a pCRT measurement can have and not be rejected. If all fits on the criticalTime candidates fail this criteria, a RuntimeError will be raised.

Returns:

  • pCRTTuple (tuple of np.ndarray of float) – The optimized parameters and their standard deviations, respectively, chosen according to the exclusionMethod and exclusionCriteria.

  • criticalTime (float) – The critical time, chosen according to the exclusionMethod and exclusionCriteria.

Raises:
  • ValueError – If an invalid value for exclusionMethod was passed.

  • RuntimeError – If either the fit failed on all criticalTime candidates or no fit passed the exclusionCriteria.

pyCRT.curveFitting.calcPCRTBestFit(timeScdsArr: ndarray[Any, dtype[float64]], avgIntensArr: ndarray[Any, dtype[float64]], criticalTimeList: Iterable[float], pCRTInitialGuesses: Sequence[float] | ndarray[Any, dtype[float64]] | None = None, exclusionCriteria: float = inf) Tuple[tuple[numpy.ndarray[Any, numpy.dtype[numpy.float64]], numpy.ndarray[Any, numpy.dtype[numpy.float64]]], float]

Fits the pCRT exponential on the f(timeScds)=avgIntens data given by timeScdsArr and avgIntensArr respectively using the candidate critical times given by criticalTimeList, returning the fitted parameters, their standard deviations and the criticalTime that gave the lowest relative uncertainty for the 1/pCRT parameter.

Parameters:
  • timeScdsArr (np.ndarray of float) – An array of time instants in seconds. Typically corresponding to the timestamp of each frame in a video recording.

  • avgIntensArr (np.ndarray of float) – The array of average intensities for a given channel inside the region of interest (ROI), with respect to timeScdsArr.

  • criticalTimeList (iterable of float) – An iterable of candidate critical times. curveFitting.fitPCRT will be called with each criticalTime.

  • pCRTInitialGuesses (sequence of float or None, default=None) – The initial guesses for the rRCT exponential fitting. If None, p0=[1.0, -0.3, 0.0] will be used by default (see curveFitting.fitPCRT and curveFitting.fitExponential).

  • exclusionCriteria (float, default=np.inf) – The maximum relative uncertainty a pCRT measurement can have and not be rejected. If all fits on the criticalTime candidates fail this criteria, a RuntimeError will be raised.

Returns:

  • pCRTTuple (tuple of np.ndarray of float) – The optimized parameters and their standard deviations, respectively, that gave the least standard deviation for the 1/pCRT parameter of the pCRT exponential function.

  • criticalTime (float) – The critical time associated with the aforementioned parameters.

Raises:

RuntimeError – If either the fit failed on all criticalTime candidates or no fit passed the exclusionCriteria.

pyCRT.curveFitting.calcPCRTFirstThatWorks(timeScdsArr: ndarray[Any, dtype[float64]], avgIntensArr: ndarray[Any, dtype[float64]], criticalTimeList: Iterable[float], pCRTInitialGuesses: Sequence[float] | ndarray[Any, dtype[float64]] | None = None, exclusionCriteria: float = inf) Tuple[tuple[numpy.ndarray[Any, numpy.dtype[numpy.float64]], numpy.ndarray[Any, numpy.dtype[numpy.float64]]], float]

Fits the pCRT exponential on the f(timeScds)=avgIntens data given by timeScdsArr and avgIntensArr respectively using the candidate critical times given by criticalTimeList, returning the fitted parameters, their standard deviations and the criticalTime corresponding to the first critical time candidate that passed the exclusion criteria.

Parameters:
  • timeScdsArr (np.ndarray of float) – An array of time instants in seconds. Typically corresponding to the timestamp of each frame in a video recording.

  • avgIntensArr (np.ndarray of float) – The array of average intensities for a given channel inside the region of interest (ROI), with respect to timeScdsArr.

  • criticalTimeList (iterable of float) – An iterable of candidate critical times. curveFitting.fitPCRT will be called with each criticalTime.

  • pCRTInitialGuesses (sequence of float or None, default=None) – The initial guesses for the rRCT exponential fitting. If None, p0=[1.0, -0.3, 0.0] will be used by default (see curveFitting.fitPCRT and curveFitting.fitExponential).

  • exclusionCriteria (float, default=np.inf) – The maximum relative uncertainty a pCRT measurement can have and not be rejected. If all fits on the criticalTime candidates fail this criteria, a RuntimeError will be raised.

Returns:

  • pCRTTuple (tuple of np.ndarray of float) – The first optimized parameters and their respective standard deviations that passed the exclusion criteria.

  • criticalTime (float) – The critical time associated with the aforementioned parameters.

Raises:

RuntimeError – If either the fit failed on all criticalTime candidates or no fit passed the exclusionCriteria.

pyCRT.curveFitting.calcPCRTStrict(timeScdsArr: ndarray[Any, dtype[float64]], avgIntensArr: ndarray[Any, dtype[float64]], criticalTime: float, pCRTInitialGuesses: Sequence[float] | ndarray[Any, dtype[float64]] | None = None, exclusionCriteria: float = inf) Tuple[tuple[numpy.ndarray[Any, numpy.dtype[numpy.float64]], numpy.ndarray[Any, numpy.dtype[numpy.float64]]], float]

Fits the pCRT exponential on the f(timeScds)=avgIntens data given by timeScdsArr and avgIntensArr respectively using criticalTime as the critical time, returning the fitted parameters, their standard deviations and the critical time itself.

Parameters:
  • timeScdsArr (np.ndarray of float) – An array of time instants in seconds. Typically corresponding to the timestamp of each frame in a video recording.

  • avgIntensArr (np.ndarray of float) – The array of average intensities for a given channel inside the region of interest (ROI), with respect to timeScdsArr.

  • criticalTime (float) – The critical time. The pCRT exponential will be fitted on timeScdsArr and avgIntenArr up until this value in timeScdsArr.

  • pCRTInitialGuesses (sequence of float or None, default=None) – The initial guesses for the rRCT exponential fitting. If None, p0=[1.0, -0.3, 0.0] will be used by default (see curveFitting.fitPCRT and curveFitting.fitExponential).

  • exclusionCriteria (float, default=np.inf) – The maximum relative uncertainty a pCRT measurement can have and not be rejected. If all fits on the criticalTime candidates fail this criteria, a RuntimeError will be raised.

Returns:

  • pCRTTuple (tuple of np.ndarray of float) – The optimized parameters and their standard deviations

  • criticalTime (float) – The critical time associated with the aforementioned parameters.

Raises:

RuntimeError – If either the fit failed or it didn’t pass the exclusion criteria.

pyCRT.curveFitting.calculateRelativeUncertainty(pCRTTuple: tuple[Union[Sequence[float], numpy.ndarray[Any, numpy.dtype[numpy.float64]]], Union[Sequence[float], numpy.ndarray[Any, numpy.dtype[numpy.float64]]]]) float64

Calculates the pCRT’s relative uncertainty (with a 95% confidence interval) given a tuple with the optimized pCRT exponential parameters and their respective standard deviations.

pyCRT.curveFitting.covToStdDev(cov: ndarray[Any, dtype[float64]]) ndarray[Any, dtype[float64]]

Converts the covariance matrix returned by SciPy parameter optimization functions into an array with the standard deviation of each parameter. Refer to the documentation of scipy.optimize.curve_fit for more information

pyCRT.curveFitting.diffExpPoly(x: ndarray[Any, dtype[float64]], expParams: ndarray[Any, dtype[float64]], polyParams: ndarray[Any, dtype[float64]]) ndarray[Any, dtype[float64]]

Evaluates the function abs(exponential(expParams) - polynomial(polyParams)) over x

pyCRT.curveFitting.exponential(x: ndarray[Any, dtype[float64]], a: float | int | float64 | int64, b: float | int | float64 | int64, c: float | int | float64 | int64) ndarray[Any, dtype[float64]]

Exponential function of the form a*exp(b*x)+c. Refer to np.exp from the Numpy documentation for more information.

pyCRT.curveFitting.findMaxDivergencePeaks(x: ndarray[Any, dtype[float64]], y: ndarray[Any, dtype[float64]]) list[int]
pyCRT.curveFitting.findMaxDivergencePeaks(x: ndarray[Any, dtype[float64]], expTuple: tuple[Union[Sequence[float], numpy.ndarray[Any, numpy.dtype[numpy.float64]]], Union[Sequence[float], numpy.ndarray[Any, numpy.dtype[numpy.float64]]]], polyTuple: tuple[Union[Sequence[float], numpy.ndarray[Any, numpy.dtype[numpy.float64]]], Union[Sequence[float], numpy.ndarray[Any, numpy.dtype[numpy.float64]]]]) list[int]

Find the indices of the peaks of maxDiv(expParams, polyParams) and returns them in descending order of diffExpPoly[i]. Usage:

findMaxDivergencePeaks(x, expParams=expParams, polyParams=polyParams)

to directly compute the peaks, or

findMaxDivergencePeaks(x, y)

to fit the polynomial and exponential functions on the data, and then compute the peaks.

Parameters:
  • x (np.ndarray) – Tipically the array of frame timestamps.

  • *args (np.ndarray) – Another array, y, that tipically is the array of average intensities for a channel.

  • **kwargs (tuple of 2 arrays) – The parameters and standard deviations to the exponential and polynomial functions, if they have already been calculated.

Returns:

List of indexes of x where the peaks of maximum absolute divergence between the polynomial and exponential functions have been found, sorted by the peak magnitude.

Return type:

maxIndexesSorted

pyCRT.curveFitting.fitExponential(x: ndarray[Any, dtype[float64]], y: ndarray[Any, dtype[float64]], p0: Sequence[float] | ndarray[Any, dtype[float64]] | None = None) tuple[numpy.ndarray[Any, numpy.dtype[numpy.float64]], numpy.ndarray[Any, numpy.dtype[numpy.float64]]]

Fits an exponential function of the form a*exp(b*x)+c on the data, and returns a tuple of two arrays, one with the optimized parameters and another with their standard deviations. Refer to the documentation of scipy.optimize.curve_fit for more information.

Parameters:
  • x (np.ndarray) – Self-explanatory.

  • y (np.ndarray) – Self-explanatory.

  • p0 (sequence of 3 real numbers or None, default=None) – The initial guesses for each parameter, in order of a, b and c (see summary above). If None, will use p0=[1.0, -0.3, 0].

Returns:

  • expParams – The optimized parameters

  • expStdDev – The optimized parameters’ respective standard deviations

Raises:

RuntimeError – If the curve fit failed.

pyCRT.curveFitting.fitPCRT(x: ndarray[Any, dtype[float64]], y: ndarray[Any, dtype[float64]], p0: Sequence[float] | ndarray[Any, dtype[float64]] | None = None, maxDiv: Iterable[int] | int | None = None) tuple[tuple[numpy.ndarray[Any, numpy.dtype[numpy.float64]], numpy.ndarray[Any, numpy.dtype[numpy.float64]]], int]

Slices the x and y arrays from start to maxDiv and fit an exponential function on the data, and returns a tuple, the first element of which is the optimized parameters and their standard deviations, and the other is the maxDiv used. If maxDiv is a list of integers, it will try to fit on each value and return on the first successful fit.

Parameters:
  • x (np.ndarray) – Self-explanatory. The arrays over which the curve fit will be tried.

  • y (np.ndarray) – Self-explanatory. The arrays over which the curve fit will be tried.

  • p0 (sequence of real numbers, default=None) – The initial guesses for each parameter of the exponential function. Refer to the documentation of pyCRT.curveFitting.exponential for more information.

  • maxDiv (iterable of ints, or int, or None, default=None) – Maximum divergence index between the exponential and polynomial functions fitted on the entire data set. Refer to pyCRT.curveFitting.findMaxDivergencePeaks for more information.

Returns:

  • (pCRTParams, pCRTStdDev) (tuple of np.ndarrays) – The optimized parameters for the exponential function and their standard deviations.

  • maxDiv (int) – The maximum divergence index used. This is useful if a list of maxDivs was or None was passed.

Raises:
  • TypeError – If maxDiv isn’t a list, an int, or None.

  • RuntimeError – If the exponential fit failed on the single maxDiv passed, or if a list was passed and it failed on all the maxDivs in the list.

pyCRT.curveFitting.fitPolynomial(x: ndarray[Any, dtype[float64]], y: ndarray[Any, dtype[float64]], p0: Sequence[float] | ndarray[Any, dtype[float64]] | None = None) tuple[numpy.ndarray[Any, numpy.dtype[numpy.float64]], numpy.ndarray[Any, numpy.dtype[numpy.float64]]]

Fits a polynomial function of the form coefs[0] + coefs[0]*x + coefs[1]*x**2 + … on the data, and returns a tuple of two arrays, one with the optimized parameters and another with their standard deviations. Refer to the documentation of scipy.optimize.curve_fit for more information.

Parameters:
  • x (np.ndarray) – Self-explanatory.

  • y (np.ndarray) – Self-explanatory.

  • p0 (sequence of real numbers or None, default=None) – The initial guesses for each parameter in increasing polynomial order (see summary above). Note that this determines the order of the polynomial, for example, a list of length 7 specifies a polynomial of sixth order.

Returns:

  • polyParams – The optimized parameters

  • polyStdDev – The optimized parameters’ respective standard deviations

Raises:

RuntimeError – If the curve fit failed.

pyCRT.curveFitting.pCRTFromParameters(pCRTTuple: tuple[Union[Sequence[float], numpy.ndarray[Any, numpy.dtype[numpy.float64]]], Union[Sequence[float], numpy.ndarray[Any, numpy.dtype[numpy.float64]]]]) tuple[float, float]

Calculate the pCRT and its uncertainty with a 95% confidence interval from the pCRT exponential’s optimized parameters.

Parameters:

pCRTTuple (tuple of sequences of float) – A tuple with the fitted parameters and their standard deviations, respectively. See fitPCRT.

Returns:

  • pCRT (float) – The calculated pCRT, which is the negative inverse of the “b” parameter of the exponential function defined in this module (see exponential).

  • pCRTUncertainty (float) – The pCRT’s uncertainty with a 95% confidence interval, calculated from the standard deviation of the “b” parameter of the exponential function.

pyCRT.curveFitting.polynomial(x: ndarray[Any, dtype[float64]], *coefs: float | int | float64 | int64) ndarray[Any, dtype[float64]]

Polynomial of the form coefs[0] + coefs[0]*x + coefs[1]*x**2 + … Refer to the Numpy documentation for more information.

pyCRT.frameOperations module

Frame manipulation functions (pyCRT.frameOperations)

A collection of small functions that that do something to frames (which are 3D numpy arrays that represent each channel of each pixel of an image), typically recieving a frame and returning another. Functionality includes cropping, calculating average intensity, drawing a ROI, etc,

pyCRT.frameOperations.calcAvgInten(frame: ndarray[Any, dtype[float64]], roi: tuple[int, int, int, int] | str | None) ndarray[Any, dtype[float64]]

Calculates the average channel intensity on the pixels inside the ROI.

Parameters:
  • frame (3D np.ndarray) – A matrix with each channel’s intensity for each pixel. The output of cv2.imread.

  • roi (tuple of 4 ints, str or None) – The ROI. It can be a tuple of 4 ints, in which case the first two are the x and y coordinates of the rectangle’s top-left corner, and the other two are the lengths of its sides. If not a tuple, the average will be computed over the entire frame.

Returns:

channelsAvgInten – The average intensity for each channel (in the order of BGR), calcualted with the pixels inside the ROI.

Return type:

3x1 np.ndarray

pyCRT.frameOperations.cropFrame(frame: ndarray[Any, dtype[float64]], roi: tuple[int, int, int, int] | str | None) ndarray[Any, dtype[float64]]

Draws a red rectangle around the ROI.

Parameters:
  • frame (3D np.ndarray) – A matrix with each channel’s intensity for each pixel. The output of cv2.imread.

  • roi (tuple of 4 ints, str or None) – The ROI. It can be a tuple of 4 ints, in which case the first two are the x and y coordinates of the rectangle’s top-left corner, and the other two are the lengths of its sides. If not a tuple, it’ll just assume the ROI hasn’t been specified yet or is supposed to be the entire frame, in which case the original frame will be returned unmodified.

Returns:

croppedFrame – The portion of the frame inside the rectangle specified by the roi parameter. This array’s dimensions will be the last two elements of the roi tuple. If roi is not a tuple, it’ll just return the entire frame.

Return type:

3D np.ndarray

pyCRT.frameOperations.drawRoi(frame: ndarray[Any, dtype[float64]], roi: tuple[int, int, int, int] | str | None) ndarray[Any, dtype[float64]]

Draws a red rectangle around the ROI.

Parameters:
  • frame (3D np.ndarray) – A matrix with each channel’s intensity for each pixel. The output of cv2.imread.

  • roi (tuple of 4 ints, str or None) – The ROI. It can be a tuple of 4 ints, in which case the first two are the x and y coordinates of the rectangle’s top-left corner, and the other two are the lengths of its sides. If not a tuple, it’ll just assume the ROI hasn’t been specified yet or is supposed to be the entire frame, in which case the original frame will be returned unmodified.

Returns:

frameWithRoi – The original frame passed to this function, either unmodified or with the sides of a red rectangle drawn on the coordinates specified by the roi tuple.

Return type:

3D np.ndarray

pyCRT.frameOperations.rescaleFrame(frame: ndarray[Any, dtype[float64]], rescaleFactor: float | int | float64 | int64) ndarray[Any, dtype[float64]]

Changes the frame’s dimensions, using bilinear interpolation.

Parameters:
  • frame (3D np.ndarray) – A matrix with each channel’s intensity for each pixel. The output of cv2.imread.

  • rescaleFactor (real number) – The factor by which the frame’s dimensions will be multiplied.

Returns:

rescaledFrame – The rescaled frame, using bilinear interpolation.

Return type:

3D np.ndarray

pyCRT.simpleUI module

A simplified object-oriented interface for pyCRT (pyCRT.simpleUI)

This module provides the PCRT class, which is meant to be the simplest way to use pyCRT’s functions distributed among it’s other modules.

class pyCRT.simpleUI.PCRT(fullTimeScdsArr: ndarray[Any, dtype[float64]], channelsAvgIntensArr: ndarray[Any, dtype[float64]], channel: str = 'g', fromTime: float | int | float64 | int64 | None = None, toTime: float | int | float64 | int64 | None = None, sliceMethod: str = 'from local max', funcParamsTuples: dict[str, tuple[Union[Sequence[float], numpy.ndarray[Any, numpy.dtype[numpy.float64]]], Union[Sequence[float], numpy.ndarray[Any, numpy.dtype[numpy.float64]]]]] | None = None, initialGuesses: dict[str, Union[Sequence[float], numpy.ndarray[Any, numpy.dtype[numpy.float64]]]] | None = None, criticalTime: float | None = None, exclusionCriteria: float = 0.12, exclusionMethod: str = 'first that works')

Bases: object

Representation of a pCRT measurement. Aside from the pCRT value itself, it also stores all the information that went into calculating the pCRT, as well as functions related to this calculation and storing the results in a file. This class is meant to be the easiest way to use pyCRT.

property B: ndarray[Any, dtype[float64]]

The average intensities of the B channel, measured from the start of the recording.

property G: ndarray[Any, dtype[float64]]

The average intensities of the G channel, measured from the start of the recording.

property R: ndarray[Any, dtype[float64]]

The average intensities of the R channel, measured from the start of the recording.

__init__(fullTimeScdsArr: ndarray[Any, dtype[float64]], channelsAvgIntensArr: ndarray[Any, dtype[float64]], channel: str = 'g', fromTime: float | int | float64 | int64 | None = None, toTime: float | int | float64 | int64 | None = None, sliceMethod: str = 'from local max', funcParamsTuples: dict[str, tuple[Union[Sequence[float], numpy.ndarray[Any, numpy.dtype[numpy.float64]]], Union[Sequence[float], numpy.ndarray[Any, numpy.dtype[numpy.float64]]]]] | None = None, initialGuesses: dict[str, Union[Sequence[float], numpy.ndarray[Any, numpy.dtype[numpy.float64]]]] | None = None, criticalTime: float | None = None, exclusionCriteria: float = 0.12, exclusionMethod: str = 'first that works')

Initializes the PCRT instance with all the parameters that are necessary for calculating the pCRT. This method has many parameters but only fullTimeScdsArr and channelsAvgIntensArr are required, though it is important to know about each parameter.

Parameters:
  • fullTimeScdsArr (np.ndarray of float) – An array of time instants measured in seconds, with respect to the start of the recording.

  • channelsAvgIntensArr (np.ndarray of float) –

    The array of average channel intensities over the pixels in a certain region of interest (ROI). Each line is an array of the average intensities for each channel (in the order of BGR).

    This, and fullTimeScdsArr are typically the outputs of videoReading.readVideo.

  • channel (str, default='g') – The channel that will be used to calculate the pCRT. Can be ‘b’, ‘g’ or ‘r’. This argument specifies which column of channelsAvgIntensArr will be stored as the channelFullAvgIntens property of this instance (see PCRT.channelFullAvgIntens).

  • fromTime (float or None, default=None) – The elements of fullTimeScdsArr from and to which the pCRT phenomenon actually takes place. This is the interval of channelFullAvgIntens. If None, this interval will be from the first and to the last elements of fullTimeScdsArr respectively. The rcrt.fromTime and rcrt.toTime attributes won’t be the same as these parameters after initialization, though, that depends on the sliceMethod (see below).

  • toTime (float or None, default=None) – The elements of fullTimeScdsArr from and to which the pCRT phenomenon actually takes place. This is the interval of channelFullAvgIntens. If None, this interval will be from the first and to the last elements of fullTimeScdsArr respectively. The rcrt.fromTime and rcrt.toTime attributes won’t be the same as these parameters after initialization, though, that depends on the sliceMethod (see below).

  • sliceMethod (str, default='from local max') – Which way the slice attribute is to be calculated from the fromTime and toTime parameters. See PCRT.setSlice for details.

  • funcParamsTuples (dict of str keys and tuples of 2 np.ndarray of float as) –

  • None (values or) – The fitted parameters and their standard deviations of the exponential, polynomial and pCRT exponential functions can be specified via this dictionary if they have been calculated beforehand. The keys are ‘exponential’, ‘polynomial’ and ‘pCRT’ respectively. A function that doesn’t have its key in this dictionary will be fitted during the initialization of the PCRT instance.

  • default=None – The fitted parameters and their standard deviations of the exponential, polynomial and pCRT exponential functions can be specified via this dictionary if they have been calculated beforehand. The keys are ‘exponential’, ‘polynomial’ and ‘pCRT’ respectively. A function that doesn’t have its key in this dictionary will be fitted during the initialization of the PCRT instance.

  • initialGuesses (dict of str keys and sequence of float values or None,) –

  • default=None – The initial guesses for each function. The valid keys are the same as of funcParamsTuples. For each function whose key is not in this dict, the default initial guesses (defined in the curveFitting module) will be used.

  • criticalTime (float or None, default=None) – The critical time used for the pCRT exponential function fitting. If None, it will be calculated by calcPCRT from the time and intensity arrays or from the fitted polynomial and exponential function parameters. (see curveFitting.calcPCRT)

  • exclusionCriteria (float, default=0.12) – The maximum relative uncertainty a pCRT measurement can have and not be rejected. If all fits on the criticalTime candidates fail this criteria, a RuntimeError will be raised. See curveFitting.calcPCRT for more information.

  • relativeUncertainty (float) – The pCRT’s relative uncertainty.

  • exclusionMethod (str, default='best fit') – Which criticalTime and its associated fitted pCRT parameters and standard deviations are to be returned by calcPCRT. Possible values are ‘best fit’, ‘strict’ and ‘first that works’ (consult the documentation for the calcPCRTBestFit, calcPCRTStrict and calcPCRTFirstThatWorks functions from the curveFitting module for a description of the effect of these possible values).

property avgIntensArr: ndarray[Any, dtype[float64]]

The array of normalized average intensities of a channel. This array goes along with timeScdsArr in that it encompasses only the portion of channelFullAvgIntens wherein the CRT phenomenon occurs.

calcPCRT(criticalTime: float | None = None, pCRTInitialGuesses: Sequence[float] | ndarray[Any, dtype[float64]] | None = None, exclusionMethod: str = 'best fit', exclusionCriteria: float = inf) Tuple[tuple[numpy.ndarray[Any, numpy.dtype[numpy.float64]], numpy.ndarray[Any, numpy.dtype[numpy.float64]]], float]

Simply returns the output of curveFitting.calcPCRT called with the instance’s attributes and this function’s parameters as its arguments. See curveFitting.calcPCRT for a detailed explantion.

property channelFullAvgIntens: ndarray[Any, dtype[float64]]

The average intensities of the channel specified by the ‘channel’ instance attribute, measured from the start of the recording.

property criticalTime: float

The critical time used for the pCRT calculation, either set via keyword argument during the instance’s initialization or calculated by curveFitting.calcPCRT.

property expTuple: tuple[Union[Sequence[float], numpy.ndarray[Any, numpy.dtype[numpy.float64]]], Union[Sequence[float], numpy.ndarray[Any, numpy.dtype[numpy.float64]]]]

The optimized parameters and standard deviations of the exponential function fitted on f(timeScdsArr)=avgIntensArr. See curveFitting.fitExponential.

classmethod fromArchive(filePath: str) PCRT

Creates an PCRT instance from the data stored in a file created by the PCRT.save method.

Parameters:

filePath (str) – The path to the file in the file system. It must be a numpy npz archive containing fullTimeScdsArr, channelsAvgIntenArr, channel, fromTime, toTime, expTuple, polyTuple, pCRTTuple and criticalTime (see the init method of PCRT for an explanation of what each of these are supposed to be).

See also

PCRT.save

Use this method to store the PCRT measurement in a file that is retrievable by this method.

classmethod fromCaptureDevice(capDeviceIndex: int, roi: tuple[int, int, int, int] | str | None = None, cameraResolution: Tuple[int, int] | None = None, recordingPath: str | None = None, codecFourcc: str = 'mp4v', recordingFps: float = 30.0, **kwargs: Any) PCRT

Creates the fullTimeScdsArr and channelsAvgIntensArr arrays from video read from a video capture device, and initializes the PCRT instance with these arrays and additional arguments passed to this function as kwargs.

Parameters:
  • roi (Tuple[int, int, int, int] or "all") – The region of interest, inside which the average of each pixel will be computed. This tuple must contain 4 integers: (x, y, length_x, and length_y), where x and y are the coordinates of the rectangle’s center. If roi == “all”, then the average will be computed on the entire frame. You can also select the ROI at any time during the video by pressing the space bar and dragging the square around the desired region.

  • cameraResolution (tuple of 2 ints, default=None) – Used to optionally change the camera resolution before handing over the VideoCapture instance. If reading from a video file, it does nothing.

  • recordingPath (str, default=None) – The path (with the extension!) in the filesystem wherein to save the recording. If falsy, it won’t record the video.

  • codecFourcc (str, default='mp4v') – The fourcc identifier for the video codec to be used for the recording. Refer to www.fourcc.org/codecs.php for a list of possible codes.

  • recordingFps (float, default=None) – The FPS (frames per second) for the recording, which doesn’t need to correspond to the FPS of the camera.

  • kwargs (dict of str keys and any values) – These additional arguments will be passed to this class’s __init__ method.

See also

videoReading.readVideo

Basically all this function does is call videoReading.readVideo with the arguments passed to this function, so refer to that function’s docstring for more information.

classmethod fromVideoFile(videoPath: str, roi: tuple[int, int, int, int] | str | None = None, displayVideo: bool = True, rescaleFactor: float | int | float64 | int64 = 1.0, waitKeyTime: int = 1, **kwargs: Any) PCRT

Creates the fullTimeScdsArr and channelsAvgIntensArr arrays from a video file and initializes the PCRT instance with these arrays, and additional arguments passed to this function as kwargs.

Parameters:
  • roi (Tuple[int, int, int, int] or "all") – The region of interest, inside which the average of each pixel will be computed. This tuple must contain 4 integers: (x, y, length_x, and length_y), where x and y are the coordinates of the rectangle’s center. If roi == “all”, then the average will be computed on the entire frame. You can also select the ROI at any time during the video by pressing the space bar and dragging the square around the desired region.

  • displayVideo (bool, default=True) – Whether or not to display the video while it is being read. This must be set to True if no ROI is specified, so the ROI can be manually selected by pressing the spacebar during the video exhibition.

  • rescaleFactor (real number, optional) – Factor by which each frame will be scaled. This can help reduce the load on the hardware and speed up computation. By default the video won’t be scaled.

  • waitKeyTime (int, optional) – How many milliseconds to wait for user input between each frame. The default value is 1, so on most machines the video will appear “sped up” relative to it being played on a regular video player. See cv2.waitKey for more information.

  • kwargs (dict of str keys and any value) – These additional arguments will be passed to this class’s __init__ method.

See also

videoReading.readVideo

Basically all this function does is call videoReading.readVideo with the arguments passed to this function, so refer to that function’s docstring for more information.

property pCRT: Tuple[float, float]

The pCRT and its uncertainty with a 95% confidence interval, as calculated by curveFitting.calcPCRT.

property pCRTTuple: tuple[Union[Sequence[float], numpy.ndarray[Any, numpy.dtype[numpy.float64]]], Union[Sequence[float], numpy.ndarray[Any, numpy.dtype[numpy.float64]]]]

The optimized parameters and standard deviations of the pCRT exponential function fitted on f(timeScdsArr)=avgIntensArr. See curveFitting.fitPCRT.

property polyTuple: tuple[Union[Sequence[float], numpy.ndarray[Any, numpy.dtype[numpy.float64]]], Union[Sequence[float], numpy.ndarray[Any, numpy.dtype[numpy.float64]]]]

The optimized parameters and standard deviations of the polynomial function fitted on f(timeScdsArr)=avgIntensArr. See curveFitting.fitPolynomial.

property relativeUncertainty: float64

The relative uncertainty (with a 95% confidence interval) for the pCRT measurement, on the scale from 0 to 1.

save(filePath: str) None

Saves the relevant attributes of this PCRT instance in a numpy npz file on the specified file path. To retrieve the data in this file later, use PCRT.fromArchive.

saveAvgIntensPlot(figPath: str) None

Saves the plot of average intensities for every channel in function of the timestamp of each frame in the entire video to a file. See arrayPlotting.makeAvgIntensPlot and arrayPlotting.saveAvgIntensPlot.

savePCRTPlot(figPath: str) None

Saves the plot of normalized average intensities for the channel specified in the initialization of the PCRT instance, in function of the time since the removal of the pressure from the skin, and the fitted functions on this data. This is supposed to show only the CRT phenomenon. See arrayPlotting.makePCRTPlot and arrayPlotting.showPCRTPlot.

setSlice(fromTime: float | int | float64 | int64 | None = None, toTime: float | int | float64 | int64 | None = None, sliceMethod: str = 'from local max') None

Sets the slice object that will be used to slice the channelFullAvgIntens and fullTimeScdsArr arrays to produce avgIntensArr and timeScdsArr respectively. This slice is supposed to indicate only the region wherein the CRT phenomenon takes place. This slice is used for PCRT.timeScdsArr and PCRT.avgIntensArr.

Parameters:
  • fromTime (float or None, default=None) – The elements of fullTimeScdsArr from and to which the pCRT phenomenon actually takes place. This is the interval of channelFullAvgIntens. If None, this interval will be from the first and to the last elements of fullTimeScdsArr respectively. The rcrt.fromTime and rcrt.toTime attributes won’t be the same as these parameters after initialization, though, that depends on the sliceMethod (see below).

  • toTime (float or None, default=None) – The elements of fullTimeScdsArr from and to which the pCRT phenomenon actually takes place. This is the interval of channelFullAvgIntens. If None, this interval will be from the first and to the last elements of fullTimeScdsArr respectively. The rcrt.fromTime and rcrt.toTime attributes won’t be the same as these parameters after initialization, though, that depends on the sliceMethod (see below).

  • sliceMethod (str, default='from local max') –

    Which way the slice attribute is to be calculated from the fromTime and toTime parameters. The possible values are:

    ’from max’: the slice will be calculated from the absolute maximum of channelFullAvgIntens up to the array’s end. The fromTime and toTime arguments are not necessary for this, and in fact this is this function’s behaviour when they are both None.

    ’by time’: the slice will start on the first element of timeScdsArr that is greater than or equal to fromTime and end on the first element that is greater than or equal to toTime.

    ’from local max’: the slice will start on the maximum of channelFullAvgIntens between the indexes of fullTimeScdsArr that correspond to fromTime and toTime, and end on toTime.

showAvgIntensPlot() None

Shows the plot of average intensities for every channel in function of the timestamp of each frame in the entire video. See arrayPlotting.makeAvgIntensPlot and arrayPlotting.showAvgIntensPlot.

showPCRTPlot() None

Shows the plot of normalized average intensities for the channel specified in the initialization of the PCRT instance, in function of the time since the removal of the pressure from the skin, and the fitted functions on this data. This is supposed to show only the CRT phenomenon. See arrayPlotting.makePCRTPlot and arrayPlotting.showPCRTPlot.

property timeScdsArr: ndarray[Any, dtype[float64]]

The array of time instants in seconds, measured from the removal of the pressure from the skin. This array is supposed to encompass only portion of fullTimeScdsArr wherein the CRT phenomenon occurs.

pyCRT.videoReading module

Video reading functionality (pyCRT.videoReading)

This module contains everything directly related to extracting lightly processed data from video files or cameras, in particular obtaining the arrays with each frame’s time within the video and the average intensities array calculated within a region of interest of each frame.

Notes

This module has only been tested with wmv and mp4 files, with WMV2, and DIVX and MP4V codecs respectively.

pyCRT.videoReading.checkCaptureDevice(capDeviceIndex: int) bool

Checks if the capture device with the provided index is available, returning True if it is and False otherwise.

pyCRT.videoReading.frameReader(capture: VideoCapture, rescaleFactor: float | int | float64 | int64 = 1.0) Generator[ndarray[Any, dtype[float64]], None, None]

A generator for reading each frame from the VideoCapture instance, and optionally rescaling it.

Parameters:
  • capture (cv.VideoCapture) – The OpenCV VideoCapture instance from which to extract the frames. See pyCRT.videoReading.videoCapture

  • rescaleFactor (int or float, default=1.0) – Factor by which each frame will be scaled. This can help reduce the load on the hardware and speed up computation. By default the video won’t be scaled.

Yields:

frame (np.ndarray) – Width by Length by 3 matrix of BGR pixel intensities

pyCRT.videoReading.frameWriter(recordingPath: str, codecFourcc: str = 'mp4v', recordingFps: float = 30.0) Generator[None, ndarray[Any, dtype[float64]], None]

A generator that acts as a coroutine for recording the capture’s frames. The idea is that you initialize this generator with the arguments described below and send each frame to be recorded with the send method.

Parameters:
  • recordingPath (str, default=None) – The path (with the extension!) in the filesystem wherein to save the recording.

  • codecFourcc (str, default='mp4v') – The fourcc identifier for the video codec to be used for the recording. Refer to www.fourcc.org/codecs.php for a list of possible codes.

  • recordingFps (int, default=None) – The FPS (frames per second) for the recording, which doesn’t need to correspond to the FPS of the camera or the source video.

pyCRT.videoReading.listCaptureDevices(checkUpTo: int = 10) list[int]

Checks the first checkUpTo indexes for cv2.VideoCapture and returns a list with all the indexes that are available. See checkCaptureDevice.

pyCRT.videoReading.readVideo(videoSource: str | int, roi: tuple[int, int, int, int] | str | None = None, displayVideo: bool = True, recordingPath: str | None = None, rescaleFactor: float | int | float64 | int64 = 1.0, waitKeyTime: int = 1, cameraResolution: tuple[int, int] | None = None, codecFourcc: str = 'mp4v', recordingFps: float = 30.0) tuple[numpy.ndarray[Any, numpy.dtype[numpy.float64]], numpy.ndarray[Any, numpy.dtype[numpy.float64]]]

Extracts the time in seconds of each frame and the average pixel intensities of each channel within the region of interest (ROI).

Parameters:
  • videoSource (int or str) – The first argument to cv2.VideoCapture. If an int, it will take the corresponding detected camera as the video source. If a str, It’ll take it as a path in the filesystem for a video file.

  • roi (Tuple[int, int, int, int] or "all") – The region of interest, inside which the average of each pixel will be computed. This tuple must contain 4 integers: (x, y, length_x, and length_y), where x and y are the coordinates of the rectangle’s center. If roi == “all”, then the average will be computed on the entire frame. You can also select the ROI at any time during the video by pressing the space bar and dragging the square around the desired region.

  • displayVideo (bool, default=True) – Whether or not to display the video while it is being read. This must be set to True if no ROI is specified, so the ROI can be manually selected by pressing the spacebar during the video exhibition.

  • recordingPath (str, default=None) – The path (with the extension!) in the filesystem wherein to save the recording. If falsy, it won’t record the video.

  • rescaleFactor (real number, optional) – Factor by which each frame will be scaled. This can help reduce the load on the hardware and speed up computation. By default the video won’t be scaled.

  • waitKeyTime (int, optional) – How many milliseconds to wait for user input between each frame. The default value is 1, so on most machines the video will appear “sped up” relative to it being played on a regular video player. See cv2.waitKey for more information.

  • cameraResolution (tuple of 2 ints, default=None) – Used to optionally change the camera resolution before handing over the VideoCapture instance. If reading from a video file, it does nothing.

  • codecFourcc (str, default='mp4v') – The fourcc identifier for the video codec to be used for the recording. Refer to www.fourcc.org/codecs.php for a list of possible codes.

  • recordingFps (float, default=None) – The FPS (frames per second) for the recording, which doesn’t need to correspond to the FPS of the camera or the source video.

Returns:

  • fullTimeScdsArr (1D np.ndarray) – Time in seconds of each frame in the video.

  • channelsAvgIntensArr (2D np.ndarray) – Average pixel intensity inside the region of interest with respect to time. It is an array with shape (len(fullTimeScdsArr), 3), wherein each element is an array with the average intensity of the B, G and R (respectively) channels at that instant.

Raises:
  • TypeError – If roi isn’t a tuple or a str.

  • ValueError – If roi is a string, but not “all”, or isn’t a tuple of 4 elements

  • RuntimeError – If this function finished reading the video but no ROI was passed or selected.

pyCRT.videoReading.videoCapture(videoSource: int | str, cameraResolution: tuple[int, int] | None = None) VideoCapture

Context manager for working with a cv2.VideoCapture instance.

Parameters:
  • videoSource (int or str) – The first argument to cv2.VideoCapture. If an int, it will take the corresponding detected camera as the video source. If a str, It’ll take it as a path in the filesystem for a video file.

  • cameraResolution (tuple of 2 ints, default=None) – Used to optionally change the camera resolution before handing over the VideoCapture instance. If reading from a video file, it does nothing.

Yields:

cv2.VideoCapture

Raises:
  • ValueError – If videoSource is a str but there isn’t any file in the specified path.

  • TypeError – If videoSource isn’t a str or an int

Notes

This context manager performs no other checks other than those indicated on the Raises section. This warrants mentioning because OpenCV gives the most cryptic, confusing and even misleading error messages, so care must be taken.