Esempio n. 1
0
def image_obj(hdr, img):
    "create a object of the image corresponding to certain header"
    head = envi.read_envi_header(hdr)
    param = envi.gen_params(head)
    param.filename = img  # spectral data file corresponding to .hdr file

    if 'bbl' in head:
        head['bbl'] = [float(b) for b in head['bbl']]
        print(len(head['bbl']))
        good_bands = np.nonzero(
            head['bbl'])[0]  # get good bands only for computation
        bad_bands = np.nonzero(np.array(head['bbl']) == 0)[0]
        print("calculating target signature...")
        t_mean = target_sign(png_img, img_data_obj, channel, good_bands)

    interleave = head['interleave']
    if (interleave == 'bip' or interleave == 'BIP'):
        print("it is a bip")
        from spectral.io.bipfile import BipFile
        img_obj = BipFile(param, head)

    if (interleave == 'bil' or interleave == 'BIL'):
        print("It is a bil file")
        from spectral.io.bilfile import BilFile
        img_obj = BilFile(param, head)

    return img_obj
 def __init__(self, img: BilFile, sceneImg: QImage, imgArr: np.ndarray = None):
     self.img: BilFile = img
     self.sceneImg: QImage = sceneImg
     if imgArr is None:
         self.imgArr = img.asarray().astype(np.float64).copy()
         # normalizacja min - max dla kazdego z bandów
         for i in range(0, self.imgArr.shape[2]):
             self.imgArr[:, :, i] = (self.imgArr[:, :, i] - self.imgArr[:, :, i].min()) / (
                         self.imgArr[:, :, i].max() - self.imgArr[:, :, i].min())
     else:
         self.imgArr = imgArr
def image_obj(hdr, img):
    "create a object of the image corresponding to certain header"

    head = envi.read_envi_header(hdr)
    param = envi.gen_params(head)
    param.filename = img  # spectral data file corresponding to .hdr file

    interleave = head['interleave']
    if (interleave == 'bip' or interleave == 'BIP'):
        print("it is a bip")
        from spectral.io.bipfile import BipFile
        img_obj = BipFile(param, head)

    if (interleave == 'bil' or interleave == 'BIL'):
        print("It is a bil file")
        from spectral.io.bilfile import BilFile
        img_obj = BilFile(param, head)

    return img_obj
