read all raster bands into a numpy ndarray

        Returns
        -------
        numpy.ndarray
            the array containing all raster data
198839
def array(self):
        
        if self.bands == 1:
            return self.matrix()
        else:
            arr = self.raster.ReadAsArray().transpose(1, 2, 0)
            if isinstance(self.nodata, list):
                for i in range(0, self.bands):
                    arr[:, :, i][arr[:, :, i] == self.nodata[i]] = np.nan
            else:
                arr[arr == self.nodata] = np.nan
            return arr
593040
def numpy_buffer(ndarray):
    """"""
    # Credits to: https://github.com/joblib/joblib/blob/04b001861e1dd03a857b7b419c336de64e05714c/joblib/hashing.py

    if isinstance(ndarray, (pd.Series, pd.DataFrame)):
        ndarray = ndarray.values

    if ndarray.flags.c_contiguous:
        obj_c_contiguous = ndarray
    elif ndarray.flags.f_contiguous:
        obj_c_contiguous = ndarray.T
    else:
        obj_c_contiguous = ndarray.flatten()

    obj_c_contiguous = obj_c_contiguous.view(np.uint8)

    if hasattr(np, 'getbuffer'):
        return np.getbuffer(obj_c_contiguous)
    else:
        return memoryview(obj_c_contiguous)
635791
def _stack_bands(one, other):
    # type: (_Raster, _Raster) -> _Raster
    
    assert set(one.band_names).intersection(set(other.band_names)) == set()

    # We raise an error in the bands are the same. See above.
    if one.band_names == other.band_names:
        raise ValueError("rasters have the same bands, use another merge strategy")

    # Apply "or" to the mask in the same way rasterio does, see
    # https://mapbox.github.io/rasterio/topics/masks.html#dataset-masks
    # In other words, mask the values that are already masked in either
    # of the two rasters, since one mask per band is not supported
    new_mask = np.ma.getmaskarray(one.image)[0] | np.ma.getmaskarray(other.image)[0]

    # Concatenate the data along the band axis and apply the mask
    new_image = np.ma.masked_array(
        np.concatenate([
            one.image.data,
            other.image.data
        ]),
        mask=[new_mask] * (one.image.shape[0] + other.image.shape[0])
    )
    new_bands = one.band_names + other.band_names

    # We don't copy image and mask here, due to performance issues,
    # this output should not use without eventually being copied
    # In this context we are copying the object in the end of merge_all merge_first and merge
    return _Raster(image=new_image, band_names=new_bands)
384795
def _merge_common_bands(rasters):
    # type: (List[_Raster]) -> List[_Raster]
    
    # Compute band order
    all_bands = IndexedSet([rs.band_names[0] for rs in rasters])

    def key(rs):
        return all_bands.index(rs.band_names[0])

    rasters_final = []  # type: List[_Raster]
    for band_name, rasters_group in groupby(sorted(rasters, key=key), key=key):
        rasters_final.append(reduce(_fill_pixels, rasters_group))

    return rasters_final
537283
def array(self):
        
        return numpy.array([self[sid].array for sid in sorted(self)])
266229
def _from_numpy(data, origin=None, spacing=None, direction=None, has_components=False, is_rgb=False):
    
    if is_rgb: has_components = True
    ndim = data.ndim
    if has_components:
        ndim -= 1
    dtype = data.dtype.name
    ptype = _npy_to_itk_map[dtype]

    data = np.array(data)

    if origin is None: origin = tuple([0.]*ndim)
    if spacing is None: spacing = tuple([1.]*ndim)
    if direction is None: direction = np.eye(ndim)

    libfn = utils.get_lib_fn('fromNumpy%s%i' % (_ntype_type_map[dtype], ndim))

    if not has_components:
        itk_image = libfn(data, data.shape[::-1])
        ants_image = iio.ANTsImage(pixeltype=ptype, dimension=ndim, components=1, pointer=itk_image)
        ants_image.set_origin(origin)
        ants_image.set_spacing(spacing)
        ants_image.set_direction(direction)
        ants_image._ndarr = data
    else:
        arrays = [data[i,...].copy() for i in range(data.shape[0])]
        data_shape = arrays[0].shape
        ants_images = []
        for i in range(len(arrays)):
            tmp_ptr = libfn(arrays[i], data_shape[::-1])
            tmp_img = iio.ANTsImage(pixeltype=ptype,
                                    dimension=ndim,
                                    components=1,
                                    pointer=tmp_ptr)
            tmp_img.set_origin(origin)
            tmp_img.set_spacing(spacing)
            tmp_img.set_direction(direction)
            tmp_img._ndarr = arrays[i]
            ants_images.append(tmp_img)
        ants_image = utils.merge_channels(ants_images)
        if is_rgb: ants_image = ants_image.vector_to_rgb()
    return ants_image
318811
def run(self):
        

        self.output('PanSharpened Image processing started for bands %s' % '-'.join(map(str, self.bands)),
                    normal=True, arrow=True)

        bands = self._read_bands()
        image_data = self._get_image_data()

        new_bands = self._generate_new_bands(image_data['shape'])

        bands[:3] = self._rescale(bands[:3])
        new_bands.append(numpy.empty(image_data['shape'], dtype=numpy.uint16))

        self._warp(image_data, bands, new_bands)

        # Bands are no longer needed
        del bands

        # Calculate pan band
        pan = self._pansize(new_bands)
        del self.bands[self.band8]
        del new_bands[self.band8]

        rasterio_options = {
            'driver': 'GTiff',
            'width': image_data['shape'][1],
            'height': image_data['shape'][0],
            'count': 3,
            'dtype': numpy.uint8,
            'nodata': 0,
            'transform': image_data['dst_transform'],
            'photometric': 'RGB',
            'crs': self.dst_crs
        }

        return self._write_to_file(new_bands, pan, **rasterio_options)
