Skip to content

Pixels

siapy.entities.pixels

CoordinateInput module-attribute

CoordinateInput: TypeAlias = (
    PixelCoordinate | tuple[float, float] | Sequence[float]
)

HomogeneousCoordinate dataclass

HomogeneousCoordinate(
    X: str = "x", Y: str = "y", H: str = "h"
)

X class-attribute instance-attribute

X: str = 'x'

Y class-attribute instance-attribute

Y: str = 'y'

H class-attribute instance-attribute

H: str = 'h'

PixelCoordinate

Bases: NamedTuple

x instance-attribute

x: float

y instance-attribute

y: float

Pixels dataclass

Pixels(_data: DataFrame)

coords class-attribute

df property

df: DataFrame

from_iterable classmethod

from_iterable(
    iterable: Iterable[CoordinateInput],
) -> "Pixels"
Source code in siapy/entities/pixels.py
69
70
71
72
73
@classmethod
def from_iterable(cls, iterable: Iterable[CoordinateInput]) -> "Pixels":
    df = pd.DataFrame(iterable, columns=[cls.coords.X, cls.coords.Y])
    validate_pixel_input_dimensions(df)
    return cls(df)

load_from_parquet classmethod

load_from_parquet(filepath: str | Path) -> 'Pixels'
Source code in siapy/entities/pixels.py
75
76
77
78
79
@classmethod
def load_from_parquet(cls, filepath: str | Path) -> "Pixels":
    df = pd.read_parquet(filepath)
    validate_pixel_input_dimensions(df)
    return cls(df)

df_homogenious

df_homogenious() -> DataFrame
Source code in siapy/entities/pixels.py
85
86
87
88
def df_homogenious(self) -> pd.DataFrame:
    df_homo = self.df.copy()
    df_homo[self.coords.H] = 1
    return df_homo

x

x() -> 'pd.Series[float]'
Source code in siapy/entities/pixels.py
90
91
def x(self) -> "pd.Series[float]":
    return self.df[self.coords.X]

y

y() -> 'pd.Series[float]'
Source code in siapy/entities/pixels.py
93
94
def y(self) -> "pd.Series[float]":
    return self.df[self.coords.Y]

to_numpy

to_numpy() -> NDArray[floating[Any]]
Source code in siapy/entities/pixels.py
96
97
def to_numpy(self) -> NDArray[np.floating[Any]]:
    return self.df.to_numpy()

to_list

to_list() -> list[PixelCoordinate]
Source code in siapy/entities/pixels.py
 99
100
def to_list(self) -> list[PixelCoordinate]:
    return self.df.values.tolist()

save_to_parquet

save_to_parquet(filepath: str | Path) -> None
Source code in siapy/entities/pixels.py
102
103
def save_to_parquet(self, filepath: str | Path) -> None:
    self.df.to_parquet(filepath, index=True)

as_type

as_type(dtype: type) -> 'Pixels'
Source code in siapy/entities/pixels.py
105
106
107
108
109
def as_type(self, dtype: type) -> "Pixels":
    converted_df = self.df.copy()
    converted_df[self.coords.X] = converted_df[self.coords.X].astype(dtype)
    converted_df[self.coords.Y] = converted_df[self.coords.Y].astype(dtype)
    return Pixels(converted_df)

get_coordinate

get_coordinate(idx: int) -> PixelCoordinate
Source code in siapy/entities/pixels.py
111
112
113
def get_coordinate(self, idx: int) -> PixelCoordinate:
    row = self.df.iloc[idx]
    return PixelCoordinate(x=row[self.coords.X], y=row[self.coords.Y])

validate_pixel_input_dimensions

validate_pixel_input_dimensions(
    df: DataFrame | Series,
) -> None
Source code in siapy/entities/pixels.py
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
def validate_pixel_input_dimensions(df: pd.DataFrame | pd.Series) -> None:
    if isinstance(df, pd.Series):
        raise InvalidTypeError(
            input_value=df,
            allowed_types=pd.DataFrame,
            message="Expected a DataFrame, but got a Series.",
        )

    if df.empty:
        raise InvalidInputError(
            message="Input DataFrame is empty.",
            input_value=df,
        )

    if df.shape[1] != 2:
        raise InvalidInputError(
            message="Invalid input dimensions: expected 2 columns (x, y), got",
            input_value=df.shape[1],
        )

    if sorted(df.columns) != sorted([HomogeneousCoordinate.X, HomogeneousCoordinate.Y]):
        raise InvalidInputError(
            message=f"Invalid column names: expected ['{HomogeneousCoordinate.X}', '{HomogeneousCoordinate.Y}'], got",
            input_value=sorted(df.columns),
        )

validate_pixel_input

validate_pixel_input(
    input_data: Pixels
    | DataFrame
    | Iterable[CoordinateInput],
) -> Pixels

Validates and converts various input types to Pixels object.

Source code in siapy/entities/pixels.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
def validate_pixel_input(input_data: Pixels | pd.DataFrame | Iterable[CoordinateInput]) -> Pixels:
    """Validates and converts various input types to Pixels object."""
    try:
        if isinstance(input_data, Pixels):
            return input_data

        if isinstance(input_data, pd.DataFrame):
            validate_pixel_input_dimensions(input_data)
            return Pixels(input_data)

        if isinstance(input_data, np.ndarray):
            if input_data.ndim != 2 or input_data.shape[1] != 2:
                raise InvalidInputError(
                    input_value=input_data.shape,
                    message=f"NumPy array must be 2D with shape (n, 2), got shape {input_data.shape}",
                )
            return Pixels(pd.DataFrame(input_data, columns=[HomogeneousCoordinate.X, HomogeneousCoordinate.Y]))

        if isinstance(input_data, Iterable):
            return Pixels.from_iterable(input_data)  # type: ignore

        raise InvalidTypeError(
            input_value=input_data,
            allowed_types=(Pixels, pd.DataFrame, np.ndarray, Iterable),
            message=f"Unsupported input type: {type(input_data).__name__}",
        )

    except Exception as e:
        if isinstance(e, (InvalidTypeError, InvalidInputError)):
            raise

        raise InvalidInputError(
            input_value=input_data,
            message=f"Failed to convert input to Pixels: {str(e)}"
            f"\nExpected a Pixels instance or an iterable (e.g. list, np.array, tuple, pd.DataFrame)."
            f"\nThe input must contain 2D coordinates with x and y values.",
        )