Esempio n. 4
0
def create_image(hdr_file, metadata=None, **kwargs):
    '''
    Creates an image file and ENVI header with a memmep array for write access.

    Arguments:

        `hdr_file` (str):

            Header file (with ".hdr" extension) name with path.

        `metadata` (dict):

            Metadata to specify the image file format. The following parameters
            (in ENVI header format) are required, if not specified via
            corresponding keyword arguments: "bands", "lines", "samples",
            and "data type".

    Keyword Arguments:

        `dtype` (numpy dtype or type string):

            The numpy data type with which to store the image.  For example,
            to store the image in 16-bit unsigned integer format, the argument
            could be any of `numpy.uint16`, "u2", "uint16", or "H". If this
            keyword is given, it will override the "data type" parameter in
            the `metadata` argument.

        `force` (bool, False by default):

            If the associated image file or header already exist and `force` is
            True, the files will be overwritten; otherwise, if either of the
            files exist, an exception will be raised.

        `ext` (str):

            The extension to use for the image file.  If not specified, the
            default extension ".img" will be used.  If `ext` is an empty
            string, the image file will have the same name as the header but
            without the ".hdr" extension.

        `interleave` (str):

            Must be one of "bil", "bip", or "bsq". This keyword supercedes the
            value of "interleave" in the metadata argument, if given. If no
            interleave is specified (via keyword or `metadata`), "bip" is
            assumed.

        `shape` (tuple of integers):

            Specifies the number of rows, columns, and bands in the image.
            This keyword should be either of the form (R, C, B) or (R, C),
            where R, C, and B specify the number or rows, columns, and bands,
            respectively. If B is omitted, the number of bands is assumed to
            be one. If this keyword is given, its values supercede the values
            of "bands", "lines", and "samples" if they are present in the
            `metadata` argument.

        `offset` (integer, default 0):

            The offset (in bytes) of image data from the beginning of the file.
            This value supercedes the value of "header offset" in the metadata
            argument (if given).

    Returns:

        `SpyFile` object:

            To access a `numpy.memmap` for the returned `SpyFile` object, call
            the `open_memmap` method of the returned object.

    Examples:

        Creating a new image from metadata::

            >>> md = {'lines': 30,
                      'samples': 40,
                      'bands': 50,
                      'data type': 12}
            >>> img = envi.create_image('new_image.hdr', md)

        Creating a new image via keywords::

            >>> img = envi.create_image('new_image2.hdr',
                                        shape=(30, 40, 50),
                                        dtype=np.uint16)

        Writing to the new image using a memmap interface::

            >>> # Set all band values for a single pixel to 100.
            >>> mm = img.open_memmap(writable=True)
            >>> mm[30, 30] = 100

    '''
    from exceptions import NotImplementedError, TypeError
    import numpy as np
    import os
    import spectral

    force = kwargs.get('force', False)
    img_ext = kwargs.get('ext', '.img')
    memmap_mode = kwargs.get('memmap_mode', 'w+')
    (hdr_file, img_file) = check_new_filename(hdr_file, img_ext, force)

    default_metadata = {'header offset': 0, 'interleave': 'bip'}
    
    if metadata is None:
        metadata = default_metadata
    else:
        default_metadata.update(metadata)
        metadata = default_metadata

    # Keyword args supercede metadata dict
    if 'shape' in kwargs:
        shape = kwargs['shape']
        metadata['lines'] = shape[0]
        metadata['samples'] = shape[1]
        if len(shape) == 3:
            metadata['bands'] = shape[2]
        else:
            metadata['bands'] = 1
    if 'offset' in kwargs:
        metadata['offset'] = kwargs['offset']
    if 'dtype' in kwargs:
        metadata['data type'] = dtype_to_envi[np.dtype(kwargs['dtype']).char]

    metadata['byte order'] = spectral.byte_order

    # Verify minimal set of parameters have been provided
    if 'lines' not in metadata:
        raise Exception('Number of image rows is not defined.')
    elif 'samples' not in metadata:
        raise Exception('Number of image columns is not defined.')
    elif 'bands' not in metadata:
        raise Exception('Number of image bands is not defined.')
    elif 'samples' not in metadata:
        raise Exception('Number of image columns is not defined.')
    elif 'data type' not in metadata:
        raise Exception('Image data type is not defined.')

    params = gen_params(metadata)
    dt = np.dtype(params.dtype).char
    params.filename = img_file
        
    is_library = False
    if metadata.get('file type') == 'ENVI Spectral Library':
        is_library = True
        raise NotImplementedError('ENVI Spectral Library cannot be created ')

    # Create the appropriate object type -> the memmap (=image) will be
    # created on disk
    inter = metadata["interleave"]
    (R, C, B) = (params.nrows, params.ncols, params.nbands)
    if inter.lower() not in ['bil', 'bip', 'bsq']:
        raise ValueError('Invalid interleave specified: %s.' % str(inter))
    if inter.lower() == 'bil':
        from spectral.io.bilfile import BilFile
        memmap = np.memmap(img_file, dtype=dt, mode=memmap_mode,
                           offset=params.offset, shape=(R, B, C))
        img = BilFile(params, metadata)
        img._memmap = memmap
    elif inter.lower() == 'bip':
        from spectral.io.bipfile import BipFile
        memmap = np.memmap(img_file, dtype=dt, mode=memmap_mode,
                           offset=params.offset, shape=(R, C, B))
        img = BipFile(params, metadata)
        img._memmap = memmap
    else:
        from spectral.io.bsqfile import BsqFile
        memmap = np.memmap(img_file, dtype=dt, mode=memmap_mode,
                           offset=params.offset, shape=(B, R, C))
        img = BsqFile(params, metadata)
        img._memmap = memmap

    # Write the header file after the image to assure write success
    write_envi_header(hdr_file, metadata, is_library=is_library)
    return img
