I have a GeoTiff in UTM32 and coordinates of a rectangle also in UTM32. (This projection may not always be the case, but the projections will always be the same)
I simply need to crop the image using the rectangle .
The rectangle is given by: (xmin, xmax, ymin, ymax)
699934.584491, 700160.946739, 6168703.00544, 6169364.0093
I know how to make a polygon from the points, how to make a shapefile from the polygon, and I know how to create a masked numpy array using the points. However, I don't know how to use the polygon, the shapefile or the mask to actually crop the image.
I already looked at the description at: https://pcjericks.github.io/py-gdalogr-cookbook/raster_layers.html#clip-a-geotiff-with-shapefile
However, I don't really understand it and it seems overly complicated. (like I don't know what histogram stretching is supposed to be doing there except confusing)
Try to use bbox = (xmin,ymin,xmax,ymax)
from osgeo import gdal
bbox = (xmin,ymin,xmax,ymax)
gdal.Translate('output_crop_raster.tif', 'input_raster.tif', projWin = bbox)
Akin's answer is right, but doesn't provide a complete explanation.
You can crop a gdal file using gdal_translate , which can be used in python via gdal.Translate
.
The easiest way is with the projwin flag, which takes 4 values:
window = (upper_left_x, upper_left_y, lower_right_x, lower_right_y)
These values are in map coordinates. The bounds of the input file can be obtained via gdalinfo input_raster.tif
from the command line.
NOTE : for many coordinate systems, ymax
is actually less than ymin
, so it's important to use "upper_left" and "lower_right" to identify the coordinates instead of "max" and "min."
The complete solution, then is:
from osgeo import gdal
upper_left_x = 699934.584491
upper_left_y = 6169364.0093
lower_right_x = 700160.946739
lower_right_y = 6168703.00544
window = (upper_left_x,upper_left_y,lower_right_x,lower_right_y)
gdal.Translate('output_crop_raster.tif', 'input_raster.tif', projWin = window)
srcwin is another gdal_translate flag similar to projwin
, but takes in the pixel and line window via an offset and size, instead of using the map coordinate bounds. You would use it like this:
window = (offset_x, offset_y, size_x, size_y)
gdal.Translate('output_crop_raster.tif', 'input_raster.tif', srcWin = window)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.