0% found this document useful (0 votes)
2 views1 page

SAM Code

The document contains a Python function that computes the Spectral Angle Mapper (SAM) between two hyperspectral images represented as NumPy arrays. It checks for shape compatibility, flattens the input arrays, and calculates the mean SAM value in radians while ensuring numerical stability. An example usage of the function demonstrates its application with random data.

Uploaded by

davrazi123
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views1 page

SAM Code

The document contains a Python function that computes the Spectral Angle Mapper (SAM) between two hyperspectral images represented as NumPy arrays. It checks for shape compatibility, flattens the input arrays, and calculates the mean SAM value in radians while ensuring numerical stability. An example usage of the function demonstrates its application with random data.

Uploaded by

davrazi123
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

import numpy as np

def spectral_angle_mapper_np(preds: [Link], target:


[Link]) -> float:
"""
Compute Spectral Angle Mapper (SAM) between two hyperspectral
images.
Args:
preds: (H, W, C) predicted spectra
target: (H, W, C) reference spectra
Returns:
Mean SAM value in radians
"""
if [Link] != [Link]:
raise ValueError("preds and target must have the same
shape (H, W, C)")

# Flatten spatial dimensions


preds_flat = [Link](-1, [Link][-1])
target_flat = [Link](-1, [Link][-1])

# Avoid division by zero


eps = 1e-12
dot_product = [Link](preds_flat * target_flat, axis=1)
norm_preds = [Link](preds_flat, axis=1)
norm_target = [Link](target_flat, axis=1)

cos_theta = dot_product / (norm_preds * norm_target + eps)


cos_theta = [Link](cos_theta, -1, 1) # Numerical stability

angles = [Link](cos_theta)
return [Link](angles)

# Example usage
preds_np = [Link](16, 16, 3)
target_np = [Link](16, 16, 3)
sam_value_np = spectral_angle_mapper_np(preds_np, target_np)
print(f"SAM: {sam_value_np:.4f} radians")

You might also like