Esempio n. 5
0
def open(file, image=None):
    '''
    Opens an image or spectral library with an associated ENVI HDR header file.

    Arguments:

        `file` (str):

            Name of the header file for the image.

        `image` (str):

            Optional name of the associated image data file.

    Returns:

        :class:`spectral.SpyFile` or :class:`spectral.io.envi.SpectralLibrary`
        object.

    Raises:

        TypeError, IOError.

    If the specified file is not found in the current directory, all
    directories listed in the SPECTRAL_DATA environment variable will be
    searched until the file is found.  Based on the name of the header file,
    this function will search for the image file in the same directory as the
    header, looking for a file with the same name as the header but different
    extension. Extensions recognized are .img, .dat, .sli, and no extension.
    Capitalized versions of the file extensions are also searched.
    '''

    import os
    from exceptions import IOError, TypeError
    from spyfile import find_file_path
    import numpy
    import spectral

    headerPath = find_file_path(file)
    h = read_envi_header(headerPath)

    p = gen_params(h)

    inter = h["interleave"]

    #  Validate image file name
    if not image:
        #  Try to determine the name of the image file
        headerDir = os.path.split(headerPath)
        if headerPath[-4:].lower() == '.hdr':
            headerPathTitle = headerPath[:-4]
            exts = ['', 'img', 'IMG', 'dat', 'DAT', 'sli', 'SLI', 'hyspex'] +\
                   [inter.lower(), inter.upper()]
            for ext in exts:
                if len(ext) == 0:
                    testname = headerPathTitle
                else:
                    testname = headerPathTitle + '.' + ext
                if os.path.isfile(testname):
                    image = testname
                    break
        if not image:
            raise IOError('Unable to determine image file name.')
    else:
        image = find_file_path(image)

    p.filename = image

    if h.get('file type') == 'ENVI Spectral Library':
        # File is a spectral library
        data = numpy.fromfile(p.filename, p.dtype, p.ncols * p.nrows)
        data.shape = (p.nrows, p.ncols)
        return SpectralLibrary(data, h, p)

    #  Create the appropriate object type for the interleave format.
    inter = h["interleave"]
    if inter == 'bil' or inter == 'BIL':
        from spectral.io.bilfile import BilFile
        img = BilFile(p, h)
    elif inter == 'bip' or inter == 'BIP':
        from spectral.io.bipfile import BipFile
        img = BipFile(p, h)
    else:
        from spectral.io.bsqfile import BsqFile
        img = BsqFile(p, h)

    img.scale_factor = float(h.get('reflectance scale factor', 1.0))

    # Add band info

    if 'wavelength' in h:
        try:
            img.bands.centers = [float(b) for b in h['wavelength']]
        except:
            pass
    if 'fwhm' in h:
        try:
            img.bands.bandwidths = [float(f) for f in h['fwhm']]
        except:
            pass
    img.bands.band_unit = h.get('wavelength units', "")
    img.bands.band_quantity = "Wavelength"

    return img
