1

I have a raster file with some data pixels around the middle and a huge amount of NODATA padding everywhere around it.

How can I crop the raster so that the extent aligns with the outermost non-NODATA pixels on all sides?

The result should be perfectly aligned to the source raster's rows and columns (so, if possible, without a vector mask layer or an extent defined in CRS units).

5
  • What is the issue with a vector mask? I did a basic test with a raster with data pixels surrounded by NoData pixels, and a projected CRS. I used Raster Pixels to Polygons to create a polygon mask, and then Clip Raster By Extent with the polygon layer as a vector mask. The output layer was aligned to the source raster. Commented Mar 15, 2023 at 6:38
  • It might seem esoteric but I would be afraid of it being lossy in some circumstances due to floating point numbers etc. I want to do analysis on pixel-perfect aligned rasters, not 99.99% aligned ones. Commented Mar 15, 2023 at 6:54
  • Dear two people who votes to close this, please be nice and comment on what you feel the answer is lacking. Commented Mar 15, 2023 at 6:55
  • Have you seen raster grids go out of alignment before? Just trying to understand if this is a real issue or a theoretical one. Keep in mind that you can run checks on the before/after rasters to ensure that the differences are zero. Commented Mar 15, 2023 at 7:24
  • Theoretical, to be honest. Thank you! Commented Mar 15, 2023 at 9:29

1 Answer 1

1

Use gdal_translate https://gdal.org/programs/gdal_translate.html with -srcwin option.

-srcwin <xoff> <yoff> <xsize> <ysize>

Selects a subwindow from the source image for copying based on pixel/line location.

Offsets are counted from the top left corner. A separate challenge is to analyze the data/nodata coverage for finding the appropriate values for offsets and sizes.

1
  • Thanks, this seems like the right approach. Commented Apr 5, 2023 at 12:48

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.