Extract rotated rectangle from raster in Python

535 Views Asked by At

I'm using GDAL in Python to work with GeoTIFF rasters. I use the following code to extract small rectangular patches from the entire raster:

data_file = gdal.Open("path/to/raster.tiff")
data = data_file.ReadAsArray(xoffset, yoffset, xsize, ysize)

How could I change this code to extract rotated rectangular areas from the raster. For example, I would like to be able to extract data from the area shown in red below.

enter image description here

I'd like the red area to be resampled and rotated, so that I can access it as a simple numpy data array.

1

There are 1 best solutions below

0
On BEST ANSWER

I created a solution to this by following this excellent post about how to implement affine transforms.

My solution works by:

  1. Using ReadAsArray to read a section of the full raster that fully contains the red area;
  2. Identifying points p0, p1, p2 representing the top-left, top-right and bottom-left corners of the red area respectively in pixel coordinates;
  3. Implementing the algorithm as described in the link to compute the affine transform, leaving me with the red area on its own, rotated into a horizontal position.