Esempio n. 6
0
def create_image(hdr_file, metadata=None, **kwargs):
    '''
    Creates an image file and ENVI header with a memmep array for write access.

    Arguments:

        `hdr_file` (str):

            Header file (with ".hdr" extension) name with path.

        `metadata` (dict):

            Metadata to specify the image file format. The following parameters
            (in ENVI header format) are required, if not specified via
            corresponding keyword arguments: "bands", "lines", "samples",
            and "data type".

    Keyword Arguments:

        `dtype` (numpy dtype or type string):

            The numpy data type with which to store the image.  For example,
            to store the image in 16-bit unsigned integer format, the argument
            could be any of `numpy.uint16`, "u2", "uint16", or "H". If this
            keyword is given, it will override the "data type" parameter in
            the `metadata` argument.

        `force` (bool, False by default):

            If the associated image file or header already exist and `force` is
            True, the files will be overwritten; otherwise, if either of the
            files exist, an exception will be raised.

        `ext` (str):

            The extension to use for the image file.  If not specified, the
            default extension ".img" will be used.  If `ext` is an empty
            string, the image file will have the same name as the header but
            without the ".hdr" extension.

        `interleave` (str):

            Must be one of "bil", "bip", or "bsq". This keyword supercedes the
            value of "interleave" in the metadata argument, if given. If no
            interleave is specified (via keyword or `metadata`), "bip" is
            assumed.

        `shape` (tuple of integers):

            Specifies the number of rows, columns, and bands in the image.
            This keyword should be either of the form (R, C, B) or (R, C),
            where R, C, and B specify the number or rows, columns, and bands,
            respectively. If B is omitted, the number of bands is assumed to
            be one. If this keyword is given, its values supercede the values
            of "bands", "lines", and "samples" if they are present in the
            `metadata` argument.

        `offset` (integer, default 0):

            The offset (in bytes) of image data from the beginning of the file.
            This value supercedes the value of "header offset" in the metadata
            argument (if given).

    Returns:

        `SpyFile` object:

            To access a `numpy.memmap` for the returned `SpyFile` object, call
            the `open_memmap` method of the returned object.

    Examples:

        Creating a new image from metadata::

            >>> md = {'lines': 30,
                      'samples': 40,
                      'bands': 50,
                      'data type': 12}
            >>> img = envi.create_image('new_image.hdr', md)

        Creating a new image via keywords::

            >>> img = envi.create_image('new_image2.hdr',
                                        shape=(30, 40, 50),
                                        dtype=np.uint16)

        Writing to the new image using a memmap interface::

            >>> # Set all band values for a single pixel to 100.
            >>> mm = img.open_memmap(writable=True)
            >>> mm[30, 30] = 100

    '''
    import numpy as np
    import os
    import spectral

    force = kwargs.get('force', False)
    img_ext = kwargs.get('ext', '.img')
    memmap_mode = kwargs.get('memmap_mode', 'w+')
    (hdr_file, img_file) = check_new_filename(hdr_file, img_ext, force)

    default_metadata = {'header offset': 0, 'interleave': 'bip'}

    if metadata is None:
        metadata = default_metadata
    else:
        default_metadata.update(metadata)
        metadata = default_metadata

    # Keyword args supercede metadata dict
    if 'shape' in kwargs:
        shape = kwargs['shape']
        metadata['lines'] = shape[0]
        metadata['samples'] = shape[1]
        if len(shape) == 3:
            metadata['bands'] = shape[2]
        else:
            metadata['bands'] = 1
    if 'offset' in kwargs:
        metadata['header offset'] = kwargs['offset']
    if 'dtype' in kwargs:
        metadata['data type'] = dtype_to_envi[np.dtype(kwargs['dtype']).char]
    if 'interleave' in kwargs:
        metadata['interleave'] = kwargs['interleave']

    metadata['byte order'] = spectral.byte_order

    # Verify minimal set of parameters have been provided
    if 'lines' not in metadata:
        raise EnviException('Number of image rows is not defined.')
    elif 'samples' not in metadata:
        raise EnviException('Number of image columns is not defined.')
    elif 'bands' not in metadata:
        raise EnviException('Number of image bands is not defined.')
    elif 'samples' not in metadata:
        raise EnviException('Number of image columns is not defined.')
    elif 'data type' not in metadata:
        raise EnviException('Image data type is not defined.')

    params = gen_params(metadata)
    dt = np.dtype(params.dtype).char
    _validate_dtype(dt)
    params.filename = img_file

    is_library = False
    if metadata.get('file type') == 'ENVI Spectral Library':
        is_library = True
        raise NotImplementedError('ENVI Spectral Library cannot be created ')

    # Create the appropriate object type -> the memmap (=image) will be
    # created on disk
    inter = metadata["interleave"]
    (R, C, B) = (params.nrows, params.ncols, params.nbands)
    if inter.lower() not in ['bil', 'bip', 'bsq']:
        raise ValueError('Invalid interleave specified: %s.' % str(inter))
    if inter.lower() == 'bil':
        from spectral.io.bilfile import BilFile
        memmap = np.memmap(img_file,
                           dtype=dt,
                           mode=memmap_mode,
                           offset=params.offset,
                           shape=(R, B, C))
        img = BilFile(params, metadata)
        img._memmap = memmap
    elif inter.lower() == 'bip':
        from spectral.io.bipfile import BipFile
        memmap = np.memmap(img_file,
                           dtype=dt,
                           mode=memmap_mode,
                           offset=params.offset,
                           shape=(R, C, B))
        img = BipFile(params, metadata)
        img._memmap = memmap
    else:
        from spectral.io.bsqfile import BsqFile
        memmap = np.memmap(img_file,
                           dtype=dt,
                           mode=memmap_mode,
                           offset=params.offset,
                           shape=(B, R, C))
        img = BsqFile(params, metadata)
        img._memmap = memmap

    # Write the header file after the image to assure write success
    write_envi_header(hdr_file, metadata, is_library=is_library)
    return img
