How to use the spectral.open_image function in spectral

To help you get started, we’ve selected a few spectral examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github nshaud / DeepHyperX / utils.py View on Github external
def open_file(dataset):
    _, ext = os.path.splitext(dataset)
    ext = ext.lower()
    if ext == '.mat':
        # Load Matlab array
        return io.loadmat(dataset)
    elif ext == '.tif' or ext == '.tiff':
        # Load TIFF file
        return misc.imread(dataset)
    elif ext == '.hdr':
        img = spectral.open_image(dataset)
        return img.load()
    else:
        raise ValueError("Unknown file format: {}".format(ext))
github capstone-coal / pycoal / examples / example_spectra.py View on Github external
@copyright:  Copyright (C) 2017-2019 COAL Developers

@license:    GNU General Public License version 2

@contact:    coal-capstone@googlegroups.com
'''

import constants
import spectral
import matplotlib
import matplotlib.pyplot as plt

# load library
library_filename = constants.LIBRARY_FILENAME
library = spectral.open_image(library_filename)
schwert_index = library.names.index(u'Schwertmannite BZ93-1 s06av95a=b')
sldgwet_index = library.names.index(u'Renyolds_TnlSldgWet SM93-15w s06av95a=a')
sludge_index = library.names.index(u'Renyolds_Tnl_Sludge SM93-15 s06av95a=a')
bands = [1000 * band for band in library.bands.centers]

# customize figure
plt.rcParams['font.size'] = 8
plt.rcParams['legend.fontsize'] = 8
plt.rcParams['xtick.labelsize'] = 8
plt.rcParams['ytick.labelsize'] = 8
plt.rcParams['lines.linewidth'] = 2
plt.rcParams['text.color'] = 'white'
plt.rcParams['xtick.color'] = 'white'
plt.rcParams['ytick.color'] = 'white'
plt.rcParams['axes.labelcolor'] = 'white'
plt.rcParams['axes.edgecolor'] = 'white'
github capstone-coal / pycoal / pycoal / mineral.py View on Github external
model_file_name (str):          filename of the Keras model used to
        classify
        class_names (str[], optional):  list of names of classes handled by
        the model
        scores_file_name (str):         filename of the image to hold each
        pixel's classification score
        in_memory (boolean, optional):  enable loading entire image

    Returns:
        None
    """

    from keras.models import load_model

    # open the image
    image = spectral.open_image(image_file_name)
    if in_memory:
        data = image.load()
    else:
        data = image.asarray()
    m = image.shape[0]
    n = image.shape[1]

    # allocate a zero-initialized MxN array for the classified image
    classified = numpy.zeros(shape=(m, n), dtype=numpy.uint16)

    if scores_file_name is not None:
        # allocate a zero-initialized MxN array for the scores image
        scored = numpy.zeros(shape=(m, n), dtype=numpy.float64)

    model = load_model(model_file_name)
github AngryCai / Research / Toolbox / Preprocessing.py View on Github external
def prepare_data(self, img_path, gt_path):
        if img_path[-3:] == 'mat':
            import scipy.io as sio
            img_mat = sio.loadmat(img_path)
            gt_mat = sio.loadmat(gt_path)
            img_keys = img_mat.keys()
            gt_keys = gt_mat.keys()
            img_key = [k for k in img_keys if k != '__version__' and k != '__header__' and k != '__globals__']
            gt_key = [k for k in gt_keys if k != '__version__' and k != '__header__' and k != '__globals__']
            return img_mat.get(img_key[0]).astype('float64'), gt_mat.get(gt_key[0]).astype('int8')
        else:
            import spectral as spy
            img = spy.open_image(img_path).load()
            gt = spy.open_image(gt_path)
            a = spy.principal_components()
            a.transform()
            return img, gt.read_band(0)
github eecn / Hyperspectral-Classification / utils.py View on Github external
def open_file(dataset):
    _, ext = os.path.splitext(dataset)
    ext = ext.lower()
    if ext == '.mat':
        # Load Matlab array
        return io.loadmat(dataset)
    elif ext == '.tif' or ext == '.tiff':
        # Load TIFF file
        return imageio.imread(dataset)
    elif ext == '.hdr':
        img = spectral.open_image(dataset)
        return img.load()
    else:
        raise ValueError("Unknown file format: {}".format(ext))
github capstone-coal / pycoal / pycoal / mineral.py View on Github external
"""
        Generate a three-band hypercube from an AVIRIS image.
        Args:
            image_file_name (str):     filename of the source image

        Returns:
            None
        """

        start = time.time()
        logging.info(
            "Starting generation of hypercube from input file: '%s'" % (
                image_file_name))

        # # open the image
        image = spectral.open_image(image_file_name)

        #view the hypercube
        view_cube(image, bands=[29, 19, 9], title="Hypercube representation of %s" % os.path.basename(image_file_name))
        
        end = time.time()
        seconds_elapsed = end - start
        m, s = divmod(seconds_elapsed, 60)
        h, m = divmod(m, 60)
        logging.info(
            "Completed hypercube generation. Time elapsed: '%d:%02d:%02d'" % (
                h, m, s))
github capstone-coal / pycoal / pycoal / environment.py View on Github external
def create_empty_copy(source_filename, destination_filename):
        """
        Create an empty copy of a COAL classified image with the same size.

        Args:
            source_filename (str):      filename of the source image
            destination_filename (str): filename of the destination image
        """
        logging.info(
            "Creating an empty copy of classified image '%s' with the same "
            "size. Saving to '%s'", source_filename, destination_filename)
        # open the source image
        source = spectral.open_image(source_filename)

        # create an empty array of the same dimensions
        destination = numpy.zeros(shape=source.shape, dtype=numpy.uint16)

        # save it with source metadata
        spectral.io.envi.save_classification(destination_filename, destination,
                                             class_names=['No data', 'Data'],
                                             metadata={'data ignore value': 0,
                                                       'map info':
                                                           source.metadata.get(
                                                               'map info')})
github capstone-coal / pycoal / examples / example_sam.py View on Github external
@license:    GNU General Public License version 2

@contact:    coal-capstone@googlegroups.com
'''

