Base Classes

class opencsp.common.lib.cv.CacheableImage.CacheableImage(array: ndarray | None = None, cache_path: str | None = None, source_path: str | None = None)

Bases: object

An image container that allows for caching an image when the image data isn’t in use, or for retrieval of an image from the cached file when the data is in use.

The intended use for this class is to reduce memory usage by caching images to disk while not in use. Therefore, there is an inherent priority order for the data that is returned from various methods:

  1. in-memory array

  2. numpy cache file

  3. image source file

Sources

Only one of the inputs (array, cache_path, source_path) are required in the constructor. In fact, there is a method from_single_source() that tries to guess which input is being provided. The “array” parameter should be the raw image data, the cache_path should be a string to a .npy file, and the source_path should be a string to an image file. Note that the cache_path file doesn’t need to exist yet, but can instead be an indicator for where to cache the image to.

The following table determines how images are retrieved based on the given parameters ([X] = given and file exists, [X] = given and file doesn’t exist, * = any):

array

cache_p

source_p

retrieval method

X

array (cache_path after cacheing, a temporary cache_path will be assigned)

X

X

*

array (cache_path after cacheing, array contents will then be ignored)

X

[X]

array (cache_path after cacheing, array contents will be saved to cache_path)

X

[X]

X

array (source_path after cacheing, array contents will then be ignored)

X

X

array (source_path after cacheing, array contents will then be ignored)

X

[X]

array (cache_path after cacheing, array contents will be saved to cache_path)

X

*

cache_path

[X]

X

source_path

X

source_path

In addition, the following cases will raise a FileNotFoundError during the __init__ method():

array

cache_p

source_p

[X]

[X]

sys.getsizeof

This class overrides the default __sizeof__ dunder method, meaning that the size returned by sys.getsizeof(cacheable_image) is not just the size of all variables tracked by the instance. Rather, the size of the Numpy array and Pillow image are returned. This metric better represents the memory-conserving use case that is intended for this class.

__sizeof__ returns close to 0 if the array and image attributes have been set to None (aka the cache() method has been executed). Note that this does not depend on the state of the garbage collector, which might not actually free the memory for some time after it is no longer being tracked by this class. An attempt at freeing the memory can be done immediately with gc.collect() but the results of this are going to be implementation specific.

The size of the source path, image path, and all other attributes are not included in the return value of __sizeof__. This decision was made for simplicity. Also the additional memory has very little impact. For example a 256 character path uses ~0.013% as much memory as a 1920x1080 monochrome image.

__init__(array: ndarray | None = None, cache_path: str | None = None, source_path: str | None = None)
Parameters:
  • array (np.ndarray, optional) – The image, as it exists in memory. Should be compatible with image_tools.numpy_to_image().

  • cache_path (str, optional) – Where to find and/or save the cached version of the image. Should be a numpy (.npy) file.

  • source_path (str, optional) – The source file for the image (an image file, for example jpg or png). If provided, then this file will be used as the backing cache instead of creating a new cache file.

classmethod all_cacheable_images_size()

The number of bytes of system memory used by all cacheable images for in-memory numpy arrays and in-memory Pillow images.

cache(cache_path: str | None = None)

Stores this instance to the cache and releases the handle to the in-memory image. Note that the memory might not be abailable for garbage collection, if there are other parts of the code that still have references to the in-memory image or array.

Parameters:

cache_path (str, optional) – The cache path/name.ext to use for storing this image, in case this image doesn’t already have a cache path. Can be None if a new cache file isn’t needed (the source image file is accessible or this instance has been cached before). By default None

static cache_images_to_disk_as_necessary(memory_limit_bytes: int, tmp_path_generator: Callable[[], str], log_level=10)

Check memory usage and convert images to files (aka file path strings) as necessary in order to reduce memory usage.

Note that due to the small amount of necessary memory used by each CacheableImage instance, all instances can be cached and still be above the memory_limit_bytes threshold. This can happen either when memory_limit_bytes is sufficiently small, or the number of live CacheableImages is sufficiently large. In these cases, this method may not be able to lower the amount of memory in use.

