Get masked array from input GDAL Band

    Parameters
    ----------
    b : gdal.Band 
        Input GDAL Band 
    
    Returns
    -------
    np.ma.array    
        Masked array containing raster values
174940
def b_getma(b):
    
    b_ndv = get_ndv_b(b)
    #bma = np.ma.masked_equal(b.ReadAsArray(), b_ndv)
    #This is more appropriate for float, handles precision issues
    bma = np.ma.masked_values(b.ReadAsArray(), b_ndv)
    return bma
413888
def maskedFilter(arr, mask, ksize=30, fill_mask=True,
                 fn='median'):
    '''
    
    '''

    if fill_mask:
        mask1 = mask
        out = arr
    else:
        mask1 = ~mask
        out = np.full_like(arr, fill_value=np.nan)
    mask2 = ~mask

    if fn == 'mean':
        _calcMean(arr, mask1, mask2, out, ksize // 2)
    else:
        buff = np.empty(shape=(ksize * ksize), dtype=arr.dtype)
        _calcMedian(arr, mask1, mask2, out, ksize // 2, buff)
    return out
263103
def mask_image_data(data):
    """"""
    if data.bands.size in (2, 4):
        if not np.issubdtype(data.dtype, np.integer):
            raise ValueError("Only integer datatypes can be used as a mask.")
        mask = data.data[-1, :, :] == np.iinfo(data.dtype).min
        data = data.astype(np.float64)
        masked_data = da.stack([da.where(mask, np.nan, data.data[i, :, :])
                                for i in range(data.shape[0])])
        data.data = masked_data
        data = data.sel(bands=BANDS[data.bands.size - 1])
    return data
59359
def array2mask(cls, array=None, **kwargs):
        """"""
        kwargs['dtype'] = bool
        if array is None:
            return numpy.ndarray.__new__(cls, 0, **kwargs)
        return numpy.asarray(array, **kwargs).view(cls)
1884
def read_band_blocks(self, blocksize=CHUNK_SIZE):
        """"""
        # For sentinel 1 data, the block are 1 line, and dask seems to choke on that.
        band = self.filehandle

        shape = band.shape
        token = tokenize(blocksize, band)
        name = 'read_band-' + token
        dskx = dict()
        if len(band.block_shapes) != 1:
            raise NotImplementedError('Bands with multiple shapes not supported.')
        else:
            chunks = band.block_shapes[0]

        def do_read(the_band, the_window, the_lock):
            with the_lock:
                return the_band.read(1, None, window=the_window)

        for ji, window in band.block_windows(1):
            dskx[(name, ) + ji] = (do_read, band, window, self.read_lock)

        res = da.Array(dskx, name, shape=list(shape),
                       chunks=chunks,
                       dtype=band.dtypes[0])
        return DataArray(res, dims=('y', 'x'))
426155
def mask_by_value(self, nodata):
        
        return self.copy_with(image=np.ma.masked_array(self.image.data, mask=self.image.data == nodata))
731516
def gdal2np_dtype(b):
    
    dt_dict = gdal_array.codes
    if isinstance(b, str):
        b = gdal.Open(b)
    if isinstance(b, gdal.Dataset):
        b = b.GetRasterBand(1)
    if isinstance(b, gdal.Band):
        b = b.DataType
    if isinstance(b, int):
        np_dtype = dt_dict[b]
    else:
        np_dtype = None
        print("Input must be GDAL Dataset or RasterBand object")
    return np_dtype
611726
def transpose(self, *args, **kwargs):
        
        tdata = np.transpose(self.data, *args, **kwargs)
        tmask = np.transpose(self.mask, *args, **kwargs) if is_an_array(self.mask) else self.mask
        return ArrayWithMask(tdata, tmask, self.fill_value)
1246393
def _mask_to_bytes(self, mask):
        
        chunks = []
        shiftmask = (2 ** 64) - 1
        for x in range(16):
            chunks.append(struct.pack('<Q', mask & shiftmask))
            mask >>= 64
        return mitogen.core.b('').join(chunks)
702149
def from_bytes(cls, image_bytes, affine, crs, band_names=None):
        
        b = io.BytesIO(image_bytes)
        image = imageio.imread(b)
        roll = np.rollaxis(image, 2)
        if band_names is None:
            band_names = [0, 1, 2]
        elif isinstance(band_names, str):
            band_names = [band_names]

        return GeoRaster2(image=roll[:3, :, :], affine=affine, crs=crs, band_names=band_names)
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)
755186
def get_xy_ma(bma, gt, stride=1, origmask=True, newmask=None):
    
    pX = np.arange(0, bma.shape[1], stride)
    pY = np.arange(0, bma.shape[0], stride)
    psamp = np.meshgrid(pX, pY)
    #if origmask:
    #    psamp = np.ma.array(psamp, mask=np.ma.getmaskarray(bma), fill_value=0)
    mX, mY = pixelToMap(psamp[0], psamp[1], gt)
    mask = None
    if origmask:
        mask = np.ma.getmaskarray(bma)[::stride]
    if newmask is not None:
        mask = newmask[::stride]
    mX = np.ma.array(mX, mask=mask, fill_value=0)
    mY = np.ma.array(mY, mask=mask, fill_value=0)
    return mX, mY
911155
def _apply_mask(
    data: np.ndarray,
    encoded_fill_values: list,
    decoded_fill_value: Any,
    dtype: Any,
) -> np.ndarray:
    """"""
    data = np.asarray(data, dtype=dtype)
    condition = False
    for fv in encoded_fill_values:
        condition |= data == fv
    return np.where(condition, decoded_fill_value, data)
854125
def _extract_intensities(image, mask = slice(None)):
    
    return numpy.array(image, copy=True)[mask].ravel()
845455
def mdaOnes(shap, dtype=numpy.float, mask=None):
    
    res = MaskedDistArray(shap, dtype)
    res[:] = 1
    res.mask = mask
    return res
1200663
def masked(self) -> np.ndarray:
        """"""
        arr = self[:]
        arr.shape = self.shape
        arr = wt_kit.share_nans(arr, *self.parent.channels)[0]
        return np.nanmean(
            arr, keepdims=True, axis=tuple(i for i in range(self.ndim) if self.shape[i] == 1)
        )
631661
def fill_array(dstarr, order, r, g, b, a):
    
    # TODO: can we make this more efficient?
    dtype = dstarr.dtype
    maxv = np.iinfo(dtype).max
    bgval = dict(A=int(maxv * a), R=int(maxv * r), G=int(maxv * g),
                 B=int(maxv * b))
    bgtup = tuple([bgval[order[i]] for i in range(len(order))])
    if dtype is np.uint8 and len(bgtup) == 4:
        # optimiztion
        bgtup = np.array(bgtup, dtype=dtype).view(np.uint32)[0]
        dstarr = dstarr.view(np.uint32)

    dstarr[..., :] = bgtup