import constants
import math
import numpy
import spectral
import matplotlib
import matplotlib.pyplot as plt

# load library
library_filename = constants.LIBRARY_FILENAME_6
library = spectral.open_image(library_filename)

# open the image
image_filename = \
    '../pycoal/tests/images/ang20150422t163638_corr_v1e_img_4000-4010_550' \
    '-560.hdr'

image = spectral.open_image(image_filename)

# access a pixel known
x = 4
y = 7
pixel = image[x, y]

# define a resampler
resample = spectral.BandResampler([x / 1000 for x in image.bands.centers],
                                  library.bands.centers)
github capstone-coal / pycoal / examples / example_splib06.py View on Github external
@copyright:  Copyright (C) 2017-2019 COAL Developers

@license:    GNU General Public License version 2

@contact:    coal-capstone@googlegroups.com
"""

import constants
import numpy
import spectral
from spectral.graphics.colorscale import create_default_color_scale

# Import SPLIB06 as a SPy image and display its dimensions.
library_filename = constants.LIBRARY_FILENAME_6
library = spectral.open_image(library_filename)
library.spectra.shape
# (1365, 224)

# Transpose the image to display vertical samples horizontally and display
# its dimensions.
spectra = numpy.transpose(library.spectra)
spectra.shape
# (224, 1365)

# Create a 256 color scale gradient.
scale = create_default_color_scale(256)

# Generate and display a Python Imaging Library (PIL) image. Arbitrarily
# scale the very small reflectance values by `50` to produce a suitable
# color distribution.
pilspectra = spectral.graphics.make_pil_image(50 * spectra, color_scale=scale)
github arthurmensch / modl / modl / datasets / image.py View on Github external
image = image[..., np.newaxis]
        if scale != 1:
            image = memory.cache(rescale)(image, scale=scale)
        return image
    elif source == 'lisboa':
        image = imread(join(data_dir, 'images', 'lisboa.jpg'), as_grey=gray)
        image = image.astype(np.float32) / 255
        if image.ndim == 2:
            image = image[..., np.newaxis]
        if scale != 1:
            image = memory.cache(rescale)(image, scale=scale)
        return image
    elif source == 'aviris':
        from spectral import open_image

        image = open_image(
            join(data_dir,
                 'aviris',
                 'f100826t01p00r05rdn_b/'
                 'f100826t01p00r05rdn_b_sc01_ort_img.hdr'))
        image = np.array(image.open_memmap(), dtype=np.float32)
        good_bands = list(range(image.shape[2]))
        good_bands.remove(110)
        image = image[:, :, good_bands]
        indices = image == -50
        image[indices] = -1
        image[~indices] -= np.min(image[~indices])
        image[~indices] /= np.max(image[~indices])
        return image
    else:
        raise ValueError('Data source is not known')