Esempio n. 7
0
def open(file, image=None):
    '''
    Opens an image or spectral library with an associated ENVI HDR header file.

    Arguments:

        `file` (str):

            Name of the header file for the image.

        `image` (str):

            Optional name of the associated image data file.

    Returns:

        :class:`spectral.SpyFile` or :class:`spectral.io.envi.SpectralLibrary`
        object.

    Raises:

        TypeError, EnviDataFileNotFoundError

    If the specified file is not found in the current directory, all
    directories listed in the SPECTRAL_DATA environment variable will be
    searched until the file is found.  Based on the name of the header file,
    this function will search for the image file in the same directory as the
    header, looking for a file with the same name as the header but different
    extension. Extensions recognized are .img, .dat, .sli, and no extension.
    Capitalized versions of the file extensions are also searched.
    '''

    import os
    from .spyfile import find_file_path
    import numpy
    import spectral

    header_path = find_file_path(file)
    h = read_envi_header(header_path)
    check_compatibility(h)
    p = gen_params(h)

    inter = h["interleave"]

    #  Validate image file name
    if not image:
        #  Try to determine the name of the image file
        (header_path_title, header_ext) = os.path.splitext(header_path)
        if header_ext.lower() == '.hdr':
            exts = [ext.lower() for ext in KNOWN_EXTS] + [inter.lower()]
            exts = [''] + exts + [ext.upper() for ext in exts]
            for ext in exts:
                if len(ext) == 0:
                    testname = header_path_title
                else:
                    testname = header_path_title + '.' + ext
                if os.path.isfile(testname):
                    image = testname
                    break
        if not image:
            msg = 'Unable to determine the ENVI data file name for the ' \
              'given header file. You can specify the data file by passing ' \
              'its name as the optional `image` argument to envi.open.'
            raise EnviDataFileNotFoundError(msg)
    else:
        image = find_file_path(image)

    p.filename = image

    if h.get('file type') == 'ENVI Spectral Library':
        # File is a spectral library
        data = numpy.fromfile(p.filename, p.dtype, p.ncols * p.nrows)
        data.shape = (p.nrows, p.ncols)
        return SpectralLibrary(data, h, p)

    #  Create the appropriate object type for the interleave format.
    inter = h["interleave"]
    if inter == 'bil' or inter == 'BIL':
        from spectral.io.bilfile import BilFile
        img = BilFile(p, h)
    elif inter == 'bip' or inter == 'BIP':
        from spectral.io.bipfile import BipFile
        img = BipFile(p, h)
    else:
        from spectral.io.bsqfile import BsqFile
        img = BsqFile(p, h)

    img.scale_factor = float(h.get('reflectance scale factor', 1.0))

    # Add band info

    if 'wavelength' in h:
        try:
            img.bands.centers = [float(b) for b in h['wavelength']]
        except:
            pass
    if 'fwhm' in h:
        try:
            img.bands.bandwidths = [float(f) for f in h['fwhm']]
        except:
            pass
    img.bands.band_unit = h.get('wavelength units', None)

    if 'bbl' in h:
        try:
            h['bbl'] = [int(float(b)) for b in h['bbl']]
        except:
            print('Unable to parse bad band list (bbl) in header as integers.')
    return img
