optibeam package

Submodules

optibeam.camera module

class optibeam.camera.BaslerCamera(camera: InstantCamera, params: dict = {})[source]

Bases: Camera

Class representing a Basler camera. https://docs.baslerweb.com/precision-time-protocol#checking-the-status-of-the-ptp-clock-synchronization

capture() Generator[ndarray, None, None][source]

Captures an image using the camera.

Returns:

An array representing the captured image.

Return type:

np.ndarray

close()[source]

Closes the camera after capturing images. release resources.

demo_video()[source]
enable_ptp() None[source]

Enables the Precision Time Protocol (PTP) on the camera. (if supported)

get_info() dict[source]

Retrieves information about the Basler camera.

Returns:

A dictionary containing camera details such as model, serial number, etc.

Return type:

dict

open()[source]

Opens the camera for capturing images.

ptp_status() bool[source]

Checks the status of the Precision Time Protocol (PTP) on the camera.

Returns:

True if PTP is enabled, False otherwise.

Return type:

bool

set_camera_params(params: dict)[source]

Resets the camera parameters based on the input dictionary.

Parameters:

params (dict) – A dictionary containing camera parameter settings such as exposure, ISO, etc.

class optibeam.camera.Camera[source]

Bases: ABC

Abstract base class for a camera, providing a blueprint for camera operations.

abstract capture() ndarray[source]

Captures an image using the camera.

Returns:

An array representing the captured image.

Return type:

np.ndarray

abstract close() None[source]

Closes the camera after capturing images. release resources.

abstract enable_ptp() None[source]

Enables the Precision Time Protocol (PTP) on the camera. (if supported)

abstract get_info() dict[source]

Retrieves information about the camera.

Returns:

A dictionary containing camera details such as model, resolution, and other relevant parameters.

Return type:

dict

abstract open() None[source]

Opens the camera for capturing images.

abstract ptp_status() bool[source]

Checks the status of the Precision Time Protocol (PTP) on the camera.

Returns:

True if PTP is enabled, False otherwise.

Return type:

bool

abstract set_camera_params(params: dict)[source]

Resets the camera parameters based on the input dictionary.

Parameters:

params (dict) – A dictionary containing camera parameter settings such as exposure, ISO, etc.

class optibeam.camera.Synchronizer(cameras: List[Camera])[source]

Bases: object

Class to handle synchronization and simultaneous image capturing from multiple camera objects using PTP.

camera_registration()[source]
initialize_ptp()[source]

Initializes PTP on all cameras to synchronize them.

take_images()[source]
optibeam.camera.num_of_cameras_detected()[source]

Returns the detected number of cameras that connected to the computer

Returns:

The number of cameras detected.

Return type:

int

optibeam.dmd module

optibeam.evaluation module

optibeam.evaluation.beam_params(narray, normalize=True)[source]

Input: single channel narray image -> beam parameters (beam centroids, beam widths), normalized. Two 1D Gaussian fits are used. Output: dictionary object containing the beam parameters.

optibeam.evaluation.center_of_mass(narray)[source]
optibeam.evaluation.fit_2d_gaussian(image)[source]
optibeam.evaluation.fit_gaussian(x, y)[source]

Gaussian fit (Least Squares Fitting) https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html

optibeam.evaluation.gaussian(x, a, mu, sigma)[source]
optibeam.evaluation.gaussian_2d(xy, A, x0, y0, sigma_x, sigma_y)[source]
optibeam.evaluation.plot_gaussian_fit(image)[source]

Plot the horizontal and vertical histograms of the image, and the Gaussian fit. input: 2d numpy array representing the image output: None

optibeam.simulation module

class optibeam.simulation.CauchyDistribution(canvas: DynamicPatterns)[source]

Bases: Distribution

Class for generating a 2D Cauchy distribution.

class optibeam.simulation.Distribution(canvas: DynamicPatterns)[source]

Bases: ABC

Abstract class for defining the distribution of different beam patterns.

abstract update(*args, **kwargs)[source]

Update the distribution’s state.

property pattern: ndarray

Return the distribution’s current pattern.

class optibeam.simulation.DynamicPatterns(height: int = 128, width: int = 128)[source]

Bases: object

Class for generating and managing dynamic patterns on a 2D canvas. Focusing on image pattern generation only.

append(distribution)[source]

Append a distribution object to the list of distributions.

apply_distribution()[source]
clear_canvas()[source]
get_image(type='narray')[source]
plot_canvas(cmap='viridis', pause=0.01)[source]
transform(transformations: List[Callable[[ndarray], ndarray]])[source]

Apply a series of transformations on the final image (), not on the canvas.

update(*args, **kwargs)[source]