Parameters:
  • memory_limit_bytes (int) – The total number of bytes of memory that all CacheableImages are allowed to use for their in-memory arrays and images, in sum. Note that each CachableImage instance will still use some small amount of memory even after it has been cached.

  • tmp_path_generator (Callable[[], str]) – A function that returns a path/name.ext for a file that does not exist yet. This file will be used to save the numpy array out to.

  • log_level (int, optional) – The level to print out status messages to, including the amount of memory in use before and after caching images. By default lt.log.DEBUG.

classmethod from_single_source(array_or_path: ndarray | str | CacheableImage | Image) CacheableImage

Generates a CacheableImage from the given numpy array, numpy ‘.npy’ file, or image file.

static lru(deregister=True) CacheableImage | None

Returns the least recently used cacheable instance, where “use” is counted every time the image is loaded from cache.

If deregister is true, then the returned instance is moved from the “active” list to the “inactive” list of cacheable images. This is useful when we anticipate that the returned instance isn’t going to be used for a while, such as from the method cache_images_to_disk_as_necessary().

This does not load any cached data from disk.

save_image(image_path_name_ext: str)

Saves this image as an image file to the given file. This method is best used when an image is intended to be kept after a computation, in which case the newly saved image file can be the on-disk reference instead of an on-disk cache file.

Note: this replaces the internal reference to source_path, if any, with the newly given path. It is therefore suggested to not use this method unless you are using this class as part of an end-use application, in order to avoid unintended side effects.

Parameters:

image_path_name_ext (str) – The file path/name.ext to save to. For example “image.png”.

to_image() Image

Converts the numpy array representation of this image into a Pillow Image class and returns the converted value.

validate_cache_path(cache_path: str | None, caller_name: str)

Verifies that the cache_path, if set, ends with “.npy”. Raises a ValueError otherwise.

Parameters:
  • cache_path (str | None) – The path/name.ext to save this image to, as a numpy array. For example ft.join(orp.opencsp_scratch_dir(), “/OpenCSP/tmp001.npy”).

  • caller_name (str) – Name of the calling method. This is used as part of the generated error message.

validate_source_path(source_path: str | None, caller_name: str)

Ensures that the given source_path has one of the readable file extensions, or is None.

property cache_path: str | None

The path/name.ext to the cached numpy array.

property nparray: ndarray[Any, dtype[int64]] | None

The data for this CacheableImage, as a numpy array. This is the default internal representation of data for this class.

property source_path: str | None

The path/name.ext to the source image file.

class opencsp.common.lib.cv.OpticalFlow.OpticalFlow(frame1_dir: str, frame1_name_ext: str, frame2_dir: str, frame2_name_ext: str, grayscale_normalization: Callable[[ndarray], ndarray] | None = None, prev_flow=None, pyr_scale=0.5, levels=5, dense_winsize=15, iterations=3, poly_n=5, poly_sigma=1.2, dense_flags=0, cache=False)

Bases: object

A class for computing optical flow between two images using OpenCV.

This class wraps around OpenCV’s optical flow functions, providing functionality to compute dense optical flow and manage caching of results.

__init__(frame1_dir: str, frame1_name_ext: str, frame2_dir: str, frame2_name_ext: str, grayscale_normalization: Callable[[ndarray], ndarray] | None = None, prev_flow=None, pyr_scale=0.5, levels=5, dense_winsize=15, iterations=3, poly_n=5, poly_sigma=1.2, dense_flags=0, cache=False)

Wrapper class around cv::calcOpticalFlowFarneback (and also cv::calcOpticalFlowPyrLK, eventually).

Note

opencsp is not compatible with the multiprocessing library on Linux. Typical error message::

“global /io/opencv/modules/core/src/parallel_impl.cpp (240) WorkerThread 6: Can’t spawn new thread: res = 11”

This is due to some sort of bug with how multiprocessing processes and OpenCV threads interact. Possible solutions: - use concurrent.futures.ThreadPoolExecutor - Loky multiprocessing https://github.com/joblib/loky