Esempio n. 8
0
def open(file, image=None):
    '''
    Opens an image or spectral library with an associated ENVI HDR header file.

    Arguments:

        `file` (str):

            Name of the header file for the image.

        `image` (str):

            Optional name of the associated image data file.

    Returns:

        :class:`spectral.SpyFile` or :class:`spectral.io.envi.SpectralLibrary`
        object.

    Raises:

        TypeError, EnviDataFileNotFoundError

    If the specified file is not found in the current directory, all
    directories listed in the SPECTRAL_DATA environment variable will be
    searched until the file is found.  Based on the name of the header file,
    this function will search for the image file in the same directory as the
    header, looking for a file with the same name as the header but different
    extension. Extensions recognized are .img, .dat, .sli, and no extension.
    Capitalized versions of the file extensions are also searched.
    '''

    import os
    from .spyfile import find_file_path
    import numpy
    import spectral

    header_path = find_file_path(file)
    h = read_envi_header(header_path)
    check_compatibility(h)
    p = gen_params(h)

    inter = h["interleave"]

    #  Validate image file name
    if not image:
        #  Try to determine the name of the image file
        (header_path_title, header_ext) = os.path.splitext(header_path)
        if header_ext.lower() == '.hdr':
            exts = [ext.lower() for ext in KNOWN_EXTS] + [inter.lower()]
            exts = [''] + exts + [ext.upper() for ext in exts]
            for ext in exts:
                if len(ext) == 0:
                    testname = header_path_title
                else:
                    testname = header_path_title + '.' + ext
                if os.path.isfile(testname):
                    image = testname
                    break
        if not image:
            msg = 'Unable to determine the ENVI data file name for the ' \
              'given header file. You can specify the data file by passing ' \
              'its name as the optional `image` argument to envi.open.'
            raise EnviDataFileNotFoundError(msg)
    else:
        image = find_file_path(image)

    p.filename = image

    if h.get('file type') == 'ENVI Spectral Library':
        # File is a spectral library
        data = numpy.fromfile(p.filename, p.dtype, p.ncols * p.nrows)
        data.shape = (p.nrows, p.ncols)
        return SpectralLibrary(data, h, p)

    #  Create the appropriate object type for the interleave format.
    inter = h["interleave"]
    if inter == 'bil' or inter == 'BIL':
        from spectral.io.bilfile import BilFile
        img = BilFile(p, h)
    elif inter == 'bip' or inter == 'BIP':
        from spectral.io.bipfile import BipFile
        img = BipFile(p, h)
    else:
        from spectral.io.bsqfile import BsqFile
        img = BsqFile(p, h)

    img.scale_factor = float(h.get('reflectance scale factor', 1.0))

    # Add band info

    if 'wavelength' in h:
        try:
            img.bands.centers = [float(b) for b in h['wavelength']]
        except:
            pass
    if 'fwhm' in h:
        try:
            img.bands.bandwidths = [float(f) for f in h['fwhm']]
        except:
            pass
    img.bands.band_unit = h.get('wavelength units', None)

    if 'bbl' in h:
        try:
            h['bbl'] = [int(float(b)) for b in h['bbl']]
        except:
            print('Unable to parse bad band list (bbl) in header as integers.')
    return img
Esempio n. 9
0
def open(file, image=None):
    '''
    Opens an image or spectral library with an associated ENVI HDR header file.

    Arguments:

        `file` (str):

            Name of the header file for the image.

        `image` (str):

            Optional name of the associated image data file.

    Returns:

        :class:`spectral.SpyFile` or :class:`spectral.io.envi.SpectralLibrary`
        object.

    Raises:

        TypeError, IOError.

    If the specified file is not found in the current directory, all
    directories listed in the SPECTRAL_DATA environment variable will be
    searched until the file is found.  Based on the name of the header file,
    this function will search for the image file in the same directory as the
    header, looking for a file with the same name as the header but different
    extension. Extensions recognized are .img, .dat, .sli, and no extension.
    Capitalized versions of the file extensions are also searched.
    '''

    import os
    from .spyfile import find_file_path
    import numpy
    import spectral

    headerPath = find_file_path(file)
    h = read_envi_header(headerPath)

    p = gen_params(h)

    inter = h["interleave"]

    #  Validate image file name
    if not image:
        #  Try to determine the name of the image file
        headerDir = os.path.split(headerPath)
        if headerPath[-4:].lower() == '.hdr':
            headerPathTitle = headerPath[:-4]
            exts = ['', 'img', 'IMG', 'dat', 'DAT', 'sli', 'SLI', 'hyspex'] +\
                   [inter.lower(), inter.upper()]
            for ext in exts:
                if len(ext) == 0:
                    testname = headerPathTitle
                else:
                    testname = headerPathTitle + '.' + ext
                if os.path.isfile(testname):
                    image = testname
                    break
        if not image:
            raise IOError('Unable to determine image file name.')
    else:
        image = find_file_path(image)

    p.filename = image

    if h.get('file type') == 'ENVI Spectral Library':
        # File is a spectral library
        data = numpy.fromfile(p.filename, p.dtype, p.ncols * p.nrows)
        data.shape = (p.nrows, p.ncols)
        return SpectralLibrary(data, h, p)

    #  Create the appropriate object type for the interleave format.
    inter = h["interleave"]
    if inter == 'bil' or inter == 'BIL':
        from spectral.io.bilfile import BilFile
        img = BilFile(p, h)
    elif inter == 'bip' or inter == 'BIP':
        from spectral.io.bipfile import BipFile
        img = BipFile(p, h)
    else:
        from spectral.io.bsqfile import BsqFile
        img = BsqFile(p, h)

    img.scale_factor = float(h.get('reflectance scale factor', 1.0))

    # Add band info

    if 'wavelength' in h:
        try:
            img.bands.centers = [float(b) for b in h['wavelength']]
        except:
            pass
    if 'fwhm' in h:
        try:
            img.bands.bandwidths = [float(f) for f in h['fwhm']]
        except:
            pass
    img.bands.band_unit = h.get('wavelength units', "")
    img.bands.band_quantity = "Wavelength"

    return img
