Read a scene one window at a time#
Calculate the mean of valid samples in a band without keeping the whole scene in memory. Each read replaces the previous pixels, so add the valid count and sum to running totals before reading the next window.
Read two rows and their mask together#
From the checkout root, use cugeo-raster/tests/data/dataset_masks/nodata.tif, a two-band, 4 × 4 UInt8 image. The first row of band 1 is [0, 1, 0, 7], and its mask is [0, 255, 0, 255]. The nonzero mask entries admit 1 and 7. Use the mask because a fill value alone cannot establish validity.
Allocate the pixel and mask buffers once. Window takes column offset, row offset, width and height, in that order. Band numbering starts at 1. A scalar band index fills a 2-D array. The supplied NumPy buffers select the host route for both reads.
import numpy as np
import cugeo.raster as cr
path = "cugeo-raster/tests/data/dataset_masks/nodata.tif"
pixels = np.empty((2, 4), dtype=np.uint8)
mask = np.empty_like(pixels)
total_count = 0
total_sum = 0
with cr.open(path) as ds:
for row in (0, 2):
window = cr.windows.Window(0, row, 4, 2)
ds.read(1, window=window, out=pixels)
ds.read_masks(1, window=window, out=mask)
count = int(np.count_nonzero(mask))
subtotal = int(pixels[mask != 0].sum(dtype=np.uint64))
print(row, count, subtotal)
total_count += count
total_sum += subtotal
print(total_count, total_sum, total_sum / total_count)
Check the counts and mean#
The two window lines should be 0 6 29 and 2 6 31. The final line should be 12 60 5.0. Dividing the combined sum by the combined count gives every valid pixel equal weight, even when windows contain different numbers of valid pixels.