deeptrees.modules

deeptrees.modules.indices

deeptrees.modules.indices.gci(raster, red_idx=0, green_idx=1, nir_idx=3, axis=0)[source]

Calculate Green Chlorophyll Index (GCI). GCI = (NIR / GREEN) - 1

deeptrees.modules.indices.hue(raster, red_idx=0, green_idx=1, blue_idx=2, axis=0)[source]

Calculate hue from RGB.

deeptrees.modules.indices.ndvi(raster, red_idx=0, nir_idx=3, axis=0)[source]

Calculate Normalized Difference Vegetation Index (NDVI). NDVI = (NIR - RED) / (NIR + RED)

deeptrees.modules.indices.ndvi_xarray(img, red, nir)[source]

Calculates the Normalized Difference Vegetation Index (NDVI) from a given image.

NDVI is calculated using the formula: (NIR - Red) / (NIR + Red + 1E-10). The input image bands are implicitly converted to Float32 for the calculation.

Parameters: img (xarray.DataArray): The input image as an xarray DataArray. red (int or str): The band index or name corresponding to the red band. nir (int or str): The band index or name corresponding to the near-infrared (NIR) band.

Returns: xarray.DataArray: The NDVI values as an xarray DataArray.

deeptrees.modules.losses

class deeptrees.modules.losses.BinarySegmentationLoss(iou_weight=0.5, **kwargs)[source]

Bases: _Loss

Combines binary cross entropy loss with -log(iou). Works with probabilities, so after applying sigmoid activation.

__init__(iou_weight=0.5, **kwargs)[source]

Initialize internal Module state, shared by both nn.Module and ScriptModule.

forward(y_pred, y_true)[source]

Computes the custom loss function which is a combination of Binary Cross-Entropy (BCE) loss and Intersection over Union (IoU) loss. Parameters: ———– y_pred : torch.Tensor

The predicted output tensor from the model. It should have the same shape as y_true.

y_truetorch.Tensor

The ground truth tensor. It should have the same shape as y_pred.

Returns:

torch.Tensor

The computed loss value which is a weighted sum of BCE loss and the negative logarithm of IoU.

Notes:

  • The BCE loss is weighted by (1 - self.iou_weight).

  • The IoU loss is weighted by self.iou_weight and is computed as the negative logarithm of the IoU.

  • Ensure that iou function is defined and computes the Intersection over Union correctly.

class deeptrees.modules.losses.BinarySegmentationLossWithLogits(iou_weight=0.5, **kwargs)[source]

Bases: _Loss

Combines binary cross entropy loss with -log(iou). Works with logits - don’t apply sigmoid to your network output.

__init__(iou_weight=0.5, **kwargs)[source]

Initialize internal Module state, shared by both nn.Module and ScriptModule.

forward(y_pred, y_true)[source]

Computes the loss by combining Binary Cross-Entropy (BCE) loss and Intersection over Union (IoU) loss. :type y_pred: torch.Tensor :param y_pred: The predicted output tensor from the model. This tensor typically contains

the predicted probabilities for each class.

Parameters:

y_true (torch.Tensor) – The ground truth tensor. This tensor contains the actual class labels.

Returns:

The computed loss value which is a combination of BCE loss and IoU loss.

Return type:

torch.Tensor

The loss is calculated as follows: 1. Compute the BCE loss between the predicted and true values. 2. Compute the IoU loss between the predicted and true values. 3. Combine the two losses using the iou_weight attribute to balance their contributions. .. note:

- The `iou_weight` attribute should be defined in the class to control the balance between BCE and IoU losses.
- The `bceloss` method should be defined in the class to compute the BCE loss.
- The `iou_with_logits` function should be defined to compute the IoU loss with logits.

deeptrees.modules.metrics

deeptrees.modules.metrics.iou(y_pred, y_true)[source]

Calculate the Intersection over Union (IoU) between two tensors. The IoU is a measure of the overlap between two sets, defined as the intersection divided by the union of the sets. It is commonly used in image segmentation tasks to evaluate the accuracy of predictions. :type y_pred: torch.Tensor :param y_pred: Predicted tensor, typically a binary mask. :type y_pred: torch.Tensor :type y_true: torch.Tensor :param y_true: Ground truth tensor, typically a binary mask. :type y_true: torch.Tensor