Esempio n. 10
0
def create_image(hdr_file, metadata, **kwargs):
    '''
    Creates an image file and ENVI header with a memmep array for write access.

    Arguments:

        `hdr_file` (str):

            Header file (with ".hdr" extension) name with path.

        `metadata` (dict):

            Metadata to specify the image file format.  The following paramters
            (in ENVI header format) are required: "bands", "lines", "samples",
            "header offset", and "data type".

    Keyword Arguments:

        `dtype` (numpy dtype or type string):

            The numpy data type with which to store the image.  For example,
            to store the image in 16-bit unsigned integer format, the argument
            could be any of `numpy.uint16`, "u2", "uint16", or "H". If this
            keyword is given, it will override the "data type" parameter in
            the `metadata` argument.

        `force` (bool, False by default):

            If the associated image file or header already exist and `force` is
            True, the files will be overwritten; otherwise, if either of the
            files exist, an exception will be raised.

        `ext` (str):

            The extension to use for the image file.  If not specified, the
            default extension ".img" will be used.  If `ext` is an empty
            string, the image file will have the same name as the header but
            without the ".hdr" extension.

        `memmap_mode` (str):

            Mode of img.memmap ("w+" by default). See numpy.memmap for further
            information.

    Returns:

        `SpyFile` object:

            The returned SpyFile subclass object will have a `numpy.memmmap`
            object member named `memmap`, which can be used for direct access
            to the memory-mapped file data.
    '''
    from exceptions import NotImplementedError, TypeError
    import numpy as np
    import os
    import spectral

    force = kwargs.get('force', False)
    img_ext = kwargs.get('ext', '.img')
    memmap_mode = kwargs.get('memmap_mode', 'w+')
    (hdr_file, img_file) = check_new_filename(hdr_file, img_ext, force)

    metadata = metadata.copy()
    params = gen_params(metadata)
    if kwargs.get('dtype'):
        metadata['data type'] = dtype_to_envi[dtype(kwargs['dtype']).char]
        dt = np.dtype(kwargs['dtype']).char
    else:
        dt = np.dtype(params.dtype).char
    metadata['byte order'] = spectral.byte_order
    params.filename = img_file

    is_library = False
    if metadata.get('file type') == 'ENVI Spectral Library':
        is_library = True
        raise NotImplementedError('ENVI Spectral Library cannot be created ')

    # Create the appropriate object type -> the memmap (=image) will be
    # created on disk
    inter = metadata["interleave"]
    (R, C, B) = (params.nrows, params.ncols, params.nbands)
    if inter.lower() not in ['bil', 'bip', 'bsq']:
        raise ValueError('Invalid interleave specified: %s.' % str(inter))
    if inter.lower() == 'bil':
        from spectral.io.bilfile import BilFile
        memmap = np.memmap(img_file, dtype=dt, mode=memmap_mode,
                           offset=params.offset, shape=(R, B, C))
        img = BilFile(params, metadata)
        img.memmap = memmap
    elif inter.lower() == 'bip':
        from spectral.io.bipfile import BipFile
        memmap = np.memmap(img_file, dtype=dt, mode=memmap_mode,
                           offset=params.offset, shape=(R, C, B))
        img = BipFile(params, metadata)
        img.memmap = memmap
    else:
        from spectral.io.bsqfile import BsqFile
        memmap = np.memmap(img_file, dtype=dt, mode=memmap_mode,
                           offset=params.offset, shape=(B, R, C))
        img = BsqFile(params, metadata)
        img.memmap = memmap

    # Write the header file after the image to assure write success
    write_envi_header(hdr_file, metadata, is_library=is_library)
    return img