Parameters:
  • frame1_dir (str) – Directory for frame1.

  • frame1_name_ext (str) – First input image, which will be the reference point for the flow.

  • frame2_dir (str) – Directory for frame2.

  • frame2_name_ext (str) – Second input image, to compare to the first.

  • grayscale_normalization (Callable[[np.ndarray], np.ndarray], optional) – A function for normalizing grayscale images (default is None).

  • prev_flow (optional) – Previous flow calculations to make computation faster. (default is None).

  • pyr_scale (float, optional) – Parameter specifying the image scale (<1) to build pyramids for each image; pyr_scale=0.5 means a classical pyramid, where each next layer is twice smaller than the previous one. (default is 0.5).

  • levels (int, optional) – Number of pyramid layers including the initial image; levels=1 means that no extra layers are created and only the original images are used. (default is 1).

  • dense_winsize (int, optional) – Averaging window size; larger values increase the algorithm’s robustness to image noise and give more chances for fast motion detection, but yield a more blurred motion field. (default is 15).

  • iterations (int, optional) – Number of iterations the algorithm does at each pyramid level. (default is 3).

  • poly_n (int, optional) – Size of the pixel neighborhood used to find polynomial expansion in each pixel; larger values mean that the image will be approximated with smoother surfaces, yielding a more robust algorithm and more blurred motion field, typically poly_n = 5 or 7. (default is 5.)

  • poly_sigma (float, optional) – Standard deviation of the Gaussian that is used to smooth derivatives used as a basis for the polynomial expansion; for poly_n=5, you can set poly_sigma=1.1, for poly_n=7, a good value would be poly_sigma=1.5. (default is 1.2).

  • dense_flags (int, optional) –

    Operation flags that can be a combination of the following:
    • OPTFLOW_USE_INITIAL_FLOW uses the input flow as an initial flow approximation.

    • OPTFLOW_FARNEBACK_GAUSSIAN uses the Gaussian winsize×winsize filter instead of a box filter of the same size for optical flow estimation; usually, this option gives more accurate flow than with a box filter, at the cost of lower speed; normally, winsize for a Gaussian window should be set to a larger value to achieve the same level of robustness. (default is 0).

  • cache (bool, optional) – If True, then pickle the results from the previous 5 computations and save them in the user’s home directory. If False, then don’t save them. Defaults to False. The cache option should not be used in production runs. I (BGB) use it for rapid development. It will error when used while running in production (aka on solo). (default is False)

clear_cache()

Clears the cache directory by deleting cached files.

This method removes any cached optical flow data stored in the cache directory.

Return type:

None

dense() tuple[ndarray, ndarray]

Computes the optical flow between two images on a pixel-by-pixel basis using Gunnar Farneback’s algorithm.

This method calculates the dense optical flow and returns the magnitude and angle of the flow.

Returns:

  • self.mag (np.ndarray) – The magnitude of the flow per pixel (units are in pixels).

  • self.ang (np.ndarray) – The direction of the flow per pixel (units are in radians, 0 to the right, positive counter-clockwise).

Notes

Uses the Gunnar Farneback’s algorithm: https://docs.opencv.org/3.4/dc/d6b/group__video__track.html#ga5d10ebbd59fe09c5f650289ec0ece5af

draw_flow_angle_reference()

Generates and displays a reference image for optical flow angles.

This method creates a circular reference image that visualizes the angles of optical flow with corresponding colors. The image is displayed with angle labels at key positions.

Return type:

None

classmethod from_file(dir: str, name_ext: str, error_on_not_exist=True)

Creates an instance of the class by loading magnitude and angle matrices from a file generated from the save() method.

Parameters:
  • dir (str) – The directory where the file is located.

  • name_ext (str) – The name of the file to load.

  • error_on_not_exist (bool, optional) – If True, raises an error if the file does not exist. Defaults to True.

Returns:

An instance of the class populated with data from the file.

Return type:

OpticalFlow

static get_save_file_name_ext(frame1_name_maybe_ext: str)

Generates the file name used to save the results from the flow analysis.

Parameters:

frame1_name_maybe_ext (str) – The base name of the frame, which may include an extension.

Returns:

The generated file name for saving optical flow results.

Return type:

str

limit_by_angle(lower: float, upper: float, keep='inside')

Sets any angles not in the specified range (and the corresponding magnitudes) to 0.

This method is similar to limit_by_magnitude, but it operates on the angle values instead.