Returns:

The IoU score, a value between 0 and 1, where 1 indicates

perfect overlap and 0 indicates no overlap.

Return type:

float

Note

  • The function uses a small epsilon value to avoid division by zero.

  • Both input tensors should have the same shape.

  • The tensors are expected to be of type torch.float32.

deeptrees.modules.metrics.iou_with_logits(y_pred, y_true)[source]

Compute the Intersection over Union (IoU) score with logits. This function applies a sigmoid activation to the predicted logits and then calculates the IoU score between the predicted and true values. :type y_pred: torch.Tensor :param y_pred: The predicted logits tensor. This tensor should contain raw, unnormalized scores. :type y_pred: torch.Tensor :type y_true: torch.Tensor :param y_true: The ground truth binary tensor. This tensor should contain binary values (0 or 1). :type y_true: torch.Tensor

Returns:

The IoU score between the predicted and true values.

Return type:

float

Example

>>> y_pred = torch.tensor([[0.8, 0.4], [0.3, 0.9]])
>>> y_true = torch.tensor([[1, 0], [0, 1]])
>>> iou_score = iou_with_logits(y_pred, y_true)
>>> print(iou_score)

deeptrees.modules.polygon_metrics

deeptrees.modules.polygon_utils

deeptrees.modules.postprocessing

deeptrees.modules.rasterize_utils

deeptrees.modules.traits

deeptrees.modules.traits.chlorophyll_index(red, green, nir, save_to=None)[source]

Calculate the Chlorophyll Index-Green (CIG) from the given bands. The Chlorophyll Index Green (CIG) is defined as (NIR/Green)-1. Parameters: red (numpy.ndarray): The red band values. green (numpy.ndarray): The green band values. nir (numpy.ndarray): The near-infrared (NIR) band values. save_to (str): The file path to save the calculated GCI values as a CSV file. Default is None. Returns: numpy.ndarray: The calculated Chlorophyll Index (CIG) values.

deeptrees.modules.traits.green_chlorophyll_index(red, green, nir, save_to=None)[source]

Calculate the Green Chlorophyll Index (GCI) from the given bands. The Green Chlorophyll Index (GCI) is defined as (NIR-Green)/(NIR+Green). Parameters: red (numpy.ndarray): The red band values. green (numpy.ndarray): The green band values. nir (numpy.ndarray): The near-infrared (NIR) band values. save_to (str): The file path to save the calculated GCI values as a CSV file. Default is None. Returns: numpy.ndarray: The calculated Green Chlorophyll Index (GCI) values.

deeptrees.modules.traits.hue_index(red, green, blue, save_to=None)[source]

Calculate the Hue Index from the given bands. The Hue Index is defined as arctan((2*green - red - blue) / sqrt(3) * (red - blue)). Parameters: red (numpy.ndarray): The red band values. green (numpy.ndarray): The green band values. blue (numpy.ndarray): The blue band values. save_to (str): The file path to save the calculated Hue Index values as a CSV file. Default is None. Returns: numpy.ndarray: The calculated Hue Index values.

deeptrees.modules.traits.longest_cross_spread(polygon)[source]

Calculate the longest cross spread of a given polygon. The longest cross spread is defined as the maximum distance between two points on the polygon’s boundary that are perpendicular to the longest spread line of the polygon. Parameters: polygon (shapely.geometry.Polygon): The input polygon for which the longest cross spread is calculated. Returns: tuple: A tuple containing:

  • max_cross_distance (float): The maximum cross distance found.

  • cross_point_pair (tuple): A tuple of two shapely.geometry.Point objects representing the endpoints of the longest cross spread. If the polygon is None or invalid, or if no valid cross spread is found, returns (None, None).

deeptrees.modules.traits.longest_spread(polygon)[source]

Calculate the longest distance between any two points on the exterior of a polygon. Parameters: polygon (shapely.geometry.Polygon): A shapely Polygon object. If the polygon is None or not a valid polygon, the function returns (None, None). Returns: tuple: A tuple containing the maximum distance (float) and the pair of points (tuple of shapely.geometry.Point) that are farthest apart.

If the polygon is invalid, returns (None, None).

deeptrees.modules.utils

Contents