Update the canvas by updating all the distributions. Need distribution objects have the update method implemented.

property height
property width
class optibeam.simulation.GaussianDistribution(canvas: DynamicPatterns, mean_x: float = 0.5, mean_y: float = 0.5, std_x: float = 0.1, std_y: float = 0.1, x_velocity: float = 0, y_velocity: float = 0, speed_momentum: float = 0.9, rotation_radians: float = 0, rotation_velocity: float = 0, rotation_momentum: float = 0.95)[source]

Bases: Distribution

Class for generating a 2D Gaussian distribution.

change_distribution_params(vol_scale: float = 0.01, std_scale: float = 0.01, rot_scale: float = 0.01)[source]
generate_2d_gaussian() ndarray[source]

Generate a rotated 2D Gaussian distribution based on the current state of the distribution. The rotation is centered around the mean of the distribution.

update(*args, **kwargs)[source]

Update the distribution’s state.

class optibeam.simulation.MaxwellBoltzmannDistribution(canvas: DynamicPatterns)[source]

Bases: Distribution

Class for generating a 2D Maxwell-Boltzmann distribution.

optibeam.simulation.apply_transformation_matrix(image: ndarray, transformation_matrix: ndarray) ndarray[source]

Applies a 3x3 transformation matrix to a 2D numpy array image.

Args: - image (numpy.ndarray): The input image as a 2D numpy array. - transformation_matrix (numpy.ndarray): The 3x3 transformation matrix.

Returns: - numpy.ndarray: The transformed image.

optibeam.simulation.compile_transformation_matrix(image: ndarray, translate: tuple = (0, 0), radians: float = 0, scale_x: float = 1, scale_y: float = 1) ndarray[source]
optibeam.simulation.create_mosaic_image(size: int = 1024, n: int = 3) ndarray[source]
optibeam.simulation.macro_pixel(narray: ndarray, size: int = 8) ndarray[source]

Expand a 2D numpy array (image) to a macro pixel (size, size) array. e.g. If canvas is 64x64, and input size is 8, then it will return a 512x512 pixel matrix.

Parameters: - size: The size of the macro pixel.

Returns: - A 2D numpy array expanded image.

optibeam.simulation.pixel_value_remap(narray: ndarray, max_pixel_value: int = 255) ndarray[source]

Rescale the pixel values of the canvas to a new maximum value.

optibeam.simulation.transform_image(image, rotate=0, scale=1.0, translate=(0, 0), implementation='opencv')[source]

Transforms a 2D numpy array image according to the specified parameters. - rotate: Rotation angle in degrees (counterclockwise) - scale: Scaling factor - translate: Tuple (tx, ty) representing translation in pixels - implementation: Choice of implementation (‘opencv’ or ‘custom’)

optibeam.training module

class optibeam.training.Logger(log_dir, model=None, dataset=None, history=None, info='')[source]

Bases: object

Create folder and a log file in the specified directory, containing the experiment details (snapshot). After training, save the log content in the log file under the log directory.

log_parse()[source]
register_dataset()[source]
register_extra(extra_info)[source]
register_model()[source]
register_training()[source]
save()[source]
tf_model_summary()[source]
update()[source]
class optibeam.training.PlotPredictionImageCallback(x_data, y_data)[source]

Bases: Callback

Callback to plot the true and predicted images on a random validation image input: x_data (np.array, (n x m), speckle pattern), y_data (np.array, (p x q), beam image)

on_epoch_end(epoch, logs=None, title=['MMF Speckle Pattern (Input)', 'Original Beam Distribution (Ground Truth)', 'Reconstructed Image (Output)'])[source]

Called at the end of an epoch.

Subclasses should override for any actions to run. This function should only be called during TRAIN mode.

Parameters:
  • epoch – Integer, index of epoch.

  • logs – Dict, metric results for this training epoch, and for the validation epoch if validation is performed. Validation result keys are prefixed with val_. For training epoch, the values of the Model’s metrics are returned. Example: {‘loss’: 0.2, ‘accuracy’: 0.7}.

class optibeam.training.PlotPredictionParamsCallback(val_images, val_labels, val_beam_images)[source]

Bases: Callback

Callback to plot the true and predicted beam parameters on a random validation image input: val_images (np.array, (m, n)), val_labels (np.array, (l, 1), normalized), val_beam_image (np.array, (p, q))

on_epoch_begin(epoch, logs=None)[source]

Called at the start of an epoch.

Subclasses should override for any actions to run. This function should only be called during TRAIN mode.

Parameters:
  • epoch – Integer, index of epoch.

  • logs – Dict. Currently no data is passed to this argument for this method but that may change in the future.

optibeam.training.clean_tensor(narray)[source]