Parameters:
  • lower (float) – The bottom of the range of angles to include.

  • upper (float) – The top of the range of angles to include.

  • keep (str, optional) – Either “inside” or “outside”. If “inside”, then values < lower or > upper will be set to 0. If “outside”, then values > lower and < upper will be set to 0 (default is “inside”).

Returns:

The indices that were set to 0.

Return type:

np.ndarray

limit_by_magnitude(lower: float, upper: float, keep='inside')

Sets any magnitudes not in the specified range (and the corresponding angles) to 0.

Once applied, you can run the dense() method again to recover the original values.

Parameters:
  • lower (float) – The bottom of the range of values to include.

  • upper (float) – The top of the range of values to include.

  • keep (str, optional) – Either “inside” or “outside”. If “inside”, then values < lower or > upper will be set to 0. If “outside”, then values > lower and < upper will be set to 0 (default is “inside”).

Returns:

The indices that were set to 0.

Return type:

np.ndarray

load(dir: str, name_ext: str = '', error_on_not_exist=True)

Loads the magnitude and angle matrices from the specified file into this instance.

Parameters:
  • dir (str) – The directory where the file is located.

  • name_ext (str, optional) – The name of the file to load. Defaults to the output of _default_save_file_name_ext().

  • error_on_not_exist (bool, optional) – If True, raises an error if the file does not exist. Defaults to True.

Returns:

A tuple containing the magnitude and angle matrices as from the dense() method, or (None, None) if the file does not exist.

Return type:

tuple[np.ndarray, np.ndarray]

save(dir: str, name_ext='', overwrite=False)

Saves the magnitude and angle matrices computed in the dense() method to the specified file.

Note

This method saves the matrices exactly as they were computed in dense(), without applying any limits from limit_by_magnitude or limit_by_angle.

Parameters:
  • dir (str) – The directory where the file will be saved.

  • name_ext (str, optional) – The file name to save to. Defaults to the output of get_save_file_name_ext().

  • overwrite (bool, optional) – If True, overwrites any existing file. Defaults to False.

Returns:

saved_path_name_ext – The full path of the saved file.

Return type:

str

Raises:

RuntimeError – If the matrices do not exist or if the file already exists and overwrite is False.

to_img(mag_render_clip: tuple[float, float] | None = None)

Converts the flow to an image by mapping the magnitude of movement to value/intensity and the angle of movement to hue.

The mapping of angles to hues is as follows:
  • Up: green

  • Down: red

  • Left: blue

  • Right: yellow

Note

This method must be called after dense() has been executed.

Parameters:

mag_render_clip (tuple[float, float], optional) – If provided, clips the rendered magnitude to this range (low -> 0, high -> 255). Defaults to None.

Returns:

The resulting image, which can be passed to View3D.draw_image (row major, RGB color channels).

Return type:

np.ndarray

Raises:

RuntimeError – If dense() hasn’t been executed yet.

ang: ndarray

XY Matrix. The OpenCSP version of the angle matrix, where each value corresponds to a pixel in frame1 and represents the angle that the pixel moved in to frame2 (radians, 0 to the right, positive counter-clockwise).

mag: ndarray

XY Matrix. The OpenCSP version of the magnitude matrix, where each value corresponds to a pixel in frame1 and represents the number of pixels that pixel has moved by frame2.

Utility Functions

image_filters

A collection of functions that operate on images to facilitate computer vision. Each filter accepts at least one image, and returns at least one image, where the input and output image have the same shape and data type. In addition, filters may accept or return additional argument or values.

For reshapers that filter images without any guarantee of maintaining shape or type, see image_reshapers.py.

opencsp.common.lib.cv.image_filters.percentile_filter(image: ndarray, percentile: int = 50, filter_shape: int | tuple = 3) ndarray

Finds the hotest pixel at the given percentile within a neighborhood of the given filter_shape. Can also be used as a minimum, median, or maximum filter by setting percentile to 0, 50, or 100, accordingly.

This is the same as a sliding window function for capturing the percentile pixel within the window. For example:

