ShockOscillationAnalysis package
Subpackages
Submodules
ShockOscillationAnalysis.ShockOscillationAnalysis module
Created on Tue Dec 20 09:32:30 2022
@author: Ahmed H. Hanfy
- class ShockOscillationAnalysis.ShockOscillationAnalysis.SOA(f: int = 1, D: int = 1, pixelScale: float = 1)
Bases:
object- CleanSnapshots(img: ndarray[int], *args, **kwargs) ndarray[int]
Clean and enhance snapshots based on specified corrections. This method takes an original image snapshot img and applies specified corrections based on the provided *args. Supported corrections include ‘Brightness/Contrast’, ‘Average’, and ‘FFT’.
- Parameters:
img (numpy.ndarray): Original image snapshot.
- ** args (str)*: Variable-length argument list specifying the corrections to apply.
Supported corrections: ‘Brightness/Contrast’, ‘Average’, ‘FFT’.
- ** kwargs: Additional parameters for correction functions.
- FFT:
filterCenter (list): Overrides the default filter center if provided.
D (int): Overrides the default cut-off frequency if provided.
n (int): Overrides the default filter order if provided.
ShowIm (bool): Overrides the default value for displaying images if provided.
- Brightness/Contrast:
Brightness (float, optional): Brightness adjustment factor (default: 1). Valid range: 0 (min) to 2 (max).
Contrast (float, optional): Contrast adjustment factor (default: 1). Valid range: 0 (min) to 2 (max).
Sharpness (float, optional): Sharpness adjustment factor (default: 1). Valid range: 0 (min) to 3 (max).
- Returns:
numpy.ndarray: Corrected image snapshot.
- Example:
>>> cleaned_image = instance.CleanSnapshots(original_image, 'Brightness/Contrast', 'FFT', Brightness=1.5, D=20)
Note
If ‘Brightness/Contrast’ is in *args, the image undergoes brightness and contrast adjustments.
If ‘Average’ is in *args, the average illumination effect is removed.
If ‘FFT’ is in *args, the illumination effects are corrected using FFT-based filtering.
- DefineReferences(img: ndarray[int], shp: tuple[int], Ref_x0: list[int], scale_pixels: bool, Ref_y0: int = -1, Ref_y1: int = -1, slice_loc: int = 0, **kwargs) tuple[list[int], int, int]
Define reference lines on an image for scalling and further processing.
- Parameters:
img (np.ndarray): The image on which to draw the reference lines.
shp (tuple): Shape of the image (height, width).
Ref_x0 (list[int]): List of x-coordinates for vertical reference lines.
scale_pixels (bool): Whether to scale pixels based on the reference lines.
Ref_y0 (int, optional): y-coordinate of the top horizontal reference line. Default is -1.
Ref_y1 (int, optional): y-coordinate of the bottom horizontal reference line. Default is -1.
slice_loc (int, optional): Location of the slice for horizontal reference lines. Default is 0.
- Returns:
- tuple: A tuple containing:
Ref_x0 (list[int]): Sorted list of x-coordinates for vertical reference lines.
Ref_y0 (int): y-coordinate of the top horizontal reference line.
Ref_y1 (int): y-coordinate of the bottom horizontal reference line.
- Example:
>>> instance = SOA() >>> img = cv2.imread('path/to/image.jpg') >>> shape = img.shape >>> Ref_x0 = [100, 200] >>> scale_pixels = True >>> Ref_y0 = -1 >>> Ref_y1 = -1 >>> slice_loc = 50 >>> ref_x0, ref_y0, ref_y1 = instance.DefineReferences(img, shape, Ref_x0, scale_pixels, Ref_y0, Ref_y1, slice_loc) >>> print(ref_x0, ref_y0, ref_y1)
Note
The function sets up vertical and horizontal reference lines on the image.
It calculates the pixel scale if scale_pixels is True using horizontal distance between the reference vertical lines {Ref_x0}.
- LineDraw(img: ndarray[int], lineType: str, LineNameInd: int, Intialize=False, **kwargs) list
Drive the extract_coordinates function to draw lines.
- Parameters:
img (numpy.ndarray): A single OpenCV image.
- lineType (str):
‘V’ for Vertical line (starts from top to bottom of the image),
‘H’ for Horizontal line (starts from the left to the right),
‘Inc’ for Inclined line (not averaging, takes the exact selected points).
LineNameInd (int): Index of the window title from the list.
Initialize (bool, optional): To reset the values of Reference and line_coordinates for a new line set. True or False (Default: False).
- Returns:
list: Cropping limits or (line set).
- Example:
>>> instance = SOA() >>> line_set = instance.LineDraw(image, 'V', 0, Initialize=True) >>> print(line_set)
Note
The function uses the extract_coordinates method to interactively draw lines on the image.
It waits until the user presses a key to close the drawing window.
Note
LineNameIndis the index number refering to one of these values as window title:“First Reference Line (left)”,
“Second Reference Line (right)”,
“Horizontal Reference Line”,
“estimated shock location”
- ShockTrakingAutomation(img: ndarray[int], method: str = 'integral', reviewInterval: list[int] = [0, 0], Signalfilter: str = None, **kwargs) list[float]
This method automates the shock tracking process and generates shock signals based on linescanning technique, where a snapshots list is given as input, three methods of tracking can be proposed
integral: This method tracks the shock through the largest blocked area by the knife. More information and detailed discrepancies can be found in this article https://dx.doi.org/10.2139/ssrn.4797840.
darkest_spot: The shock is tracked by the abslute dark point of the schlieren image
maxGrad: By performing sobel gradient algorithem, the shock edge is determined as the maximum gradient and tracked. More information can be found in this article https://doi.org/10.1007/s00348-021-03145-3
for better resolution and to avoid any missed shock location, signal filtering can be applied, the method supports these methods
median: run through the signal entry by entry, replacing each entry with the median of the entry and its neighboring entries when entries are 3
Wiener: based on minimizing the mean square error between the estimated random process and the desired process.
med-Wiener: use both filter sequentially
- Parameters:
img (numpy.ndarray): Input image or image data.
method (str): Method for shock tracking (integral, darkest_spot, maxGrad). Default is ‘integral’.
reviewInterval (list): List containing two integers representing the review interval. Available only with ‘integral’ method. Default is [0, 0].
Signalfilter (str): The method for signal filtering (median, Wiener, med-Wiener). Default is None.
CheckSolutionTime (bool): Whether to check solution time. Default is True.
** kwargs:
- Returns:
numpy.ndarray: Generated shock signals.
- Example:
>>> shock_signals = ShockTrakingAutomation(image, method='integral', reviewInterval=[10, 20], Signalfilter='median', CheckSolutionTime=True)
- VelocitySignal(Signal: list[float], TotalTime: float) list[float]
Calculate the velocity signal from the given positional signal. The function calculates the velocity at each point in the Signal using finite differences. It uses a forward difference for the first point, a backward difference for the last point, and a central difference for all intermediate points. It then subtracts the average velocity from each point to return the velocity signal.
- Parameters:
Signal (list or numpy.ndarray): Positional signal data points in mm.
TotalTime (float): Total time duration over which the signal is recorded.
- Returns:
numpy.ndarray: Velocity signal after removing the average velocity.
- Example:
>>> signal = [0, 1, 2, 3, 4, 5] >>> total_time = 5.0 >>> velocity_signal = VelocitySignal(signal, total_time) >>> print(velocity_signal)
Note
The velocity is calculated in units per second, while the signal amplitudes are measured in millimeters (mm).
The returned velocity signal has the mean velocity subtracted.
- extract_coordinates(event: int, x: int, y: int, flags: int, parameters: tuple[str, tuple[int], str]) None
Record starting (x, y) coordinates on left mouse button click and draw a line that crosses all over the image, storing it in a global variable. In case of horizontal or vertical lines, it takes the average between points.
- Drawing steps:
Push the left mouse on the first point.
Pull the mouse cursor to the second point.
The software will draw a thick red line (indicating the mouse locations) and a green line indicating the Final line result.
To confirm, press the left click anywhere on the image, or to delete the line, press the right click anywhere on the image.
Press any key to proceed.
- Parameters:
event (int): The type of event (e.g., cv2.EVENT_LBUTTONDOWN).
x (int): The x-coordinate of the mouse cursor.
y (int): The y-coordinate of the mouse cursor.
flags (int): Flags associated with the mouse event.
- parameters (tuple): A tuple containing:
Name of the window to display the image.
Image shape (tuple of y-length and x-length).
- Line type (‘V’ for vertical, ‘H’ for horizontal,
‘Inc’ for inclined).
- Returns:
None
- Example:
>>> instance = SOA() >>> cv2.setMouseCallback(window_name, instance.extract_coordinates, parameters)
Note
If ‘Inc’ is provided as the line type, it uses the ‘InclinedLine’ method to calculate the inclined line and display it on the image.
ShockOscillationAnalysis.decorators module
Created on Sun May 28 13:49:58 2024
@author: Ahmed H. Hanfy
- ShockOscillationAnalysis.decorators.TimeCalculation(timeInSec: float)
Convert the given time in seconds into a formatted string representation.
- Parameters:
timeInSec (float): The time duration in seconds.
- Returns:
None
- Example:
>>> instance = SOA() >>> instance.TimeCalculation(3665)
Note
The function converts the time duration into hours, minutes, and seconds.
It prints the total run time in a human-readable format.
- ShockOscillationAnalysis.decorators.calculate_running_time(func)
Decorator to calculate the running time of a function.
This decorator calculates the running time of a function by measuring the time taken to execute it. It prints the running time to the console using the TimeCalculation function.
- Parameters:
func (function): The function to be decorated.
- Returns:
function: The wrapped function.
- Examples:
>>> @calculate_running_time ... def my_function(): ... # function body ... pass
In this example, the running time of the my_function will be calculated and printed to the console.
ShockOscillationAnalysis.generateshocksignal module
Created on Sun Dec 10 02:41:58 2023
@author: Ahmed H. Hanfy
- ShockOscillationAnalysis.generateshocksignal.DarkestSpotShocktracking(SnapshotSlice: list[int], ShockLocation: list[float], **kwargs) tuple[list, list]
Perform shock tracking based on the location of the darkest spot in a snapshot slice.
This function identifies the position of the darkest spot in a given snapshot slice and appends its index to the list of shock locations. Optionally, it also records any uncertainty regarding the shock location.
- Parameters:
SnapshotSlice (list[int]): The snapshot slice to be analyzed for shock tracking.
Plot (bool): A flag indicating whether to generate plots during shock tracking.
count (int): The count or index of the current snapshot slice.
ShockLocation(list): A list containing the indices of previously detected shock locations.
uncertain (list): A list to store any uncertain shock locations.
- Returns:
A tuple containing the updated ShockLocation list and the uncertain list.
- ShockOscillationAnalysis.generateshocksignal.GenerateShockSignal(img: ndarray[int], method: str = 'integral', signalfilter: str = None, review_slice_tracking: int | list[int, int] = -1, log_dirc: str = '', **kwargs) tuple[list, list]
Find the shockwave locations in a series of snapshots with optional signal processing filters.
- Parameters:
img (numpy.ndarray): Input array of shape (num_snapshots, height, width) representing a series of snapshots.
method (str, optional): shock tracking method (integral(Defult), darkest_spot, maxGrad).
review_slice_tracking (int|list[int, int], optional): List specifying the review interval for plotting. Default is -1.
signalfilter (str, optional): Type of signal filter to apply (‘median’, ‘Wiener’, ‘med-Wiener’). Default is None.
log_dirc (str): log file directory.
- Returns:
ShockLocation (list): List of shock locations for each snapshot.
uncertain (list): List of uncertain shock locations with additional information.
- Examples:
>>> # Create an instance of the class >>> SA = SOA(f,D) >>> # Load a series of snapshots (assuming 'snapshots' is a NumPy array) >>> shock_locations, uncertain_locations = SA.GenerateShockSignal(snapshots)
- ShockOscillationAnalysis.generateshocksignal.GradShocktracking(GradSlice, ShockLocation, **kwargs)
Perform shock tracking based on gradient values.
- Parameters:
GradSlice (numpy.ndarray): Array containing gradient values for shock tracking.
ShockLocation (list): List containing the shock location from previous iterations.
- Returns:
- tuple: A tuple containing:
list: Updated shock location.
bool: Flag indicating uncertainty.
- Example:
>>> shock_loc, is_uncertain = GradShocktracking(grad_values, Plot=True, count=10, ShockLocation=[0], uncertain=False)
This function performs shock tracking based on gradient values extracted from a slice of data. It updates the shock location and determines if there’s uncertainty in the tracking process.
- ShockOscillationAnalysis.generateshocksignal.GradientGenerator(img: ndarray[int], KernalDim: int = 3) ndarray[int]
Generate the gradient magnitude of an image using Sobel operators. This function applies Sobel operators to compute the gradient magnitude of the input image. The KernalDim parameter specifies the dimension of the Sobel kernel used for gradient calculation.
- Parameters:
img (numpy.ndarray): Input image (grayscale).
KernalDim (int): Dimension of the Sobel kernel. Default is 3.
- Returns:
numpy.ndarray: Gradient magnitude of the input image.
- Example:
>>> gradient = GradientGenerator(image, KernalDim=3)
Note
The input image should be in grayscale.
The function returns the gradient magnitude of the input image.
- ShockOscillationAnalysis.generateshocksignal.IntegralShocktracking(SnapshotSlice: list[int], ShockLocation: float, Plot: bool, count: int, uncertain: bool, log_dirc: str = '') tuple[float, bool]
Perform shock tracking based on integral method discriped in https://dx.doi.org/10.2139/ssrn.4797840.
- Parameters:
SnapshotSlice (list): snapshot slice in grayscale where shock is tracked.
Plot (bool): Whether to plot the slice tracking process info.
count (int): Current snapshot/image number.
ShockLocation (float): Location of the shock from the previous iteration.
uncertain (bool): Flag indicating uncertainty.
log_dirc (str): log file directory.
- Returns:
- tuple: A tuple containing:
float: Updated shock location.
bool: Flag indicating uncertainty.
- Example:
>>> shock_loc, is_uncertain = IntegralShocktracking(slice_values, Plot=True, count=10, ShockLocation=0, uncertain=False)
It updates the shock location and determines if there’s uncertainty in the tracking process.
ShockOscillationAnalysis.imgcleaningfunctions module
Created on Sat Dec 9 00:20:49 2023
@author: Ahmed H. Hanfy
- ShockOscillationAnalysis.imgcleaningfunctions.BrightnessAndContrast(img: array, log_dirc, **kwargs) array
Adjusts the brightness, contrast, and sharpness of an image. This function adjusts the brightness, contrast, and sharpness of the input image. The Brightness, Contrast, and Sharpness parameters control the degree of adjustment. The image is converted to grayscale if it is in color. The adjusted image is returned as a NumPy array.
If optional parameters are not provided, default values are used.
The valid range for Brightness and Contrast is from 0 to 2, and for Sharpness is from 0 to 3.
- Parameters:
img (numpy.ndarray): NumPy array representing the image.
log_dirc (str): log file directory.
- ** kwargs:
Brightness (float, optional): Brightness adjustment factor (default: 1). Valid range: 0 (min) to 2 (max).
Contrast (float, optional): Contrast adjustment factor (default: 1). Valid range: 0 (min) to 2 (max).
Sharpness (float, optional): Sharpness adjustment factor (default: 1). Valid range: 0 (min) to 3 (max).
- Returns:
numpy.ndarray: NumPy array representing the adjusted image.
- Example:
>>> adjusted_image = BrightnessAndContrast(image, Brightness=1.5, Contrast=1.2, Sharpness=2)
See also
For more information on PIL: https://pillow.readthedocs.io/en/stable/
Important
This function uses the Python Imaging Library (PIL) to perform the adjustments. Ensure that the PIL library is installed in your Python environment.
- ShockOscillationAnalysis.imgcleaningfunctions.CleanIlluminationEffects(img: array, log_dirc, filterCenter: list[tuple] = [(0, 233)], D: int = 10, n: int = 10, ShowIm: bool = False, **kwargs) array
Clean illumination effects from an image using a frequency domain approach.
- Parameters:
img (numpy.ndarray): Input image (grayscale or BGR).
log_dirc (str): log file directory.
filterCenter (list): Coordinates [x, y] of the filter center. Default: [0, 233].
D (float): Cut-off frequency for the low-pass filter. Default: 10.
n (int): Filter order. Default: 10.
ShowIm (bool): Whether to display intermediate images during processing. Default: False.
- ** kwargs: Additional keyword arguments:
filterCenter (list): Overrides the default filter center if provided.
D (int): Overrides the default cut-off frequency if provided.
n (int): Overrides the default filter order if provided.
ShowIm (bool): Overrides the default value for displaying images if provided.
- Returns:
numpy.ndarray: Cleaned image.
- Example:
>>> import cv2 >>> import numpy as np >>> image = cv2.imread('your_image.jpg') >>> result = CleanIlluminationEffects(image, filterCenter=[0, 233], D=10, n=10, ShowIm=True) >>> cv2.imshow('Original Image', image) >>> cv2.imshow('Cleaned Image', result) >>> cv2.waitKey(0) >>> cv2.destroyAllWindows()
Note
If the input image is in color (BGR), it will be converted to grayscale before processing.
The function uses a frequency domain approach with a low-pass filter to remove illumination effects.
The filter parameters (filterCenter, D, n) can be adjusted to control the cleaning process.
If ShowIm is set to True, intermediate images will be displayed during processing.
- ShockOscillationAnalysis.imgcleaningfunctions.SliceListAverage(img: array, log_dirc: str = '') array
Compute the average intensity profile across the width of an image and subtract it from each row.
- Parameters:
img (numpy.ndarray): Input image (grayscale or BGR).
log_dirc (str): log file directory.
- Returns:
numpy.ndarray: New image with the average intensity profile subtracted from each row.
- Example:
>>> import cv2 >>> import numpy as np >>> image = cv2.imread('your_image.jpg') >>> result = Average(image) >>> cv2.imshow('Original Image', image) >>> cv2.imshow('Result Image', result) >>> cv2.waitKey(0) >>> cv2.destroyAllWindows()
Note
If the input image is in color (BGR), it will be converted to grayscale before processing.
The function computes the average intensity profile across the width of the image.
It then subtracts this average from each row to obtain a new image.
- ShockOscillationAnalysis.imgcleaningfunctions.plotting(FFT: array, y: int, Spectlocation: list) None
Plot the magnitude spectrum of a Fourier-transformed image. This function plots the magnitude spectrum of the Fourier-transformed image. The input ‘FFT’ is a 2D NumPy array representing the Fourier-transformed image. The ‘y’ parameter is the height of the original image. The ‘Spectlocation’ parameter is a list containing the location information for spectral analysis.
The plot displays the magnitude spectrum using a logarithmic scale. The vertical axis is limited based on the height of the original image and the spectral location.
- Parameters:
FFT (numpy.ndarray): 2D NumPy array representing the Fourier-transformed image.
y (int): Height of the original image.
Spectlocation (list): List containing the location information for spectral analysis.
- Returns:
None
- Example:
>>> plotting(FFT_image, 512, [0, 233])
Note
This function assumes that the FFT input is a complex-valued array with shape (height, width, 2), where the last dimension represents the real and imaginary parts of the Fourier-transformed image.
ShockOscillationAnalysis.linedrawingfunctions module
Created on Fri Dec 1 10:38:37 2023
author: Ahmed H. Hanfy
- ShockOscillationAnalysis.linedrawingfunctions.AngleFromSlope(slope: float) float
Calculate the angle in degrees from the given slope. This function computes the angle in degrees corresponding to the provided slope value.
- Parameters:
slope (float): The slope of the line.
- Returns:
float: The angle in degrees corresponding to the given slope.
- Example:
>>> slope = 2 >>> angle = AngleFromSlope(slope) >>> print(angle) 26.56505117707799
- ShockOscillationAnalysis.linedrawingfunctions.InclinedLine(P1: tuple[int], P2: tuple[int] = (), slope: float = None, imgShape: tuple[int] = (), log_dirc='') tuple[tuple[int], tuple[int], float, float]
Generates the inclined line equation from two points or one point and slope.
The image boundary/shape should be given.
- Parameters:
P1 (tuple): First point tuple (a1, b1).
P2 (tuple, optional): Second point tuple (a2, b2). Defaults to ().
slope (float, optional): Slope of the line. Defaults to None.
imgShape (tuple): Image size (y-length, x-length).
- Returns:
- tuple: A tuple containing:
first boundary point tuple.
second boundary point tuple.
line slope.
y-intercept.
- Example:
>>> instance = YourClass() >>> result = instance.InclinedLine((0, 0), (2, 4), imgShape=(5, 5)) >>> print(result) ((0, 0), (5, 5), 1.0, 0)
Note
If imgShape is not provided, the function prints an error message and aborts the program.
If only one point (P1) and slope (slope) are provided, the function calculates the second point.
If the line is not vertical or horizontal, it calculates the boundary points based on the image shape.
If the line is vertical, the slope is np.inf, and the function returns vertical boundary points.
If the line is horizontal, the slope is 0, and the function returns horizontal boundary points.
- ShockOscillationAnalysis.linedrawingfunctions.XCheck(x: float, Shp: tuple[int], slope: float, a: float) tuple[float]
Check and calculate the image boundary y-coordinate based on the given x-coordinate and slope.
This function takes an x-coordinate, image shape parameters (Shp), slope, and intercept (a) as inputs, and calculates the corresponding y-coordinate (p2) based on the specified conditions.
- Parameters:
x (float): The x-coordinate to be checked.
Shp (tuple): A tuple containing shape parameters (Shp[0] for y-axis limit, Shp[1] for x-axis limit).
slope (float): The slope of the line.
a (float): The y-intercept of the line.
- Returns:
tuple: A tuple (p2) representing the calculated point (x, y).
- Example:
>>> instance = YourClass() >>> result = instance.XCheck(2.5, (10, 5), 2, 3) >>> print(result) (2.5, 8)
Note
If x is within the range [0, Shp[1]], the y-coordinate is calculated based on the line equation.
If x is greater than Shp[1], the y-coordinate is calculated at the point (Shp[1], y2), where y2 is determined by the line equation.
If x is less than 0, the y-coordinate is calculated at the point (0, y2), where y2 is determined by the line equation.
ShockOscillationAnalysis.preview module
Created on Wed Feb 28 11:05:30 2024
@author: Ahmed H. Hanfy
- ShockOscillationAnalysis.preview.AvgAnglePlot(ax: axes, img_shp: tuple, P: tuple, slope: float, angle: float, txt: bool = True, lin_color='w', lin_opacity=1, **kwargs) None
Plot the average angle line and optional text annotation on a given axis. This function uses the InclinedLine function to determine the end points of the line based on the given slope and image shape. It then plots the line and an optional text annotation indicating the angle.
- Parameters:
ax (matplotlib.axes.Axes): The axis on which to plot.
img_shp (tuple): Shape of the image (height, width).
P (tuple): A point (x, y) through which the line passes.
slope (float): Slope of the line.
angle (float): Angle to display as annotation.
txt (bool): Whether to show the text annotation for oscilation boundary.
- **kwargs: Additional keyword arguments for customization:
avg_txt_Yloc (int, optional): Y location for the text annotation. Default is image height minus 100.
avg_txt_size (int, optional): Font size of the text annotation. Default is 26.
- Example:
>>> fig, ax = plt.subplots() >>> img_shp = (600, 800) >>> P = (100, 300) >>> slope = 0.5 >>> angle = 45.0 >>> AvgAnglePlot(ax, img_shp, P, slope, angle, avg_lin_color='r', avg_show_txt=True) >>> plt.show()
- ShockOscillationAnalysis.preview.PreviewCVPlots(img: ndarray, Ref_x0: list[int] = None, Ref_y: list[int] | int = None, tk: list[int] = None, avg_shock_loc: list[float] = None, **kwargs)
PreviewCVPlots function is used to overlay various plot elements on an image for visualization purposes.
- Parameters:
img (np.ndarray): Input image.
Ref_x0 (list[int]): List of x-coordinates for reference lines.
Ref_y (list[int]|int): List of y-coordinates for reference lines.
tk (list[int]): List of y-coordinates for tk lines.
avg_shock_loc (list[float]): Average shock location.
- Keyword Arguments:
Ref_x0_color (tuple): Color of reference x0 lines. Defaults to CVColor.GREEN.
tk_color (tuple): Color of tk lines. Defaults to CVColor.GREENBLUE.
Ref_y1_color (tuple): Color of reference y1 lines. Defaults to CVColor.FUCHSIPINK.
Ref_y2_color (tuple): Color of reference y2 lines. Defaults to CVColor.YELLOW.
avg_shock_loc_color (tuple): Color of average shock location line. Defaults to CVColor.CYAN.
- Returns:
np.ndarray: Image with overlaid plot elements.
- ShockOscillationAnalysis.preview.angle_txt(ax, X, avg_txt_Yloc, angle, lin_color, lin_opacity, avg_txt_size, op_rotate=False)
- ShockOscillationAnalysis.preview.plot_review(ax: axes, img: ndarray, shp: tuple[int], x_loc: list[float], column_y: list[float], uncertain: list[float], uncertain_y: list[float], avg_slope: float, avg_ang: float, mid_loc: int = -1, y: int = -1, y_avg: float = -1, avg_preview_mode=None, Mach_ang_mode=None, **kwargs)
Plot review function to visualize shock points and additional features on an image.
- Parameters:
ax (matplotlib.axes._subplots.AxesSubplot): The subplot to draw the plot on.
img (np.ndarray): The input image to display.
shp (tuple): The shape of the image.
x_loc (list): List of x-coordinates for the shock points.
column_y (list): List of y-coordinates for the shock points.
uncertain (list): List of uncertain points.
uncertain_y (list): List of y-coordinates for uncertain points.
avg_slope (float): The average slope.
avg_ang (float): The average angle.
mid_loc (int, optional): The middle location. Defaults to -1.
y (int, optional): The y-coordinate. Defaults to -1.
y_avg (list(float), optional): middle vertical locations from RANSAC. Defaults to -1.
avg_preview_mode (bool, optional): Flag indicating whether to show average preview mode. Defaults to None.
Mach_ang_mode (bool, optional): Flag indicating whether to show Mach angle mode. Defaults to None.
**kwargs: Additional keyword arguments for customization.
- Returns:
None
- ShockOscillationAnalysis.preview.residual_preview(error, margins, nSlices, count, log_dirc='')
- ShockOscillationAnalysis.preview.rotate_axes(ax: axes, angle: float, center: tuple[int] = (0, 0)) axes
Rotate the elements of a Matplotlib axis around a specified center point. This function applies an affine transformation to rotate all plot elements (lines and images) on the given Matplotlib axis by a specified angle around a defined center.
- Parameters:
ax (matplotlib.axes.Axes): The Matplotlib axis object containing the elements to be rotated.
angle (float): The angle of rotation in degrees (counterclockwise).
center (tuple[int, int]): A tuple representing the (x, y) coordinates of the rotation center. Defaults to (0, 0).
- Returns:
matplotlib.axes.Axes: The axis with rotated elements.
Note
This transformation affects the visual rendering of the axis elements but does not modify the underlying data.
Ensure that the input axis contains elements like lines or images for the transformation to have an effect.
The function works with both line plots and images added to the Matplotlib axis.
- Example:
>>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots() >>> ax.plot([0, 1], [0, 1], label="Line") >>> rotate_axes(ax, angle=45, center=(0.5, 0.5)) >>> plt.show()
- ShockOscillationAnalysis.preview.visualize_shock_angles(shock_deg: list[float], avg_ang_glob: float, std_mid_Avg: float, output_directory: str = '') None
Plot a histogram of shock angles and overlay statistical indicators.
- Parameters:
shock_deg (list[float]): List of shock angles in degrees.
avg_ang_glob (float): Global average of the shock angles.
std_mid_Avg (float): Standard deviation of the shock angles.
- output_directory (str, optional): Directory to save the plot.
If empty, the plot is not saved.
- Returns:
None
ShockOscillationAnalysis.shocktracking module
Created on Fri Dec 1 15:27:54 2023
@author: Ahmed H. Hanfy
- ShockOscillationAnalysis.shocktracking.ShockTraking(SnapshotSlice: ndarray, LastShockLoc: int = -1, Plot: bool = False, count: int = -1, Alpha: float = 0.3, log_dirc: str = '')
Process a given slice to track shock waves and determine the shock location.
- Parameters:
SnapshotSlice (numpy.ndarray): A slice of the image to process.
LastShockLoc (int, optional): The location of the last shock. Default is -1.
Plot (bool, optional): Whether to plot the slice illumination values with locations and average line. Default is False.
count (int, optional): Counter for plotting. Default is -1.
log_dirc (str): log file directory.
- Returns:
- tuple: A tuple containing:
minLoc (float): The determined location of the shock wave.
certainLoc (bool): True if the shock location is certain, False otherwise.
reason (str): A string providing the reason for uncertainty if certainLoc is False.
- Example:
>>> instance = SOA(f) >>> result = instance.ShockTraking(SnapshotSlice, LastShockLoc=10, Plot=True, count=1) >>> print(result)
Note
The function processes the illumination values of a given image slice to track shock waves.
It returns the determined shock location, certainty status, and a reason for uncertainty.
ShockOscillationAnalysis.shocktrackingoptimized module
Created on Thu Jan 11 08:23:35 2024
@author: Ahmed H. Hanfy
- ShockOscillationAnalysis.shocktrackingoptimized.ShockTraking(SnapshotSlice, LastShockLoc=-1, Plot=False, count=-1, alpha=0.3)
Process a given slice to track shock waves and determine the shock location.
- Parameters:
SnapshotSlice (numpy.ndarray): A slice of the image to process.
LastShockLoc (int, optional): The location of the last shock. Default is -1.
Plot (bool, optional): Whether to plot the slice illumination values with locations and average line. Default is False.
count (int, optional): Counter for plotting. Default is -1.
- Returns:
- tuple: A tuple containing:
minLoc (float): The determined location of the shock wave.
certainLoc (bool): True if the shock location is certain, False otherwise.
reason (str): A string providing the reason for uncertainty if certainLoc is False.
- Example:
>>> instance = SOA(f) >>> result = instance.ShockTraking(SnapshotSlice, LastShockLoc=10, Plot=True, count=1) >>> print(result)
Important
this function is still under testing
- ShockOscillationAnalysis.shocktrackingoptimized.findlocalminimums(Reference, slice_pixels, plot=False, ax=[], alpha=0, Last_Loc=-1)
Find local minimums in a given slice of pixels.
- Parameters:
Reference (float): Reference value for comparison.
slice_pixels (list[float]): List of pixel values in the slice.
- Keyword Arguments:
plot (bool): Whether to plot the local minimums. Defaults to False.
ax (matplotlib.axes.Axes): Axes object for plotting. Required if plot=True.
alpha (float): Threshold for considering a local minimum. Defaults to 0.
Last_Loc (int): Last location of the local minimum. Defaults to -1.
- Returns:
tuple: Tuple containing local minimums, areas, and axes object.
ShockOscillationAnalysis.support_func module
- ShockOscillationAnalysis.support_func.bg_manipulation(path: str, y_crop: tuple[int] = None, x_crop: tuple[int] = None, resize: tuple[int] = None, bg_rotate=0, n: int = -1, log_dirc: str = '') tuple
Perform background image manipulation including cropping, resizing, and rotation.
This function processes a set of background images by applying optional cropping, resizing, and rotation. The first image in the specified path is used for manipulation.
- Parameters:
path (str): File path pattern to locate background image files. Supports wildcards.
y_crop (tuple[int], optional): A tuple (y_min, y_max) defining the vertical cropping range. Defaults to the full height of the image.
x_crop (tuple[int], optional): A tuple (x_min, x_max) defining the horizontal cropping range. Defaults to the full width of the image.
resize (tuple[int], optional): A tuple (width, height) defining the new dimensions for resizing. Defaults to the dimensions after cropping.
bg_rotate (bool, optional): Whether to rotate the image 90 degrees clockwise. Defaults to 0 (no rotation).
n (int, optional): Number of images expected in the specified path. If -1, no specific count is enforced. Defaults to -1.
log_dirc (str): log file directory.
- Returns:
- tuple:
np.ndarray: The processed background image.
int: Number of background images found in the specified path.
Note
If the path does not contain any files, the function will print an error and return None.
If fewer files than expected are found, a warning message is displayed.
- Steps:
Verify the availability of files at the given path.
Load the first image from the sorted list of files.
Apply cropping based on the provided x_crop and y_crop parameters.
Resize the cropped image to the specified resize dimensions.
Optionally rotate the image by 90 degrees clockwise.
- Example:
>>> bg_img, n_images = bg_manipulation("path/to/images/*.png", y_crop=(50, 200), x_crop=(30, 150), resize=(100, 100), bg_rotate=True)
- ShockOscillationAnalysis.support_func.log_message(message: str, log_file_dirc: str = '') None
Logs a message to a specified file.
The function checks if the log file exists. If it doesn’t, the file is created. The message is then appended to the file along with a timestamp.
- Parameters:
message (str): The message string to be logged.
log_file_path (str): The path to the log file. Defaults to “application.log.txt”.