A raster worker often needs more input than it should write. A neighborhood filter needs nearby pixels; an image model may need context beyond its output region. Adding overlap to every input tile helps provide that context, but writing every overlapping result back to the destination creates a different problem. The last worker to finish can overwrite another worker's prediction, and a visually plausible mosaic can hide inconsistent ownership at tile boundaries.

This tutorial builds an offline window planner and a reconstruction test for imagery-processing work associated with a proposed UNITED UAV UG32 mapping configuration. UNITED UAV publishes this article and the linked listing. The aircraft supplies the project context; the example assumes no standard camera, onboard processor, raster format or measured accuracy. Establish the actual acquisition and processing deliverables with the proposed payload configuration.

The implementation uses only Python's standard library. It does not open imagery or run a model. Its job is narrower and testable: describe what a worker owns, what it reads, and which part of its local result belongs in the destination. Keeping those three rectangles distinct makes an important class of stitching errors reproducible without a large dataset.

UG32 fixed-wing VTOL aircraft shown in the UNITED UAV product catalog

Define ownership before adding overlap

Start with a destination raster whose width and height are known positive integers. Partition that raster into nonoverlapping core rectangles. Every destination pixel must belong to one core, including pixels in the last partial row or column of tiles. This ownership partition is independent of how much neighboring data a worker needs. Changing the processing neighborhood should not change which worker owns a destination coordinate.

A read rectangle expands a core by a requested halo, then clips the expansion to the available source extent. Read rectangles may overlap. The same source pixel can therefore be read by several workers while still having only one destination owner. The third rectangle is a crop expressed in the read array's local coordinates. It identifies the core-sized result to retain after processing the larger neighborhood.

This design assumes a processing stage that preserves the read array's pixel grid and shape. A model that downsamples, changes resolution or returns only a valid interior needs an explicit mapping between its output coordinates and the source grid. Do not apply the crop from this example unchanged to such a result. First define that mapping and account for any displacement introduced by the processing stage.

Use exclusive upper endpoints consistently

Represent a rectangle with left and top coordinates included, and right and bottom coordinates excluded. A core spanning columns zero through two is stored with horizontal bounds zero and three. Its width is three, and its neighbor begins at three. This convention agrees with ordinary Python slicing and avoids needing a special shared-border rule between adjacent cores.

The same convention applies to every coordinate system in the planner. A read rectangle and a crop rectangle do not switch to inclusive endpoints merely because their origins differ. Width is always the difference between horizontal endpoints, and height is the corresponding vertical difference. Testing these identities is more useful than inspecting a thumbnail in which a missing one-pixel strip can be difficult to notice.

Keep the axis order visible at the interface. Rectangle fields below use horizontal position followed by vertical position. Array slicing usually selects rows before columns. The helper returns row and column slices in that order so a caller does not transpose a rectangular window accidentally. Include a nonsquare example in testing; square examples can conceal that mistake.

Make the three coordinate systems explicit

The core and read boxes use coordinates relative to the full raster. The crop uses coordinates relative to the clipped read box. Subtracting the read origin from each core endpoint performs the translation. Expanding a core by a halo and then always cropping by that halo is incorrect near the source boundary, where clipping has removed part of the requested neighborhood.

Consider a core touching the left edge. Its read box cannot begin at a negative source column, so the read origin remains zero. The core also begins at zero. Its crop therefore begins at local column zero, regardless of the requested halo size. An interior core may instead begin one halo width into its read array. Those are different translations even when both workers run the same processing function.

Store all three rectangles in the job description. A worker should not have to rediscover the original tiling policy from its array shape. Retaining these coordinates also makes failures easier to investigate: a reviewer can distinguish an incorrect source read from an incorrect local crop or destination placement. Include the source dataset identity separately, because coordinates alone do not identify which raster a worker processed.

Implement a geometry-only planner

The planner rejects floating-point dimensions and booleans, requires positive source dimensions and core size, and permits a zero halo. It returns immutable rectangle descriptions through a generator. Validation runs when iteration begins; merely creating the generator does not yet execute its body. Consume it inside the caller's validation boundary rather than assuming that construction has already checked the inputs.