a = np.array([ [1, 2, 3, 2, 1],
               [2, 3, 4, 3, 2],
               [3, 4, 5, 4, 3],
               [2, 3, 4, 3, 2],
               [1, 2, 3, 2, 1] ])

results = percentile_filter(a, percentile=0)
# result:
# array([ [1, 1, 2, 1, 1],
#         [1, 1, 2, 1, 1],
#         [2, 2, 3, 2, 2],
#         [1, 1, 2, 1, 1],
#         [1, 1, 2, 1, 1] ])

results = percentile_filter(a, percentile=100)
# result:
# array([ [3, 4, 4, 4, 3],
#         [4, 5, 5, 5, 4],
#         [4, 5, 5, 5, 4],
#         [4, 5, 5, 5, 4],
#         [3, 4, 4, 4, 3] ])
Parameters:
  • image (np.ndarray) – The image to be filtered

  • percentile (int, optional) – The percentile pixel of the neighborhood to capture, by default 50

  • filter_shape (int | tuple, optional) – The width and height (and depth etc) of the neighborhood to apply.

Returns:

filtered_image – The resulting image with the same shape and type as the input image.

Return type:

np.ndarray

image_reshapers

A collection of functions that operate on images to facilitate computer vision. Each function accepts at least one image, and returns at least one image, but makes no guarantees that the output image has either the same shape or data type.

For filters that don’t modify the image shape or data type, see image_filters.py.

opencsp.common.lib.cv.image_reshapers.false_color_reshaper(from_image: ndarray, input_max_value: int = 255, map_name: str = 'jet', map_type: Literal['large', 'human'] = 'human') ndarray

Updates the primary image to use the jet color map plus black and white (black->blue->cyan->green->yellow->red->white).

This larger version of the opencv color map can represent either 1020 or 1530 different grayscale colors (compared to 256 colors with opencv.applyColorMap()). However, this takes ~0.28 seconds for a 1626 x 1236 pixel image.

Parameters:
  • from_image (np.ndarray) – The image to convert to false color. Should be grayscale (aka from_image.ndim == 2).

  • input_max_value (int) – The value to map to the maximum of the color range.

  • map_name (str, optional) – The color map to use. Currently just ‘jet’ is implemented.

  • map_type (str, optional) – Whether to use the full map space ‘large’ or a smaller map space that is easier to distinguish ‘human’.

Returns:

to_image – An image with the same width and height as the input image, but with a third dimension for color. The dtype will be from_image.dtype.

Return type:

np.ndarray

Fiducials

class opencsp.common.lib.cv.fiducials.AbstractFiducials.AbstractFiducials(style: RenderControlPointSeq | None = None, pixels_to_meters: Callable[[Pxy], Vxyz] | None = None)

Bases: ABC

A collection of markers (such as an ArUco board) that is used to orient the camera relative to observed objects in the scene. It is suggested that each implementing class be paired with a complementary locator method or opencsp.common.lib.cv.spot_analysis.image_processor.AbstractSpotAnalysisImageProcessor.

__init__(style: RenderControlPointSeq | None = None, pixels_to_meters: Callable[[Pxy], Vxyz] | None = None)

Initializes the AbstractFiducials with a specified rendering style and pixel-to-meter conversion function.

Parameters:
  • style (rcps.RenderControlPointSeq, optional) – How to render this fiducial when using the default render_to_plot() method. Defaults to rcps.default().

  • pixels_to_meters (Callable[[p2.Pxy], v3.Vxyz], optional) – Conversion function to get the physical point in space for the given x/y position information. Used in the default self.scale implementation. A good implementation of this function will correct for many factors such as relative camera position and camera distortion. For extreme accuracy, this will also account for non-uniformity in the target surface. Defaults to a simple 1 meter per pixel model.

abstract get_bounding_box(index=0) RegionXY

Get the X/Y bounding box of this instance, in pixels.

Parameters:

index (int, optional) – The index of the fiducial for which to retrieve the bounding box, for fiducials that have more than one bounding box. Defaults to 0.

Returns:

The bounding box of the fiducial.

Return type:

reg.RegionXY

render(axes: Axes | None = None)

Renders this fiducial to the active matplotlib.pyplot plot.

The default implementation uses plt.scatter().

Parameters:

