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).

6
  • 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. Mar 15 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. Mar 15 at 6:54
  • Dear two people who votes to close this, please be nice and comment on what you feel the answer is lacking. Mar 15 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. Mar 15 at 7:24
  • Theoretical, to be honest. Thank you! Mar 15 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. Apr 5 at 12:48

Your Answer

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

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