| import numpy as np |
|
|
| def calculate_iou(pred_mask, true_mask): |
| """ |
| Calculate Intersection over Union (IoU) for binary masks. |
| """ |
| intersection = np.logical_and(pred_mask, true_mask).sum() |
| union = np.logical_or(pred_mask, true_mask).sum() |
| if union == 0: |
| return 1.0 |
| return intersection / union |
|
|
| def calculate_dice(pred_mask, true_mask): |
| """ |
| Calculate Dice Coefficient for binary masks. |
| """ |
| intersection = np.logical_and(pred_mask, true_mask).sum() |
| return (2. * intersection) / (pred_mask.sum() + true_mask.sum() + 1e-6) |
|
|
| def calculate_accuracy(preds, labels): |
| """ |
| Calculate simple classification accuracy. |
| """ |
| correct = (preds == labels).sum().item() |
| total = labels.size(0) |
| return correct / total |
|
|
| def calculate_ndvi(nir_band, red_band): |
| """ |
| Calculate NDVI given NIR and Red bands. |
| NDVI = (NIR - Red) / (NIR + Red) |
| """ |
| nir = nir_band.astype(float) |
| red = red_band.astype(float) |
| |
| denominator = (nir + red) |
| |
| denominator[denominator == 0] = 1e-6 |
| |
| ndvi = (nir - red) / denominator |
| return ndvi |
|
|
| def ndvi_correlation(predicted_greenery_percentages, true_mean_ndvis): |
| """ |
| Calculate Pearson correlation coefficient between predicted greenery |
| percentage and true mean NDVI across a set of images. |
| """ |
| if len(predicted_greenery_percentages) < 2: |
| return 0.0 |
| return np.corrcoef(predicted_greenery_percentages, true_mean_ndvis)[0, 1] |
|
|