Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Develop #159

Merged
merged 4 commits into from
Sep 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/api/core/exceptions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@

::: siapy.core.exceptions
1 change: 1 addition & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ nav:
- API Documentation:
- Core:
- Configs: api/core/configs.md
- Exceptions: api/core/exceptions.md
- Logger: api/core/logger.md
- Types: api/core/types.md
- Datasets:
Expand Down
2 changes: 1 addition & 1 deletion siapy/core/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

SpectralType = sp.io.envi.BilFile | sp.io.envi.BipFile | sp.io.envi.BsqFile
ImageType = SpectralImage | np.ndarray | Image
ImageSizeType = int | tuple[int, int]
ImageSizeType = int | tuple[int, ...]
ImageDataType = (
np.uint8
| np.int16
Expand Down
6 changes: 4 additions & 2 deletions siapy/entities/images.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Any, Iterable, Iterator
from typing import TYPE_CHECKING, Any, Iterable, Iterator, Sequence

import numpy as np
import spectral as sp
Expand Down Expand Up @@ -265,7 +265,9 @@ def to_subarray(self, pixels: "Pixels") -> np.ndarray:
image_arr_area[v_norm, u_norm, :] = image_arr[pixels.v(), pixels.u(), :]
return image_arr_area

def mean(self, axis: int | tuple[int] | None = None) -> float | np.ndarray:
def mean(
self, axis: int | tuple[int, ...] | Sequence[int] | None = None
) -> float | np.ndarray:
image_arr = self.to_numpy()
return np.nanmean(image_arr, axis=axis)

Expand Down
3 changes: 2 additions & 1 deletion siapy/entities/pixels.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from dataclasses import dataclass
from pathlib import Path
from typing import Annotated, ClassVar, Iterable, NamedTuple
from typing import Annotated, ClassVar, Iterable, NamedTuple, Sequence

import numpy as np
import pandas as pd
Expand Down Expand Up @@ -32,6 +32,7 @@ def from_iterable(
Annotated[int, "u coordinate on the image"],
Annotated[int, "v coordinate on the image"],
]
| Sequence[int]
],
) -> "Pixels":
df = pd.DataFrame(iterable, columns=[Pixels.coords.U, Pixels.coords.V])
Expand Down
20 changes: 18 additions & 2 deletions siapy/features/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,15 @@ def __init__(
feateng_steps: int = 2,
featsel_runs: int = 5,
max_gb: int | None = None,
transformations: list | tuple = ("1/", "exp", "log", "abs", "sqrt", "^2", "^3"),
transformations: list[str] | tuple[str, ...] = (
"1/",
"exp",
"log",
"abs",
"sqrt",
"^2",
"^3",
),
apply_pi_theorem: bool = True,
always_return_numpy: bool = False,
n_jobs: int = 1,
Expand Down Expand Up @@ -78,7 +86,15 @@ def __init__(
feateng_steps: int = 2,
featsel_runs: int = 5,
max_gb: int | None = None,
transformations: list | tuple = ("1/", "exp", "log", "abs", "sqrt", "^2", "^3"),
transformations: list[str] | tuple[str, ...] = (
"1/",
"exp",
"log",
"abs",
"sqrt",
"^2",
"^3",
),
apply_pi_theorem: bool = True,
always_return_numpy: bool = False,
n_jobs: int = 1,
Expand Down
4 changes: 2 additions & 2 deletions siapy/features/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

class FeatureSelectorConfig(BaseModel):
k_features: Annotated[
int | tuple | str,
int | str | tuple[int, ...],
"can be: 'best' - most extensive, (1, n) - check range of features, n - exact number of features",
] = (1, 20)
cv: int = 3
Expand All @@ -38,7 +38,7 @@ def feature_selector_factory(
problem_type: Literal["regression", "classification"],
*,
k_features: Annotated[
int | tuple | str,
int | str | tuple[int, ...],
"can be: 'best' - most extensive, (1, n) - check range of features, n - exact number of features",
] = (1, 20),
cv: int = 3,
Expand Down
8 changes: 5 additions & 3 deletions siapy/transformations/corregistrator.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Sequence

import matplotlib.pyplot as plt
import numpy as np

Expand All @@ -23,10 +25,10 @@ def map_affine_approx_2d(points_ref: np.ndarray, points_mov: np.ndarray) -> np.n


def affine_matx_2d(
scale: tuple[float, float] = (1, 1),
trans: tuple[float, float] = (0, 0),
scale: tuple[float, float] | Sequence[float] = (1, 1),
trans: tuple[float, float] | Sequence[float] = (0, 0),
rot: float = 0,
shear: tuple[float, float] = (0, 0),
shear: tuple[float, float] | Sequence[float] = (0, 0),
) -> np.ndarray:
"""Create arbitrary affine transformation matrix"""
rot = rot * np.pi / 180
Expand Down
32 changes: 23 additions & 9 deletions siapy/utils/images.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import spectral as sp

from siapy.core import logger
from siapy.core.exceptions import InvalidInputError
from siapy.core.types import ImageDataType, ImageType
from siapy.entities import SpectralImage
from siapy.transformations.image import rescale
Expand Down Expand Up @@ -172,7 +173,7 @@ def convert_radiance_image_to_reflectance(
panel_correction: np.ndarray,
save_path: Annotated[
str | Path | None, "Header file (with '.hdr' extension) name with path."
],
] = None,
**kwargs: Any,
) -> np.ndarray | SpectralImage:
image_ref_np = image.to_numpy() * panel_correction
Expand All @@ -187,14 +188,27 @@ def convert_radiance_image_to_reflectance(
def calculate_correction_factor_from_panel(
image: SpectralImage,
panel_reference_reflectance: float,
panel_shape_label: str = "reference_panel",
) -> np.ndarray | None:
panel_shape = image.geometric_shapes.get_by_name(panel_shape_label)
if panel_shape is None:
return None

panel_signatures = image.to_signatures(panel_shape.convex_hull())
panel_radiance_mean = panel_signatures.signals.mean()
panel_shape_label: str | None = None,
) -> np.ndarray:
if panel_shape_label:
panel_shape = image.geometric_shapes.get_by_name(panel_shape_label)
if not panel_shape:
raise InvalidInputError(
input_value={"panel_shape_label": panel_shape_label},
message="Panel shape label not found.",
)
panel_signatures = image.to_signatures(panel_shape.convex_hull())
panel_radiance_mean = panel_signatures.signals.mean()

else:
temp_mean = image.mean(axis=(0, 1))
if not isinstance(temp_mean, np.ndarray):
raise InvalidInputError(
input_value={"image": image},
message=f"Expected image.mean(axis=(0, 1)) to return np.ndarray, but got {type(temp_mean).__name__}.",
)
panel_radiance_mean = temp_mean

panel_reflectance_mean = np.full(image.bands, panel_reference_reflectance)
panel_correction = panel_reflectance_mean / panel_radiance_mean
return panel_correction
Expand Down
15 changes: 13 additions & 2 deletions tests/utils/test_utils_images.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ def shape(self) -> tuple[int, int, int]:
assert save_path.exists()


def test_calculate_correction_factor_from_panel(spectral_images):
def test_calculate_correction_factor_from_panel_with_label(spectral_images):
pixels = Pixels.from_iterable([(900, 1150), (1050, 1300)])
rect = Shape.from_shape_type(
shape_type="rectangle", pixels=pixels, label="reference_panel"
Expand All @@ -156,7 +156,6 @@ def test_calculate_correction_factor_from_panel(spectral_images):
panel_shape_label="reference_panel",
)

assert panel_correction is not None
assert isinstance(panel_correction, np.ndarray)
assert panel_correction.shape == (image_vnir.bands,)

Expand All @@ -168,6 +167,18 @@ def test_calculate_correction_factor_from_panel(spectral_images):
)


def test_calculate_correction_factor_from_panel_without_label(spectral_images):
image_vnir = spectral_images.vnir
panel_correction = calculate_correction_factor_from_panel(
image=image_vnir,
panel_reference_reflectance=0.3,
)
direct_panel_calculation = np.full(image_vnir.bands, 0.3) / image_vnir.mean(
axis=(0, 1)
)
assert np.array_equal(direct_panel_calculation, panel_correction)


def test_convert_radiance_image_to_reflectance_without_saving(spectral_images):
image_vnir = spectral_images.vnir
panel_correction = np.random.default_rng().random(image_vnir.bands)
Expand Down
Loading