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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Feature engineering functions to create additional features from input bands.
|
| 3 |
+
These functions generate vegetation indices, texture features, and other derived features
|
| 4 |
+
that the model expects beyond the 59 base bands.
|
| 5 |
+
|
| 6 |
+
Author: najahpokkiri
|
| 7 |
+
Date: 2025-05-17
|
| 8 |
+
"""
|
| 9 |
+
import numpy as np
|
| 10 |
+
from sklearn.preprocessing import StandardScaler
|
| 11 |
+
from sklearn.decomposition import PCA
|
| 12 |
+
|
| 13 |
+
# Safe division function for indices
|
| 14 |
+
def safe_divide(a, b, fill_value=0.0):
|
| 15 |
+
"""Safe division that handles zeros in the denominator"""
|
| 16 |
+
a = np.asarray(a, dtype=np.float32)
|
| 17 |
+
b = np.asarray(b, dtype=np.float32)
|
| 18 |
+
|
| 19 |
+
# Handle NaN/Inf in inputs
|
| 20 |
+
a = np.nan_to_num(a, nan=0.0, posinf=0.0, neginf=0.0)
|
| 21 |
+
b = np.nan_to_num(b, nan=1e-10, posinf=1e10, neginf=-1e10)
|
| 22 |
+
|
| 23 |
+
mask = np.abs(b) < 1e-10
|
| 24 |
+
result = np.full_like(a, fill_value, dtype=np.float32)
|
| 25 |
+
if np.any(~mask):
|
| 26 |
+
result[~mask] = a[~mask] / b[~mask]
|
| 27 |
+
|
| 28 |
+
return np.nan_to_num(result, nan=fill_value, posinf=fill_value, neginf=fill_value)
|
| 29 |
+
|
| 30 |
+
def calculate_spectral_indices(image_data):
|
| 31 |
+
"""Calculate common spectral indices from satellite bands"""
|
| 32 |
+
indices = {}
|
| 33 |
+
|
| 34 |
+
# Assuming standard band order: B2(blue), B3(green), B4(red), B8(nir), etc.
|
| 35 |
+
# Adjust band indices based on your data
|
| 36 |
+
try:
|
| 37 |
+
# Extract key bands (adjust indices as needed for your data)
|
| 38 |
+
blue = image_data[1] if image_data.shape[0] > 1 else None
|
| 39 |
+
green = image_data[2] if image_data.shape[0] > 2 else None
|
| 40 |
+
red = image_data[3] if image_data.shape[0] > 3 else None
|
| 41 |
+
nir = image_data[7] if image_data.shape[0] > 7 else None
|
| 42 |
+
swir1 = image_data[9] if image_data.shape[0] > 9 else None
|
| 43 |
+
swir2 = image_data[10] if image_data.shape[0] > 10 else None
|
| 44 |
+
|
| 45 |
+
# Calculate indices if bands are available
|
| 46 |
+
if red is not None and nir is not None:
|
| 47 |
+
# NDVI (Normalized Difference Vegetation Index)
|
| 48 |
+
indices['NDVI'] = safe_divide(nir - red, nir + red)
|
| 49 |
+
|
| 50 |
+
if blue is not None and green is not None:
|
| 51 |
+
# EVI (Enhanced Vegetation Index)
|
| 52 |
+
indices['EVI'] = 2.5 * safe_divide(nir - red, nir + 6*red - 7.5*blue + 1)
|
| 53 |
+
|
| 54 |
+
# SAVI (Soil Adjusted Vegetation Index)
|
| 55 |
+
indices['SAVI'] = 1.5 * safe_divide(nir - red, nir + red + 0.5)
|
| 56 |
+
|
| 57 |
+
# NDWI (Normalized Difference Water Index)
|
| 58 |
+
indices['NDWI'] = safe_divide(green - nir, green + nir)
|
| 59 |
+
|
| 60 |
+
if swir1 is not None and nir is not None:
|
| 61 |
+
# NDMI (Normalized Difference Moisture Index)
|
| 62 |
+
indices['NDMI'] = safe_divide(nir - swir1, nir + swir1)
|
| 63 |
+
|
| 64 |
+
if swir2 is not None and nir is not None:
|
| 65 |
+
# NBR (Normalized Burn Ratio)
|
| 66 |
+
indices['NBR'] = safe_divide(nir - swir2, nir + swir2)
|
| 67 |
+
|
| 68 |
+
except Exception as e:
|
| 69 |
+
print(f"Error calculating spectral indices: {e}")
|
| 70 |
+
|
| 71 |
+
return indices
|
| 72 |
+
|
| 73 |
+
def extract_texture_features(image_data):
|
| 74 |
+
"""Extract texture features from key bands"""
|
| 75 |
+
texture_features = {}
|
| 76 |
+
|
| 77 |
+
try:
|
| 78 |
+
from skimage.filters import sobel
|
| 79 |
+
|
| 80 |
+
# Use NIR band for texture if available
|
| 81 |
+
key_band_idx = 7 # NIR band
|
| 82 |
+
if image_data.shape[0] > key_band_idx:
|
| 83 |
+
band = image_data[key_band_idx].copy()
|
| 84 |
+
|
| 85 |
+
# Normalize for texture analysis
|
| 86 |
+
band_min, band_max = np.nanpercentile(band[~np.isnan(band)], [1, 99])
|
| 87 |
+
band_norm = np.clip((band - band_min) / (band_max - band_min + 1e-8), 0, 1)
|
| 88 |
+
|
| 89 |
+
# Handle NaN values
|
| 90 |
+
band_norm = np.nan_to_num(band_norm)
|
| 91 |
+
|
| 92 |
+
# Edge detection using Sobel filter
|
| 93 |
+
sobel_response = sobel(band_norm)
|
| 94 |
+
texture_features['Sobel'] = sobel_response
|
| 95 |
+
|
| 96 |
+
# Try to use more advanced texture features if available
|
| 97 |
+
try:
|
| 98 |
+
from skimage.feature import graycomatrix, graycoprops
|
| 99 |
+
|
| 100 |
+
# Convert to uint8 for GLCM
|
| 101 |
+
band_uint8 = (band_norm * 255).astype(np.uint8)
|
| 102 |
+
|
| 103 |
+
# Use a small central patch for efficiency
|
| 104 |
+
size = min(32, band_uint8.shape[0], band_uint8.shape[1])
|
| 105 |
+
center_y, center_x = band_uint8.shape[0] // 2, band_uint8.shape[1] // 2
|
| 106 |
+
half_size = size // 2
|
| 107 |
+
patch = band_uint8[
|
| 108 |
+
max(0, center_y - half_size):min(band_uint8.shape[0], center_y + half_size),
|
| 109 |
+
max(0, center_x - half_size):min(band_uint8.shape[1], center_x + half_size)
|
| 110 |
+
]
|
| 111 |
+
|
| 112 |
+
if patch.size > 0:
|
| 113 |
+
# Calculate GLCM
|
| 114 |
+
glcm = graycomatrix(patch, [1], [0], levels=256, symmetric=True, normed=True)
|
| 115 |
+
|
| 116 |
+
# Extract properties
|
| 117 |
+
for prop in ['contrast', 'dissimilarity', 'homogeneity', 'energy']:
|
| 118 |
+
value = float(graycoprops(glcm, prop)[0, 0])
|
| 119 |
+
# Fill with scalar value
|
| 120 |
+
texture_features[f'GLCM_{prop}'] = np.full_like(band, value)
|
| 121 |
+
|
| 122 |
+
except Exception as e:
|
| 123 |
+
print(f"Advanced texture features not available: {e}")
|
| 124 |
+
|
| 125 |
+
except Exception as e:
|
| 126 |
+
print(f"Error extracting texture features: {e}")
|
| 127 |
+
|
| 128 |
+
return texture_features
|
| 129 |
+
|
| 130 |
+
def calculate_spatial_features(image_data, indices):
|
| 131 |
+
"""Calculate spatial context features like gradients"""
|
| 132 |
+
spatial_features = {}
|
| 133 |
+
|
| 134 |
+
try:
|
| 135 |
+
# Use NIR band for gradient if available
|
| 136 |
+
key_band_idx = 7 # NIR band
|
| 137 |
+
if image_data.shape[0] > key_band_idx:
|
| 138 |
+
band = image_data[key_band_idx].copy()
|
| 139 |
+
band = np.nan_to_num(band)
|
| 140 |
+
|
| 141 |
+
# Calculate gradients
|
| 142 |
+
grad_y, grad_x = np.gradient(band)
|
| 143 |
+
grad_magnitude = np.sqrt(grad_x**2 + grad_y**2)
|
| 144 |
+
spatial_features['Gradient'] = grad_magnitude
|
| 145 |
+
|
| 146 |
+
# Calculate NDVI gradient if available
|
| 147 |
+
if 'NDVI' in indices:
|
| 148 |
+
ndvi = indices['NDVI']
|
| 149 |
+
ndvi = np.nan_to_num(ndvi)
|
| 150 |
+
|
| 151 |
+
grad_y, grad_x = np.gradient(ndvi)
|
| 152 |
+
grad_magnitude = np.sqrt(grad_x**2 + grad_y**2)
|
| 153 |
+
spatial_features['NDVI_gradient'] = grad_magnitude
|
| 154 |
+
|
| 155 |
+
except Exception as e:
|
| 156 |
+
print(f"Error calculating spatial features: {e}")
|
| 157 |
+
|
| 158 |
+
return spatial_features
|
| 159 |
+
|
| 160 |
+
def calculate_pca_features(image_data, n_components=10):
|
| 161 |
+
"""Calculate PCA features from satellite bands"""
|
| 162 |
+
pca_features = {}
|
| 163 |
+
|
| 164 |
+
try:
|
| 165 |
+
# Reshape to (pixels, bands)
|
| 166 |
+
orig_shape = image_data.shape
|
| 167 |
+
bands_reshaped = image_data.reshape(orig_shape[0], -1).T
|
| 168 |
+
|
| 169 |
+
# Handle NaN values
|
| 170 |
+
valid_mask = ~np.any(np.isnan(bands_reshaped), axis=1)
|
| 171 |
+
bands_clean = bands_reshaped[valid_mask]
|
| 172 |
+
|
| 173 |
+
if len(bands_clean) > 0:
|
| 174 |
+
# Apply PCA
|
| 175 |
+
scaler = StandardScaler()
|
| 176 |
+
bands_scaled = scaler.fit_transform(bands_clean)
|
| 177 |
+
|
| 178 |
+
# Limit components to save memory
|
| 179 |
+
n_components = min(n_components, bands_scaled.shape[1], 25)
|
| 180 |
+
pca = PCA(n_components=n_components)
|
| 181 |
+
pca_result = pca.fit_transform(bands_scaled)
|
| 182 |
+
|
| 183 |
+
# Map back to original shape
|
| 184 |
+
pca_full = np.zeros((bands_reshaped.shape[0], n_components))
|
| 185 |
+
pca_full[valid_mask] = pca_result
|
| 186 |
+
|
| 187 |
+
# Reshape to original spatial dimensions
|
| 188 |
+
pca_reshaped = pca_full.reshape(orig_shape[1], orig_shape[2], n_components)
|
| 189 |
+
|
| 190 |
+
# Store each component
|
| 191 |
+
for i in range(n_components):
|
| 192 |
+
pca_features[f'PCA_{i+1}'] = pca_reshaped[:, :, i]
|
| 193 |
+
|
| 194 |
+
except Exception as e:
|
| 195 |
+
print(f"Error calculating PCA features: {e}")
|
| 196 |
+
|
| 197 |
+
return pca_features
|
| 198 |
+
|
| 199 |
+
def extract_all_features(image_data):
|
| 200 |
+
"""
|
| 201 |
+
Extract all necessary features from input bands to match the 99 features
|
| 202 |
+
expected by the model.
|
| 203 |
+
|
| 204 |
+
Args:
|
| 205 |
+
image_data: NumPy array of shape (bands, height, width)
|
| 206 |
+
|
| 207 |
+
Returns:
|
| 208 |
+
features_array: NumPy array of shape (pixels, features)
|
| 209 |
+
valid_mask: Boolean mask indicating valid pixels
|
| 210 |
+
"""
|
| 211 |
+
height, width = image_data.shape[1], image_data.shape[2]
|
| 212 |
+
|
| 213 |
+
# Create valid pixel mask (no NaN or Inf values)
|
| 214 |
+
valid_mask = np.all(np.isfinite(image_data), axis=0)
|
| 215 |
+
|
| 216 |
+
# Extract valid pixel coordinates
|
| 217 |
+
valid_y, valid_x = np.where(valid_mask)
|
| 218 |
+
n_valid_pixels = len(valid_y)
|
| 219 |
+
|
| 220 |
+
# Calculate all feature types
|
| 221 |
+
indices = calculate_spectral_indices(image_data)
|
| 222 |
+
texture_features = extract_texture_features(image_data)
|
| 223 |
+
spatial_features = calculate_spatial_features(image_data, indices)
|
| 224 |
+
pca_features = calculate_pca_features(image_data, n_components=25)
|
| 225 |
+
|
| 226 |
+
# Combine features
|
| 227 |
+
all_features = {}
|
| 228 |
+
|
| 229 |
+
# 1. Original bands
|
| 230 |
+
for i in range(image_data.shape[0]):
|
| 231 |
+
all_features[f'Band_{i+1}'] = image_data[i]
|
| 232 |
+
|
| 233 |
+
# 2. Add other feature types
|
| 234 |
+
all_features.update(indices)
|
| 235 |
+
all_features.update(texture_features)
|
| 236 |
+
all_features.update(spatial_features)
|
| 237 |
+
all_features.update(pca_features)
|
| 238 |
+
|
| 239 |
+
# Get list of all feature names
|
| 240 |
+
feature_names = list(all_features.keys())
|
| 241 |
+
print(f"Generated {len(feature_names)} features: {feature_names}")
|
| 242 |
+
|
| 243 |
+
# Create feature matrix for valid pixels
|
| 244 |
+
feature_matrix = np.zeros((n_valid_pixels, len(feature_names)), dtype=np.float32)
|
| 245 |
+
|
| 246 |
+
for i, feature_name in enumerate(feature_names):
|
| 247 |
+
feature_data = all_features[feature_name]
|
| 248 |
+
# Extract values for valid pixels
|
| 249 |
+
if feature_data.ndim == 2:
|
| 250 |
+
feature_values = feature_data[valid_y, valid_x]
|
| 251 |
+
else:
|
| 252 |
+
# Handle case where feature is a constant or has different dimensions
|
| 253 |
+
feature_values = np.full(n_valid_pixels, feature_data)
|
| 254 |
+
|
| 255 |
+
# Handle NaN values
|
| 256 |
+
feature_values = np.nan_to_num(feature_values, nan=0.0)
|
| 257 |
+
feature_matrix[:, i] = feature_values
|
| 258 |
+
|
| 259 |
+
return feature_matrix, valid_mask, feature_names
|