axes (matplotlib.axes.Axes, optional) – The plot to render to. Uses the active plot if None. Defaults to None.

render_to_image(image: ndarray) ndarray

Renders this fiducial to a new image on top of the given image.

The default implementation creates a new matplotlib plot, and then renders to it with self.render().

Parameters:

image (np.ndarray) – The original image to which the fiducial will be rendered.

Returns:

The updated image with the fiducial rendered on top.

Return type:

np.ndarray

Raises:

Exception – If an error occurs during the rendering process.

abstract property origin: Pxy

Get the origin point(s) of this instance, in pixels.

Returns:

The origin point(s) of the fiducial.

Return type:

p2.Pxy

abstract property rotation: Rotation

Get the pointing of the normal vector(s) of this instance.

This is relative to the camera’s reference frame, where x is positive to the right, y is positive down, and z is positive in (away from the camera)

Returns:

The rotation of the fiducial relative to the camera’s reference frame.

Return type:

scipy.spatial.transform.Rotation

Notes

This can be used to describe the forward transformation from the camera’s perspective. For example, an ArUco marker whose origin is in the center of the image and is facing towards the camera could have the rotation defined as:

Rotation.from_euler('y', np.pi)

If that same ArUco marker was also placed upside down, then its rotation could be defined as:

Rotation.from_euler(
    'yz',
    [[np.pi, 0],
    [0,     np.pi]]
)

Note that this just describes rotation, and not the translation. We call the rotation and translation together the orientation.

property scale: list[float]

Get the scale(s) of this fiducial, in meters, relative to its longest axis.

This value, together with the size, can potentially be used to determine the distance and rotation of the fiducial relative to the camera.

Returns:

The scales of the fiducial in meters.

Return type:

list[float]

abstract property size: list[float]

Get the scale(s) of this fiducial, in pixels, relative to its longest axis.

As an example, if the fiducial is a square QR-code and is oriented tangent to the camera, then the scale will be the number of pixels from one corner to the other.

Returns:

The sizes of the fiducial in pixels.

Return type:

list[float]

class opencsp.common.lib.cv.fiducials.BcsFiducial.BcsFiducial(origin_px: Pxy, radius_px: float, style: RenderControlBcs | None = None, pixels_to_meters: float = 0.1)

Bases: AbstractFiducials

Fiducial for indicating where the BCS target is in an image.

__init__(origin_px: Pxy, radius_px: float, style: RenderControlBcs | None = None, pixels_to_meters: float = 0.1)

Initializes the BcsFiducial with the specified origin, radius, style, and pixel-to-meter conversion.

Parameters:
  • origin_px (p2.Pxy) – The center point of the BCS target, in pixels.

  • radius_px (float) – The radius of the BCS target, in pixels.

  • style (rcb.RenderControlBcs, optional) – The rendering style for the fiducial. Defaults to None.

  • pixels_to_meters (float, optional) – A conversion factor for how many meters a pixel represents, for use in scale(). Defaults to 0.1.

get_bounding_box(index=0) RegionXY

Get the bounding box of the BCS target.

Parameters:

index (int, optional) – Ignored for BcsFiducials.

Returns:

The bounding box as a RegionXY object.

Return type:

reg.RegionXY

Notes

The bounding box is calculated based on the origin and radius of the BCS target.

property origin: Pxy

Get the origin of the BCS fiducial.

Returns:

The center point of the BCS target in pixels.

Return type:

p2.Pxy

property rotation: Rotation

Get the rotation of the BCS fiducial.

Raises:

NotImplementedError – Rotation is not yet implemented for BcsFiducial.

property scale: list[float]

Get the scale of the BCS fiducial.

Returns:

A list containing a single value: the size of the BCS target, in meters.

Return type:

list[float]

property size: list[float]

Get the size of the BCS fiducial.

Returns:

A list containing a single value: the diameter of the BCS target.

Return type:

list[float]

class opencsp.common.lib.cv.fiducials.PointFiducials.PointFiducials(style: RenderControlPointSeq | None = None, points: Pxy | None = None)

Bases: AbstractFiducials

A collection of pixel locations where points of interest are located in an image.

__init__(style: RenderControlPointSeq | None = None, points: Pxy | None = None)

