Window from bounds is shifted by 1 Pixel

thomaswanderer@...
 

Hi. this is my first post. I am new to raster.io and really like it so far. Thumbs up for all the work :-)

But I have already a first problem: I created a function which creates a new raster for a given geographical extent and copies the values of the source raster into it. The new raster has the same characteristics as the source raster. The geographical extents can now
  • include the source raster (within)
  • lay within the source raster bounds (contained)
  • or partially overlap with the source raster bounds


For all of these cases, I create a new affine for the new raster and then fill it with the values of the source raster (or any other optionally specified value).
I still have a problem when copying over the values from the source to the target raster.
In one case the two rasters (source -> copy) are not aligned but shifted by 1 pixel. (See yellow extent in above images - All other extents create perfectly aligned new rasters)

My strategy for copying data from the source to the target is the following:

  1. I have calculated the exact pixel aligned bounds for the target raster
  2. I have the exact pixel aligned bounds from the source raster
  3. I create an intersection polygon from both
    intersection = INTERSECT(source.bounds, target.bounds)
  4. I use the intersection to create a read-window for the source
    with rasterio.open('source.tif', 'r') as source:
        read_window = source.window(*intersection.bounds))
  5. I use the intersection to create a write-window for the target
    with rasterio.open('target.tif', 'w', **profile) as target:
        write_window = target.window(*intersection.bounds))
  6. Then I read from the source and write to the target
    target.write(source.read(window=read_window), window=write_window)
For all rasters which overlap the western side of the source, I receive values which are shifted by 1 pixel west wards.



My guess is that the write_window = target.window(*intersection.bounds)) is the part where the error happens. While the read_window still reads the correct data, the write window places the copied data shifted by 1 pixel. I use the same intersection extent for the creation of both windows, and the intersection is also pixel aligned as visible in the above image. So I wonder what I do wrong. Is this maybe a rounding or precision error?

Join main@rasterio.groups.io to automatically receive all group messages.