garmentiq.landmark.derivation.utils

Geometric helpers used by the derivation functions.

  1"""Geometric helpers used by the derivation functions."""
  2import numpy as np
  3from typing import Tuple, Optional, List
  4
  5
  6def _calculate_line1_vector(
  7    p2_coord: Tuple[float, float], p3_coord: Tuple[float, float], direction: str
  8) -> Optional[Tuple[float, float]]:
  9    """
 10    Calculates the direction vector for Line 1 based on p2, p3, and direction.
 11
 12    Args:
 13        p2_coord (Tuple[float, float]): The (x, y) coordinates of the second point.
 14        p3_coord (Tuple[float, float]): The (x, y) coordinates of the third point.
 15        direction (str): The desired direction of Line 1 relative to the vector
 16            from `p2_coord` to `p3_coord`. Must be "parallel" or "perpendicular".
 17
 18    Returns:
 19        Optional[Tuple[float, float]]: The calculated direction vector (dx, dy)
 20            as a tuple of floats, or `None` if the direction is invalid or the
 21            vector (p3-p2) is a zero vector.
 22    """
 23    ref_dx = p3_coord[0] - p2_coord[0]
 24    ref_dy = p3_coord[1] - p2_coord[1]
 25
 26    if direction == "parallel":
 27        v1 = (ref_dx, ref_dy)
 28    elif direction == "perpendicular":
 29        v1 = (-ref_dy, ref_dx)
 30    else:
 31        print(
 32            f"Error: Invalid direction '{direction}'. Use 'parallel' or 'perpendicular'."
 33        )
 34        return None
 35
 36    # Check for zero vector
 37    if np.isclose(v1[0], 0) and np.isclose(v1[1], 0):
 38        print(
 39            f"Warning: Direction vector for Line 1 is zero (p2 and p3 likely coincide)."
 40        )
 41        # Decide if this should be a fatal error or handled downstream
 42        # Returning None signals an issue.
 43        return None
 44
 45    return v1
 46
 47
 48def _find_closest_point(
 49    points_list: List[Tuple[float, float]], target_point: Tuple[float, float]
 50) -> Optional[Tuple[float, float]]:
 51    """
 52    Finds the point in `points_list` that is closest (Euclidean distance) to `target_point`.
 53
 54    Args:
 55        points_list (List[Tuple[float, float]]): A list of 2D points (x, y) to search within.
 56        target_point (Tuple[float, float]): The reference point (x, y) to find the closest point to.
 57
 58    Returns:
 59        Optional[Tuple[float, float]]: The (x, y) coordinates of the closest point from
 60            `points_list` as a tuple of floats, or `None` if `points_list` is empty.
 61    """
 62    if not points_list:
 63        return None
 64
 65    points_np = np.array(points_list)
 66    target_np = np.array(target_point)
 67
 68    distances = np.linalg.norm(points_np - target_np, axis=1)
 69    closest_index = np.argmin(distances)
 70
 71    return tuple(points_np[closest_index])
 72
 73
 74def parse_derivation_args(deriv_dict, json_path, mask_path):
 75    """
 76    Parses a derivation dictionary to extract arguments for a derivation function.
 77
 78    This function is a helper for preparing arguments required by specific derivation
 79    functions (e.g., `derive_keypoint_coord`). It extracts parameters and adds fixed
 80    inputs like `json_path` and `mask_path`.
 81
 82    Args:
 83        deriv_dict (dict): A dictionary containing derivation parameters for a specific landmark.
 84        json_path (str): Path to the JSON file related to the image.
 85        mask_path (str): Path to the mask file related to the image.
 86
 87    Returns:
 88        dict: A dictionary of parsed arguments ready to be passed to a derivation function.
 89    """
 90    args = {}
 91    for k, v in deriv_dict.items():
 92        if k == "function":
 93            continue
 94        # p*_id should be ints, everything else leave as‐is
 95        if k.endswith("_id"):
 96            try:
 97                args[k] = int(v)
 98            except ValueError:
 99                # in case someone uses numbers not strictly digits
100                args[k] = int(float(v))
101        else:
102            args[k] = v
103    args["json_path"] = json_path
104    args["mask_path"] = mask_path
105    return args
106    return args
def parse_derivation_args(deriv_dict, json_path, mask_path):
 75def parse_derivation_args(deriv_dict, json_path, mask_path):
 76    """
 77    Parses a derivation dictionary to extract arguments for a derivation function.
 78
 79    This function is a helper for preparing arguments required by specific derivation
 80    functions (e.g., `derive_keypoint_coord`). It extracts parameters and adds fixed
 81    inputs like `json_path` and `mask_path`.
 82
 83    Args:
 84        deriv_dict (dict): A dictionary containing derivation parameters for a specific landmark.
 85        json_path (str): Path to the JSON file related to the image.
 86        mask_path (str): Path to the mask file related to the image.
 87
 88    Returns:
 89        dict: A dictionary of parsed arguments ready to be passed to a derivation function.
 90    """
 91    args = {}
 92    for k, v in deriv_dict.items():
 93        if k == "function":
 94            continue
 95        # p*_id should be ints, everything else leave as‐is
 96        if k.endswith("_id"):
 97            try:
 98                args[k] = int(v)
 99            except ValueError:
100                # in case someone uses numbers not strictly digits
101                args[k] = int(float(v))
102        else:
103            args[k] = v
104    args["json_path"] = json_path
105    args["mask_path"] = mask_path
106    return args
107    return args

Parses a derivation dictionary to extract arguments for a derivation function.

This function is a helper for preparing arguments required by specific derivation functions (e.g., derive_keypoint_coord). It extracts parameters and adds fixed inputs like json_path and mask_path.

Arguments:
  • deriv_dict (dict): A dictionary containing derivation parameters for a specific landmark.
  • json_path (str): Path to the JSON file related to the image.
  • mask_path (str): Path to the mask file related to the image.
Returns:

dict: A dictionary of parsed arguments ready to be passed to a derivation function.