Initializes the PointFiducials with a specified style and points.

Parameters:
  • style (rcps.RenderControlPointSeq, optional) – The rendering style for the control points. Defaults to None.

  • points (p2.Pxy, optional) – The pixel locations of the points of interest. Defaults to None.

get_bounding_box(index=0) RegionXY

Get the bounding box for a specific point by index.

Parameters:

index (int, optional) – The index of the point for which to retrieve the bounding box. Defaults to 0.

Returns:

The bounding box as a RegionXY object.

Return type:

reg.RegionXY

Notes

This method is untested and may require validation.

property origin: Pxy

Get the origin of the fiducials.

Returns:

The pixel locations of the points of interest.

Return type:

p2.Pxy

property rotation: Rotation

Get the rotation of the fiducials.

Raises:

NotImplementedError – If the orientation is not yet implemented for this class.

property scale: list[float]

Get the scale of the fiducials.

Returns:

A list of scales for each point. The default implementation for PointFiducials returns a list of zeros.

Return type:

list[float]

Notes

This property is untested and may require validation.

property size: list[float]

Get the size of the fiducials.

Returns:

A list of sizes for each point. The default implementation for PointFiducials returns a list of zeros.

Return type:

list[float]

Notes

This property is untested and may require validation.

Annotations

class opencsp.common.lib.cv.annotations.AbstractAnnotations.AbstractAnnotations(style: RenderControlPointSeq | None = None, pixels_to_meters: Callable[[Pxy], Vxyz] | None = None)

Bases: AbstractFiducials

Annotations are applied to images to mark specific points of interest. Some examples of annotations might include:

  • The hotspot in a beam where light is the brightest

  • The power envelope for 90% of the light of a beam

  • Distances between two pixels

  • Measurement overlays

This class has all the same properties as Fiducials.

class opencsp.common.lib.cv.annotations.HotspotAnnotation.HotspotAnnotation(style: RenderControlPointSeq | None = None, point: Pxy | None = None)

Bases: PointAnnotations

A class representing a hotspot annotation, likely created from a opencsp.common.lib.cv.spot_analysis.image_processor.HotspotImageProcessor instance.

The hotspot is the overall hottest location in an image, when accounting for the surrounding area. It may be the different from the centroid location or the single hottest pixel location.

This class extends the PointAnnotations class to create a specific type of annotation that represents a hotspot, which can be rendered with a specific style and point location.

style

The rendering style of the hotspot annotation.

Type:

rcps.RenderControlPointSeq

point

The point location of the hotspot annotation.

Type:

p2.Pxy

__init__(style: RenderControlPointSeq | None = None, point: Pxy | None = None)
Parameters:
  • style (rcps.RenderControlPointSeq, optional) – The rendering style for the hotspot annotation. If not provided, a default style with blue color, ‘x’ marker, and a marker size of 1 will be used.

  • point (p2.Pxy, optional) – The point location of the hotspot annotation, represented as a Pxy object. If not provided, the annotation will not have a specific point location.

Examples

>>> processor = HotspotImageProcessor(desired_shape=(30, 30))
>>> input_image = CacheableImage.from_single_source("C:/path/to/image.png")
>>> input_operable = SpotAnalysisOperable(input_image)
>>> result = processor.process_operable(input_operable, is_last=True)[0]
>>> hotspot = result.get_fiducials_by_type(HotspotAnnotation)[0]
>>> lt.info(str(type(hotspot)))
<class 'opencsp.common.lib.cv.annotations.HotspotAnnotation.HotspotAnnotation'>
>>> lt.info(str(hotspot.origin))
2D Point:
array([[2517.],
       [2733.]])
class opencsp.common.lib.cv.annotations.PointAnnotations.PointAnnotations(style: RenderControlPointSeq | None = None, points: Pxy | None = None)

Bases: PointFiducials, AbstractAnnotations

A class representing point annotations.

An example of this class is opencsp.common.lib.cv.annotations.HotspotAnnotation.HotspotAnnotation.

This class extends both PointFiducials and AbstractAnnotations to provide functionality for managing and rendering point annotations, which can be used to mark specific locations in a visual representation.