from dataclasses import dataclass from collections.abc import Iterator @dataclass(frozen=True) class Box: x0: int y0: int x1: int y1: int @property def width(self) -> int: return self.x1 - self.x0 @property def height(self) -> int: return self.y1 - self.y0 def slices(self) -> tuple[slice, slice]: return slice(self.y0, self.y1), slice(self.x0, self.x1) @dataclass(frozen=True) class Tile: core: Box read: Box crop: Box def tile_plan(width: int, height: int, side: int, halo: int) -> Iterator[Tile]: for name, value in ( ("width", width), ("height", height), ("side", side), ("halo", halo) ): if type(value) is not int: raise ValueError(f"{name} must be an integer") if width <= 0 or height <= 0 or side <= 0 or halo < 0: raise ValueError("positive dimensions and side, nonnegative halo required") for y in range(0, height, side): for x in range(0, width, side): core = Box(x, y, min(x + side, width), min(y + side, height)) read = Box( max(0, core.x0 - halo), max(0, core.y0 - halo), min(width, core.x1 + halo), min(height, core.y1 + halo), ) crop = Box( core.x0 - read.x0, core.y0 - read.y0, core.x1 - read.x0, core.y1 - read.y0, ) yield Tile(core, read, crop) 

The final core in either direction is shortened to the source extent. A large halo is allowed, but every read remains inside the source. The crop dimensions always equal the core dimensions. None of this allocates an image or proves that an actual processing function preserves the required shape. Check the returned array's dimensions before cropping and check the cropped dimensions before writing to the core destination.

Work through a small irregular raster

Take a synthetic raster five columns wide and four rows high. Choose a core side length of three and a halo of one. There are four cores. The upper-left core owns a three-by-three region. The upper-right core owns only two columns, and the lower row of cores owns only one row. The partial cores remain ordinary owners rather than being discarded because they are smaller than the nominal tile size.

Core bounds, x then y Read bounds, x then y Local crop bounds, x then y
[0,3), [0,3) [0,4), [0,4) [0,3), [0,3)
[3,5), [0,3) [2,5), [0,4) [1,3), [0,3)
[0,3), [3,4) [0,4), [2,4) [0,3), [1,2)
[3,5), [3,4) [2,5), [2,4) [1,3), [1,2)

These read footprints contain forty-two pixel positions in total, while the output owns twenty pixels. That difference is expected because context is read repeatedly. It is a count of logical positions, not a measurement of disk traffic or elapsed processing time. A test that expects the sum of read areas to equal the source area would reject a valid halo plan; a test that expects the sum of core areas to exceed it would accept duplicate ownership.

Decide what happens beyond the source boundary

Clipping a read window does not create observations outside the raster. An operator requiring a full neighborhood at every output position needs a separate boundary policy. It might mark those outputs invalid, request a padded array under an agreed convention, or process a smaller accepted extent. That decision belongs to the processing contract. It cannot be inferred from the geometry of a shortened edge read.

If the caller pads a clipped read on its left or top, the crop origin must move by the inserted padding. For example, inserting two columns before the read data shifts the crop two columns to the right in the padded array. Keeping the original crop after padding silently selects different pixels. Record both the requested context and any artificial boundary values, especially when results will be compared across processing versions.

A zero padding value should not be presented as a measured zero. Reflection and repeated-edge padding also introduce assumptions about the unobserved neighborhood. The planner deliberately returns the clipped source read without selecting one of these policies. A useful edge test verifies the declared policy with identifiable input values, rather than checking only whether the processing stage returns an array of the expected shape.

Carry validity separately from geometric coverage

Owning a pixel does not mean that its source value is valid. An exported mosaic can contain missing coverage, masked regions or pixels excluded during processing. Preserve a validity mask alongside the numerical array. The reconstruction test below uses a complete synthetic grid to isolate geometry; a production pipeline needs additional tests for the validity rules relevant to its actual deliverable.

Avoid deriving validity from a convenient numerical value unless the file contract explicitly assigns that meaning. Zero can be a legitimate value in a processed raster. If a worker treats every zero as missing while another preserves the mask supplied with the source, the same geometric plan can produce inconsistent results. Establish the mask interpretation at import and retain the distinction between an invalid output and a valid output whose value happens to be zero.

For several bands, decide which observations the operation actually requires. A calculation requiring every input band may need their joint validity, while a documented partial-input method could behave differently. A geometrically complete stitched array cannot answer that question. Preserve the reason for invalidity when the receiving workflow needs to distinguish missing source coverage from a later processing rejection.

Test reconstruction rather than a drawing of rectangles

Create a small synthetic grid whose value identifies its global row and column. For each planned job, extract the read array, apply an identity processing function, retain the local crop and place it into the core destination. Independently count destination writes. The assembled values should equal the original grid, and every destination write count should equal one. This checks translation and ownership together.

Here is a runnable identity trial after the planner definition:

grid = [[1000*y+x for x in range(5)] for y in range(4)] output = [[None]*5 for _ in range(4)] writes = [[0]*5 for _ in range(4)] for tile in reversed(list(tile_plan(5, 4, 3, 1))): r, c, cut = tile.read, tile.core, tile.crop block = [row[r.x0:r.x1] for row in grid[r.y0:r.y1]] retained = [row[cut.x0:cut.x1] for row in block[cut.y0:cut.y1]] for local_y, row in enumerate(retained): for local_x, value in enumerate(row): y, x = c.y0+local_y, c.x0+local_x output[y][x] = value writes[y][x] += 1 assert output == grid assert all(count == 1 for row in writes for count in row) 

