2

I want to clip an image named img_A of dimensions 14000x10000 using a polygon shape in order to get the same dimensions than another image named img_B of dimensions 1925x1372 (see figure 1 below). The polygon shape has the same extent than img_B. Pixel size is 0.1 m for img_A and img_B.

One important thing is that the pixels of img_A are not aligned with the pixels of img_B (figure 2). I mean there is a small offset between the pixels of both images (3 cm).

So I used rasterio.mask to clip img_A and obtain img_B extent using that code (figure 3):

import fiona
from rasterio.mask import mask

polygon = polygon.shp
raster = img_A.tif
dst = result.tif

with fiona.open(polygon, "r") as shapefile:
    geometry = [feature["geometry"] for feature in shapefile]

with rasterio.open(raster) as src:
    out_image, out_transform = mask(src, geometry, crop=True)
    out_meta = src.meta.copy()
    out_meta.update({"driver": "GTiff",
                     "height": out_image.shape[1],
                     "width": out_image.shape[2],
                     "transform": out_transform})

with rasterio.open(dst, "w", **out_meta) as dest:
    dest.write(out_image)

However, the final result is an image of dimensions 1926x1373. Moreover, the new image is slightly offset to the South-West, corresponding to the offset cited previously (3 cm), which means the image is outside of the polygon shape to the West and to the South (figure 4).

How can I obtain a well placed image with dimensions 1925x1372?

Figure 1 - Input dataset enter image description here

Figure 2 - Pixel offset enter image description here

Figure 3 - Overview of the result after clipping enter image description here

Figure 4 - Problem enter image description here

  • Finally, I fixed it using gdal.warp instead of rasterio.mask. – rdmato33 Dec 18 '19 at 12:59