def test_mask_exact2(test_fixture2): with rio.open(test_fixture2) as src: img = src.read() ndv = (18, 51, 62) assert np.max(mask_exact(img, ndv)) <= np.iinfo(img.dtype).max assert mask_exact(img, ndv).dtype == img.dtype assert np.array_equal( np.invert(np.all(np.rollaxis(img, 0, 3) == ndv, axis=2)).astype( img.dtype) * np.iinfo(img.dtype).max, mask_exact(img, ndv))
def test_mask_exact3(arr): for i in range(3): arr[i][-1][-1] = 0 ndv = (0, 0, 0) assert np.max(mask_exact(arr, ndv)) <= np.iinfo(arr.dtype).max assert mask_exact(arr, ndv).dtype == arr.dtype assert np.array_equal( np.invert(np.all(np.rollaxis(arr, 0, 3) == ndv, axis=2)).astype( arr.dtype) * np.iinfo(arr.dtype).max, mask_exact(arr, ndv))
def count_ndv_regions(img, ndv): '''Discover unique labels to count ndv regions. Parameters ---------- ndv: list a list of floats whose length = band count img: ndarray (depth x rows x cols) array Returns ------- n_labels: int an integer equal to the number of connected regions ''' np.set_printoptions(threshold=np.nan) img = mask_exact(img, ndv) _, n_labels = measure.label(img, background=255, neighbors=4, return_num=True) return n_labels
def test_mask_exact4(): arr2 = np.random.randint(0, 255, (3, 10, 15)) for i in range(3): arr2[i][-1][-1] = 255 arr2[i][1][1] = 255 arr2[i][2][2] = 255 ndv = (255, 255, 255) assert np.array_equal(np.any(np.rollaxis(arr2, 0, 3) != ndv, axis=2), mask_exact(arr2, ndv) / np.iinfo(arr2.dtype).max)
def _alpha_worker(open_file, window, ij, g_args): """rio mucho worker for alpha. It reads input files and perform alpha calculations on each window. Parameters ------------ open_files: list of rasterio open files window: tuples A window is a view onto a rectangular subset of a raster dataset and is described in rasterio by a pair of range tuples: ((row_start, row_stop), (col_start, col_stop)) g_args: dictionary Returns --------- rgba: ndarray ndarray with original RGB bands of shape (3, rows, cols) and a mask of shape (rows, cols) where opaque == 0 and transparent == max of dtype """ src = open_file[0] arr = src.read(window=window) # Determine Alpha Band if g_args['ndv']: # User-supplied nodata value alpha = mask_exact(arr, g_args['ndv']) else: # Let rasterio decide alpha = src.dataset_mask(window=window) # Replace or Add alpha band to input data if arr.shape[0] == 4: # replace band 4 with new alpha mask # (likely the same but let's not make that assumption) rgba = arr.copy() rgba[3] = alpha elif arr.shape[0] == 3: # stack the alpha mask to add band 4 rgba = np.append(arr, alpha[np.newaxis, :, :], axis=0) else: raise ValueError("Array must have 3 or 4 bands (RGB or RGBA)") return rgba
def count_ndv_regions(img, ndv): """Discover unique labels to count ndv regions. Parameters ---------- ndv: list a list of floats whose length = band count img: ndarray (depth x rows x cols) array Returns ------- int The number of connected regions """ img = mask_exact(img, ndv) return len(list(shapes(img, mask=(img != 255))))