Discard some problematic images based on beam parameters calculation. In future, need to develop a better evaluation function (beam_params) to handle this properly?

optibeam.training.seperate_img(data)[source]

temp functions for split orignal beam image and speckle pattern for later callback function use assume data consists of both beam image and speckle pattern

optibeam.training.split_dataset(data, labels, proportion=(8, 1, 1))[source]

split dataset, Tensorflow only dimension: (n, 2, width, hight, channel), (n, beam parameters NO.)

optibeam.utils module

class optibeam.utils.ImageLoader(funcs)[source]

Bases: object

load(input)[source]

Automatically decide whether to load a single image or multiple images based on the input type.

load_image(image_path)[source]

Load an image from the specified path and apply the specified functions to the image sequentially.

load_images(image_paths)[source]

Load multiple images and return a dataset in numpy array format.

optibeam.utils.add_progress_bar(iterable_arg_index=0)[source]

Decorator to add a progress bar to the specified iterable argument of a function. Parameters: - iterable_arg_index (int): The index of the iterable argument in the function’s argument list.

optibeam.utils.apply_multiprocess(function)[source]

Decorator to apply multiprocess to a function that processes an iterable. Use multiprocess which is compatible with Jupyter notebook. Could select adding a progress indicator to the operation.

optibeam.utils.apply_multiprocessing(function)[source]

Decorator to apply multiprocessing to a function that processes an iterable. No progress indicator, can be used in the terminal.

optibeam.utils.combine_functions(functions)[source]

Combine a list of functions into a single function that processes data sequentially through each function in the list.

Parameters:

functions (list[callable]) – A list of functions, where each function has the same type of input and output.

Returns:

A combined function that is the composition of all the functions in the list. If the input list is empty, returns an identity function.

Return type:

callable

optibeam.utils.deprecated(reason)[source]

Decorator to mark a function as deprecated.

optibeam.utils.deprecated_class(reason)[source]

Decorator to mark a class as deprecated.

optibeam.utils.get_all_file_paths(dirs, types=['']) list[source]

Get all file paths in the specified directories with the specified file types. input: dirs (list of strings or string of the root of dataset folder), types (list of strings)

optibeam.utils.get_system_info()[source]

Get system information including the operating system, version, machine, processor, and Python version. Returns: dict: A dictionary containing the system information.

optibeam.utils.image_normalize(narray_img: array)[source]

Normalize the input image by scaling its pixel values to the range [0, 1]. Parameters: image (np.ndarray): A NumPy array representing the input image. Returns: np.ndarray: The normalized image.

optibeam.utils.is_jupyter()[source]

Check if Python is running in Jupyter (notebook or lab) or in a command line.

optibeam.utils.minmax_normalization(arr)[source]

Min-max normalization

optibeam.utils.preset_kwargs(**preset_kwargs)[source]

A decorator to preset keyword arguments of any function. The first argument of the function is assumed to be the input data, and the rest are considered keyword arguments for tuning or controlling the function’s behavior.

Parameters: - **preset_kwargs: Arbitrary keyword arguments that will be preset for the decorated function.

optibeam.utils.process_list_in_parallel(function, data_list)[source]
optibeam.utils.rgb_to_grayscale(narray_img: array)[source]

input: image in numpy array format output: grayscale image in numpy array format by averaging all the colors

optibeam.utils.scale_image(narray_img, scaling_factor)[source]

Scales an image by a given scaling factor.

Parameters: - image: ndarray, the input image to be scaled. - scaling_factor: float, the factor by which the image will be scaled.

Returns: - scaled_image: ndarray, the scaled image.

optibeam.utils.split_image(narray_img: array, select='') Tuple[array, array][source]

input: image in numpy array format output: two images, split in the middle horizontally

optibeam.utils.subtract_minimum(arr)[source]

Subtract the minimum value from each element in a 1D NumPy array. Parameters: arr (np.ndarray): A 1D numpy array. Returns: np.ndarray: The processed array with the minimum value subtracted from each element.

optibeam.visualization module

class optibeam.visualization.visualPCA(n_components=3)[source]

Bases: object

create_gif(save_to: str, start_angle=0, end_angle=89, nums=60, fps=30, reverse=True)[source]
fit(data: array)[source]
plot_2d()[source]
plot_3d()[source]
plot_to_memory(angle: int) BytesIO[source]
optibeam.visualization.img_2_params_evaluation(image, true_label, pred_label)[source]
optibeam.visualization.plot_narray(narray_img, channel=1)[source]

Plot a 2D NumPy array as an image. Parameters: narray_img (np.ndarray): A 2D NumPy array to plot as an image.

optibeam.visualization.plot_prediction_comparison(real: array, predicted: array, param_name='')[source]

Module contents