4

Is there a way to sum two rasters of different shape using rasterio? To explain it better, the rasters have different bounding boxes, but there is an area that overlaps.

The objective is to get the result of the operation and write it to file, limiting the output raster to the area that overlaps.

2 Answers 2

5

It is possible by using windowed reading and writing available in rasterio. First, you need to find each raster bounding box and intersects them by using shapely python module. Intersecting bounding box is used for calculating indices of column, row for first and last pixel in each raster. So, these values are used for windowed reading both raster as array before calculating its respective sum. Finally, this array is written as raster by using 'write' rasterio method and configuration options. Developed code looks as follows:

import rasterio
from rasterio.windows import Window
from rasterio.transform import Affine

from shapely.geometry import box

raster1 = rasterio.open("/home/zeito/pyqgis_data/c1.tif")
raster2 = rasterio.open("/home/zeito/pyqgis_data/c2.tif")

bb_raster1 = box(raster1.bounds[0], raster1.bounds[1], raster1.bounds[2], raster1.bounds[3])
bb_raster2 = box(raster2.bounds[0], raster2.bounds[1], raster2.bounds[2], raster2.bounds[3])

xminR1, yminR1, xmaxR1, ymaxR1 = raster1.bounds
xminR2, yminR2, xmaxR2, ymaxR2 = raster2.bounds

intersection = bb_raster1.intersection(bb_raster2)
transform = Affine(raster1.res[0], 0.0, intersection.bounds[0], 0.0, -raster1.res[1], intersection.bounds[3])

p1Y = intersection.bounds[3] - raster1.res[1]/2
p1X = intersection.bounds[0] + raster1.res[0]/2
p2Y = intersection.bounds[1] + raster1.res[1]/2
p2X = intersection.bounds[2] - raster1.res[0]/2
#row index raster1
row1R1 = int((ymaxR1 - p1Y)/raster1.res[1])
#row index raster2
row1R2 = int((ymaxR2 - p1Y)/raster2.res[1])
#column index raster1
col1R1 = int((p1X - xminR1)/raster1.res[0])
#column index raster2
col1R2 = int((p1X - xminR2)/raster1.res[0])

#row index raster1
row2R1 = int((ymaxR1 - p2Y)/raster1.res[1])
#row index raster2
row2R2 = int((ymaxR2 - p2Y)/raster2.res[1])
#column index raster1
col2R1 = int((p2X - xminR1)/raster1.res[0])
#column index raster2
col2R2 = int((p2X - xminR2)/raster1.res[0])

width1 = col2R1 - col1R1 + 1
width2 = col2R2 - col1R2 + 1
height1 = row2R1 - row1R1 + 1
height2 = row2R2 - row1R2 + 1

arr_raster1 = raster1.read(1, window=Window(col1R1, row1R1, width1, height1))
arr_raster2 = raster2.read(1, window=Window(col1R2, row1R2, width2, height2))

arr_sum = arr_raster1 + arr_raster2

# Register GDAL format drivers and configuration options with a
# context manager.

with rasterio.open('/home/zeito/pyqgis_data/sum3.tif',
                   'w',
                   driver='GTiff',
                   height=arr_sum.shape[0],
                   width=arr_sum.shape[1],
                   count=1,
                   dtype=arr_sum.dtype,
                   crs=raster1.crs,
                   transform=transform) as dst:

    dst.write(arr_sum, 1)

dst.close()

I tried out above code in PyCharm with two relatively big raster layers; visualized in following image:

enter image description here

After running script, resulting sum raster layer was also loaded in QGIS and, with help of Value Tool QGIS plugin, it was corroborated in many points (including first and last pixel) that sum raster result was as expected (see following image).

enter image description here

2

This is a new answer which basically does what xunliks code does.

Its advantage is that it easily works with more than two files. For xunliks code you'd have to do a lot of changes to make it work with more files.

It also shows how you would write out the raw data in the window without doing any summing.

import rasterio
from rasterio.windows import from_bounds

from shapely.geometry import box


files = ["file1.tif", "file2.tif"]

def get_bounds(file):
    "This returns the bounds of a single tif as a tuple"
    with rasterio.open(file) as f:
        bounds = f.bounds
    return tuple(bounds)

def get_intersection(file_list):
    "This builds the smallest intersection of all files bounding boxes"
    file = file_list[-1]
    intersection = box(*get_bounds(file))
    for file in file_list[:-1]:
        bbox = box(*get_bounds(file))
        intersection = intersection.intersection(bbox)
    return intersection

intersection = get_intersection(files)

# Finally we write out the data only for this overlap
arr_sum = None
for file in bands:
    with rasterio.open(file) as src:
        affine = src.transform
        window = from_bounds(*intersection.bounds, transform=affine)
        # Copy the metadata
        out_meta = src.meta.copy()

        out_meta.update({
            "width": window.width,
            "height": window.height,
            "transform": rasterio.windows.transform(window, src.transform)
            })
        
        if arr_sum is None:
            arr_sum = src.read(window=window)
        else:
            arr_sum = arr_sum + src.read(window=window)
        # This writes the raw data in the window (not the sum)
        new_filename = "window_" + file
        with rasterio.open(new_filename, "w", **out_meta) as dst:
            dst.write(src.read(window=window))

# This writes the sum
out_meta.update(count=1)
with rasterio.open("sum.tif", "w", **out_meta) as dst:
    dst.write(arr_sum, 1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.