354045
def data():
    
    from keras.datasets import mnist
    from keras.utils import np_utils
    (x_train, y_train), (x_test, y_test) = mnist.load_data()
    x_train = x_train.reshape(60000, 784)
    x_test = x_test.reshape(10000, 784)
    x_train = x_train.astype('float32')
    x_test = x_test.astype('float32')
    x_train /= 255
    x_test /= 255
    nb_classes = 10
    y_train = np_utils.to_categorical(y_train, nb_classes)
    y_test = np_utils.to_categorical(y_test, nb_classes)
    return x_train, y_train, x_test, y_test
1353433
def dimension_values(self, dim, expanded=True, flat=True):
        
        dim_idx = self.get_dimension_index(dim)
        if not expanded and dim_idx == 0:
            return np.array(range(self.data.shape[1]))
        elif not expanded and dim_idx == 1:
            return np.array(range(self.data.shape[0]))
        elif dim_idx in [0, 1]:
            values = np.mgrid[0:self.data.shape[1], 0:self.data.shape[0]][dim_idx]
            return values.flatten() if flat else values
        elif dim_idx == 2:
            arr = self.data.T
            return arr.flatten() if flat else arr
        else:
            return super(Raster, self).dimension_values(dim)
964188
def ndvi(self):
        
        red, nir = self.reflectance(3), self.reflectance(4)
        ndvi = self._divide_zero((nir - red), (nir + red), nan)

        return ndvi
1255703
def toarray(self):
        
        A = dot(self.lmbda, khatrirao(tuple(self.U)).T)
        return A.reshape(self.shape)
721554
def _as_array(arr, dtype=None):
    
    if arr is None:
        return None
    if isinstance(arr, np.ndarray) and dtype is None:
        return arr
    if isinstance(arr, integer_types + (float,)):
        arr = [arr]
    out = np.asarray(arr)
    if dtype is not None:
        if out.dtype != dtype:
            out = out.astype(dtype)
    if out.dtype not in _ACCEPTED_ARRAY_DTYPES:
        raise ValueError("'arr' seems to have an invalid dtype: "
                         "{0:s}".format(str(out.dtype)))
    return out
689829
def getPixels(self):
        
        array = self.toArray()
        (width, height, depth) = array.size
        for x in range(width):
            for y in range(height):
                yield Pixel(array, x, y)
354407
def join(rasters):
    

    raster = rasters[0]  # using the first raster to understand what is the type of data we have
    mask_band = None
    nodata = None
    with raster._raster_opener(raster.source_file) as r:
        nodata = r.nodata
        mask_flags = r.mask_flag_enums
    per_dataset_mask = all([rasterio.enums.MaskFlags.per_dataset in flags for flags in mask_flags])
    if per_dataset_mask and nodata is None:
        mask_band = 0
    return GeoRaster2.from_rasters(rasters, relative_to_vrt=False, nodata=nodata, mask_band=mask_band)
629552
def array(self):
        
        return np.eye(self.M, self.N, self.k)
536667
def _pixel_data(image):
    
    # Test for PIL.Image and numpy.ndarray without requiring that cv2 or PIL
    # are installed.
    if 'PIL.' in str(type(image)):
        if 'L' != image.mode:
            image = image.convert('L')
        pixels = image.tobytes()
        width, height = image.size
    elif 'numpy.ndarray' in str(type(image)):
        if 3 == len(image.shape):
            # Take just the first channel
            image = image[:, :, 0]
        if 'uint8' != str(image.dtype):
            image = image.astype('uint8')
        try:
            pixels = image.tobytes()
        except AttributeError:
            # `numpy.ndarray.tobytes()` introduced in `numpy` 1.9.0 - use the
            # older `tostring` method.
            pixels = image.tostring()
        height, width = image.shape[:2]
    else:
        # image should be a tuple (pixels, width, height)
        pixels, width, height = image

        # Check dimensions
        if 0 != len(pixels) % (width * height):
            raise PyZbarError(
                (
                    'Inconsistent dimensions: image data of {0} bytes is not '
                    'divisible by (width x height = {1})'
                ).format(len(pixels), (width * height))
            )

    # Compute bits-per-pixel
    bpp = 8 * len(pixels) // (width * height)
    if 8 != bpp:
        raise PyZbarError(
            'Unsupported bits-per-pixel [{0}]. Only [8] is supported.'.format(
                bpp
            )
        )

    return pixels, width, height
101921
def run(self):
        

        self.output('Image processing started for bands %s' % '-'.join(map(str, self.bands)), normal=True, arrow=True)

        bands = self._read_bands()
        image_data = self._get_image_data()

        new_bands = self._generate_new_bands(image_data['shape'])

        self._warp(image_data, bands, new_bands)

        # Bands are no longer needed
        del bands

        rasterio_options = {
            'driver': 'GTiff',
            'width': image_data['shape'][1],
            'height': image_data['shape'][0],
            'count': 3,
            'dtype': numpy.uint8,
            'nodata': 0,
            'transform': image_data['dst_transform'],
            'photometric': 'RGB',
            'crs': self.dst_crs
        }

        return self._write_to_file(new_bands, **rasterio_options)