Use irregular source shapes, core sizes that do not divide the dimensions, zero halos, halos larger than the image, and a core larger than the whole source. Process jobs in reverse order as well as normal order. A partition with correct ownership should reconstruct the same identity result in either order. A pipeline that writes overlapping read results can instead become dependent on completion order.

For this article, local validation exercised 1,890 small combinations of dimensions, core sizes and halos using that reconstruction oracle. Separate cases covered rejected inputs and explicit edge coordinates. These tests establish the planner's behavior on synthetic arrays. They do not establish the numerical behavior of an image model, the validity of a delivered mask or the positional accuracy of an aircraft survey.

Preserve the transform associated with the retained output

Georeferencing must describe the pixels that survive the crop. A worker may attach metadata describing the read box, then retain only the core values. Writing that smaller array with the read box's origin shifts its declared location. Keep the core's global placement available when deriving the transform or destination window for the retained result.

The GDAL geotransform tutorial defines the relationship between pixel coordinates, pixel corners and georeferenced coordinates. In an affine grid, translating the pixel origin changes the mapped origin using the applicable coefficients, including rotation terms when present. A shift in columns is not automatically an easting-only change. This tutorial does not implement coordinate transformations; it preserves the offsets needed by a separately verified geospatial writer.

Test placement with a deliberately distinguishable feature away from a convenient round origin. Compare the retained core's declared location with its location in the original raster. Keep pixel-center and pixel-corner conventions explicit when building that check. A correct array reconstruction and a correct map placement are related checks, but one should not silently substitute for the other.

Budget neighborhood work without inventing an I/O speedup

An interior square core with side length S and halo R reads a square of side S plus twice R. The logical read-area ratio is therefore the expanded area divided by the core area. A synthetic 512-pixel core with a 32-pixel halo gives a ratio of 1.265625. Smaller cores can increase repeated context work substantially, even though they reduce the size of an individual processing job.

Physical reads depend on storage layout as well as that geometry. The Rasterio windowed reading and writing documentation explains that satisfying a small window can require reading complete underlying blocks. Inspect the actual dataset layout before predicting traffic or choosing worker count. A logical pixel count is useful for comparing plans; it is not a benchmark of the proposed storage service.

Also account for input bands, masks, temporary arrays, model intermediates and retained results. A generator of small job descriptions does not bound the memory consumed by a queue holding decoded arrays. Limit work in flight according to the measured processing footprint. Keep that resource policy separate from the geometric partition so changing concurrency does not accidentally change output ownership.

Write core results with explicit shape checks

After processing, retain the crop and require its dimensions to match the core before handing it to the destination writer. An array that looks close enough in a preview may have lost a border or changed resolution. Reject an unexplained mismatch instead of relying on a writer to reconcile it. In particular, a writer that resamples an array into a different window can conceal an upstream shape error.

Categorical results need another distinction. Averaging class identifiers in an overlap does not create a meaningful class. If an application deliberately combines competing predictions, define the merge rule, the information it needs and how it treats invalid inputs. The ownership approach here avoids an accidental merge by selecting only each worker's core output; it does not prevent a separately specified ensemble or blending stage.

Disjoint pixel ownership also does not establish that a particular file writer supports simultaneous writes from many processes. Use the writer's supported concurrency pattern or serialize final placement. The planner describes destination regions. It does not coordinate file handles, remote object commits or process crashes. Those execution guarantees need their own implementation and failure tests.

Make the proposed imagery handoff testable

For a UG32 mapping inquiry, specify the intended camera and processing service before assuming what imagery will be delivered. Ask for a representative raster, its dimensions, coordinate definition, pixel interpretation, masks and processing history. Then run a small window-and-reconstruction trial through the receiving software. The exact product configuration and file handoff should be agreed independently of the algorithm demonstrated here.

Store the source identity, planner version, core size, halo, boundary policy and expected array geometry with the job plan. These fields let a later reviewer reproduce why a worker read a particular neighborhood and wrote a particular region. A revised processing operator may require more context, but its new halo should not quietly change the destination ownership partition.

The useful acceptance question is whether the receiver can explain every retained output pixel: which core owns it, which source neighborhood was available, what validity rule applied and where it belongs in the declared grid. The synthetic reconstruction gives a compact way to verify the geometric part of that explanation before a large processing run makes an indexing mistake expensive to diagnose.

This article and its code were developed with AI assistance. Numerical examples and executable checks use synthetic data; no UG32 flight or sensor performance test is claimed.