spectralpython / spectral

Python module for hyperspectral image processing
MIT License
571 stars 139 forks source link

Improve docs and error message #108

Closed kormang closed 4 years ago

kormang commented 4 years ago

Example of usage - visually compare signatures from database (spectral library) and from image.

import spectral as spy
import matplotlib.pyplot as plt

# Read pixel signature.
img = open_image('92AV3C.lan')
vegetation = img[100, 60]

# Read bands.
bands = aviris.read_aviris_bands('92AV3C.spc')
# We need bands to be sorted.
bands_sorted = np.sort(bands.centers)
# Adjust signature to sorted bands.
resampler = BandResampler(bands.centers, bands_sorted, bands.bandwidths)
# Aviris data is multiplied by 10000.
vegetation = resampler(vegetation) / 10000
# Use micrometers like spectral library does.
bands_um = bands_sorted / 1000

# Open spectral library database.
db = EcostressDatabase('ecostress.db')
# Read some IDs of grass, where band range is close to that of AVIRIS.
grass_ids = [id for id, in db.query(f'SELECT SampleID FROM Spectra WHERE SampleID IN'
                                    f' (SELECT SampleID FROM Samples WHERE Name LIKE "%grass%" OR Description LIKE "%grass%" OR Class LIKE "%grass%" limit 10)'
                                    f' AND MinWavelength >= 0.35 AND  MinWavelength <= 0.38 AND MaxWavelength >= 2.4 AND MaxWavelength <= 2.6')]
# Get signatures for those IDs.
ecograss_spectra = [db.get_signature(id) for id in grass_ids]
# Transform siguratures into 2-tuple of ndarray for convenience, and also devide by 100 as library holds percentages.
ecograss_spectra = [(np.array(s.x), np.array(s.y) / 100) for s in ecograss_spectra]

# Plot grass for library.
plt.figure()
for x, y in ecograss_spectra:
    plt.plot(x, y)
# Compare plot with vegetation from the image.
plt.plot(bands_um, vegetation, color='black')

# Remove continuum.
ecograss_continuum_removed = [(x, spy.continuum.remove_continuum(y, x)) for x, y in ecograss_spectra]

# And, compare plots again.
plt.figure()
for x, y in ecograss_continuum_removed:
    plt.plot(x, y)
plt.plot(bands_um, spy.continuum.remove_continuum(vegetation, bands_um), color='black')

# Remove segmented upper hull.
ecograss_continuum_removed = [(x, spy.continuum.remove_continuum(y, x, mode='segmented')) for x, y in ecograss_spectra]

# And, compare plots again.
plt.figure()
for x, y in ecograss_continuum_removed:
    plt.plot(x, y)
plt.plot(bands_um, spy.continuum.remove_continuum(vegetation, bands_um, mode='segmented'), color='black')