└── README.md /README.md: -------------------------------------------------------------------------------- 1 | Cheat sheet for GDAL/OGR command-line geodata tools 2 | 3 | Vector operations 4 | --- 5 | 6 | __Get vector information__ 7 | 8 | ogrinfo -so input.shp layer-name 9 | 10 | Or, for all layers 11 | 12 | ogrinfo -al -so input.shp 13 | 14 | __Print vector extent__ 15 | 16 | ogrinfo input.shp layer-name | grep Extent 17 | 18 | __List vector drivers__ 19 | 20 | ogr2ogr --formats 21 | 22 | __Convert between vector formats__ 23 | 24 | ogr2ogr -f "GeoJSON" output.json input.shp 25 | 26 | __Print count of features with attributes matching a given pattern__ 27 | 28 | ogrinfo input.shp layer-name | grep "Search Pattern" | sort | uniq -c 29 | 30 | __Read from a zip file__ 31 | 32 | This assumes that archive.zip is in the current directory. This example just extracts the file, but any ogr2ogr operation should work. It's also possible to write to existing zip files. 33 | 34 | ogr2ogr -f 'GeoJSON' dest.geojson /vsizip/archive.zip/zipped_dir/in.geojson 35 | 36 | __Clip vectors by bounding box__ 37 | 38 | ogr2ogr -f "ESRI Shapefile" output.shp input.shp -clipsrc 39 | 40 | __Clip one vector by another__ 41 | 42 | ogr2ogr -clipsrc clipping_polygon.shp output.shp input.shp 43 | 44 | __Reproject vector:__ 45 | 46 | ogr2ogr output.shp -t_srs "EPSG:4326" input.shp 47 | 48 | __Add an index to a shapefile__ 49 | 50 | Add an index on an attribute: 51 | 52 | ogrinfo example.shp -sql "CREATE INDEX ON example USING fieldname" 53 | 54 | Add a spatial index: 55 | 56 | ogrinfo example.shp -sql "CREATE SPATIAL INDEX ON example" 57 | 58 | __Merge features in a vector file by attribute ("dissolve")__ 59 | 60 | ogr2ogr -f "ESRI Shapefile" dissolved.shp input.shp -dialect sqlite -sql "select ST_union(Geometry),common_attribute from input GROUP BY common_attribute" 61 | 62 | __Merge features ("dissolve") using a buffer to avoid slivers__ 63 | 64 | ogr2ogr -f "ESRI Shapefile" dissolved.shp input.shp -dialect sqlite \ 65 | -sql "select ST_union(ST_buffer(Geometry,0.001)),common_attribute from input GROUP BY common_attribute" 66 | 67 | __Merge vector files:__ 68 | 69 | ogr2ogr merged.shp input1.shp 70 | ogr2ogr -update -append merged.shp input2.shp -nln merged 71 | 72 | __Extract from a vector file based on query__ 73 | 74 | To extract features with STATENAME 'New York','New Hampshire', etc. from states.shp 75 | 76 | ogr2ogr -where 'STATENAME like "New%"' states_subset.shp states.shp 77 | 78 | To extract type 'pond' from water.shp 79 | 80 | ogr2ogr -where "type = pond" ponds.shp water.shp 81 | 82 | __Subset & filter all shapefiles in a directory__ 83 | 84 | Assumes that filename and name of layer of interest are the same... 85 | 86 | basename -s.shp *.shp | xargs -n1 -I % ogr2ogr %-subset.shp %.shp -sql "SELECT field-one, field-two FROM '%' WHERE field-one='value-of-interest'" 87 | 88 | __Extract data from a PostGis database to a GeoJSON file__ 89 | 90 | ogr2ogr -f "GeoJSON" file.geojson PG:"host=localhost dbname=database user=user password=password" \ 91 | -sql "SELECT * from table_name" 92 | 93 | __Extract data from an ESRI REST API__ 94 | 95 | Services that use ESRI maps are sometimes powered by a REST server that can provide data in OGR can consume. Finding the correct end point can be tricky and may take some false starts. 96 | 97 | ogr2ogr -f GeoJSON output.geojson "http:/example.com/arcgis/rest/services/SERVICE/LAYER/MapServer/0/query?f=json&returnGeometry=true&etc=..." OGRGeoJSON 98 | 99 | __Get the difference between two vector files__ 100 | 101 | Given two files that both have an id field, this will produce a vector file with the part of `file1.shp` that doesn't intersect with `file2.shp`: 102 | 103 | ogr2ogr diff.shp file1.shp -dialect sqlite \ 104 | -sql "SELECT ST_Difference(a.Geometry, b.Geometry) AS Geometry, a.id \ 105 | FROM file1 a LEFT JOIN 'file2.shp'.file2 b USING (id) WHERE a.Geometry != b.Geometry" 106 | 107 | This assumes that `file2.shp` and `file2.shp` are both in the current directory. 108 | 109 | __Spatial join:__ 110 | 111 | A spatial join transfers properties from one vector layer to another based on a [spatial relationship](http://postgis.net/docs/manual-2.0/reference.html#Spatial_Relationships_Measurements) between the features. Fields from the join layer can be [aggregated](https://www.sqlite.org/lang_aggfunc.html) in the output. 112 | 113 | Given a set of points (trees.shp) and a set of polygons (parks.shp) in the same directory, create a polygon layer with the geometries from parks.shp and summaries of some columns in trees.shp: 114 | 115 | ogr2ogr -f 'ESRI Shapefile' output.shp parks.shp -dialect sqlite \ 116 | -sql "SELECT p.Geometry, p.id id, SUM(t.field1) field1_sum, AVG(t.field2) field2_avg 117 | FROM parks p, 'trees.shp'.trees t WHERE ST_Contains(p.Geometry, t.Geometry) GROUP BY p.id" 118 | 119 | Note that features that from parks.shp that don't overlap with trees.shp won't be in the new file. 120 | 121 | Raster operations 122 | --- 123 | __Get raster information__ 124 | 125 | gdalinfo input.tif 126 | 127 | __List raster drivers__ 128 | 129 | gdal_translate --formats 130 | 131 | __Force creation of world file (requires libgeotiff)__ 132 | 133 | listgeo -tfw mappy.tif 134 | 135 | __Report PROJ.4 projection info, including bounding box (requires libgeotiff)__ 136 | 137 | listgeo -proj4 mappy.tif 138 | 139 | __Convert between raster formats__ 140 | 141 | gdal_translate -of "GTiff" input.grd output.tif 142 | 143 | __Convert 16-bit bands (Int16 or UInt16) to Byte type__ 144 | (Useful for Landsat 8 imagery...) 145 | 146 | gdal_translate -of "GTiff" -co "COMPRESS=LZW" -scale 0 65535 0 255 -ot Byte input_uint16.tif output_byte.tif 147 | 148 | You can change '0' and '65535' to your image's actual min/max values to preserve more color variation or to apply the scaling to other band types - find that number with: 149 | 150 | gdalinfo -mm input.tif | grep Min/Max 151 | 152 | __Convert a directory of raster files of the same format to another raster format__ 153 | 154 | basename -s.img *.img | xargs -n1 -I % gdal_translate -of "GTiff" %.img %.tif 155 | 156 | __Reproject raster:__ 157 | 158 | gdalwarp -t_srs "EPSG:102003" input.tif output.tif 159 | 160 | Be sure to add _-r bilinear_ if reprojecting elevation data to prevent funky banding artifacts. 161 | 162 | __Georeference an unprojected image with known bounding coordinates:__ 163 | 164 | gdal_translate -of GTiff -a_ullr \ 165 | -a_srs EPSG:4269 input.png output.tif 166 | 167 | __Clip raster by bounding box__ 168 | 169 | gdalwarp -te input.tif clipped_output.tif 170 | 171 | __Clip raster to SHP / NoData for pixels beyond polygon boundary__ 172 | 173 | gdalwarp -dstnodata -cutline input_polygon.shp input.tif clipped_output.tif 174 | 175 | __Crop raster dimensions to vector bounding box__ 176 | 177 | gdalwarp -cutline cropper.shp -crop_to_cutline input.tif cropped_output.tif 178 | 179 | __Merge rasters__ 180 | 181 | gdal_merge.py -o merged.tif input1.tif input2.tif 182 | 183 | Alternatively, 184 | 185 | gdalwarp input1.tif input2.tif merged.tif 186 | 187 | Or, to preserve nodata values: 188 | 189 | gdalwarp input1.tif input2.tif merged.tif -srcnodata -dstnodata 190 | 191 | __Stack grayscale bands into a georeferenced RGB__ 192 | 193 | Where LC81690372014137LGN00 is a Landsat 8 ID and B4, B3 and B2 correspond to R,G,B bands respectively: 194 | 195 | gdal_merge.py -co "PHOTOMETRIC=RGB" -separate LC81690372014137LGN00_B{4,3,2}.tif -o LC81690372014137LGN00_rgb.tif 196 | 197 | __Fix an RGB TIF whose bands don't know they're RGB__ 198 | 199 | gdal_merge.py -co "PHOTOMETRIC=RGB" input.tif -o output_rgb.tif 200 | 201 | __Export a raster for Google Earth__ 202 | 203 | gdal_translate -of KMLSUPEROVERLAY input.tif output.kmz -co FORMAT=JPEG 204 | 205 | __Raster calculation (map algebra)__ 206 | 207 | Average two rasters: 208 | 209 | gdal_calc.py -A input1.tif -B input2.tif --outfile=output.tif --calc="(A+B)/2" 210 | 211 | Add two rasters: 212 | 213 | gdal_calc.py -A input1.tif -B input2.tif --outfile=output.tif --calc="A+B" 214 | 215 | etc. 216 | 217 | __Create a hillshade from a DEM__ 218 | 219 | gdaldem hillshade -of PNG input.tif hillshade.png 220 | 221 | Change light direction: 222 | 223 | gdaldem hillshade -of PNG -az 135 input.tif hillshade_az135.png 224 | 225 | Use correct vertical scaling in meters if input is projected in degrees 226 | 227 | gdaldem hillshade -s 111120 -of PNG input_WGS1984.tif hillshade.png 228 | 229 | __Apply color ramp to a DEM__ 230 | First, create a color-ramp.txt file: 231 | _(Height, Red, Green, Blue)_ 232 | 233 | 0 110 220 110 234 | 900 240 250 160 235 | 1300 230 220 170 236 | 1900 220 220 220 237 | 2500 250 250 250 238 | 239 | Then apply those colors to a DEM: 240 | 241 | gdaldem color-relief input.tif color_ramp.txt color-relief.tif 242 | 243 | __Create slope-shading from a DEM__ 244 | First, make a slope raster from DEM: 245 | 246 | gdaldem slope input.tif slope.tif 247 | 248 | Second, create a color-slope.txt file: 249 | _(Slope angle, Red, Green, Blue)_ 250 | 251 | 0 255 255 255 252 | 90 0 0 0 253 | 254 | Finally, color the slope raster based on angles in color-slope.txt: 255 | 256 | gdaldem color-relief slope.tif color-slope.txt slopeshade.tif 257 | 258 | __Resample (resize) raster__ 259 | 260 | gdalwarp -ts -r cubic dem.tif resampled_dem.tif 261 | 262 | Entering 0 for either width or height guesses based on current dimensions. 263 | 264 | Alternatively, 265 | 266 | gdal_translate -outsize 10% 10% -r cubic dem.tif resampled_dem.tif 267 | 268 | For both of these, `-r cubic` specifies cubic interpolation: when resampling continuous data (like a DEM), the default nearest neighbor interpolation can result in "stair step" artifacts. 269 | 270 | __Burn vector into raster__ 271 | 272 | gdal_rasterize -b 1 -i -burn -32678 -l layername input.shp input.tif 273 | 274 | __Extract polygons from raster__ 275 | 276 | gdal_polygonize.py input.tif -f "GeoJSON" output.json 277 | 278 | __Create contours from DEM__ 279 | 280 | gdal_contour -a elev -i 50 input_dem.tif output_contours.shp 281 | 282 | __Get values for a specific location in a raster__ 283 | 284 | gdallocationinfo -xml -wgs84 input.tif 285 | 286 | __Convert GRIB band to .tif__ 287 | 288 | Assumes data for entire globe in WGS84. Be sure to specify band, or you may end up with a nonsense RGB image composed of the first three. 289 | 290 | gdal_translate input.grib -a_ullr -180 -90 180 90 -a_srs EPSG:4326 -b 1 output_band1.tif 291 | 292 | 293 | Other 294 | --- 295 | __Convert KML points to CSV (simple)__ 296 | 297 | ogr2ogr -f CSV output.csv input.kmz -lco GEOMETRY=AS_XY 298 | 299 | __Convert KML to CSV (WKT)__ 300 | First list layers in the KML file 301 | 302 | ogrinfo -so input.kml 303 | 304 | Convert the desired KML layer to CSV 305 | 306 | ogr2ogr -f CSV output.csv input.kml -sql "select *,OGR_GEOM_WKT from some_kml_layer" 307 | 308 | __CSV points to SHP__ 309 | 310 | Given `input.csv`: 311 | 312 | lon,lat,value 313 | -81,31,13 314 | -80,32,14 315 | -81,33,15 316 | 317 | Create a shapefile, using Spatialite functions to generate the point: 318 | 319 | ogr2ogr output.shp input.csv -dialect sqlite \ 320 | -sql "SELECT MakePoint(CAST(lon as REAL), CAST(lat as REAL), 4326) Geometry, * FROM input" 321 | 322 | Note the 4326, which refers to a spatial reference (in this case [`EPSG:4326`](http://epsg.io/4326)). Use the correct code for your data. 323 | 324 | __MODIS operations__ 325 | 326 | First, download relevant .hdf tiles from the MODIS ftp site: ; use the [MODIS sinusoidal grid](http://www.geohealth.ou.edu/modis_v5/modis.shtml) for reference. 327 | 328 | List MODIS Subdatasets in a given HDF (conf. the [MODIS products table](https://lpdaac.usgs.gov/products/modis_products_table/)) 329 | 330 | gdalinfo longFileName.hdf | grep SUBDATASET 331 | 332 | Make TIFs from each file in list; replace 'MOD12Q1:Land_Cover_Type_1' with desired Subdataset name 333 | 334 | mkdir output 335 | find . '*.hdf' -exec gdalwarp -of GTiff 'HDF4_EOS:EOS_GRID:"{}":MOD12Q1:Land_Cover_Type_1' output/{}.tif \; 336 | 337 | Merge all .tifs in output directory into single file 338 | 339 | gdal_merge.py -o output/Merged_Landcover.tif output/*.tif 340 | 341 | __BASH functions__ 342 | _Size Functions_ 343 | This size function echos the pixel dimensions of a given file in the format expected by gdalwarp. 344 | 345 | function gdal_size() { 346 | SIZE=$(gdalinfo $1 |\ 347 | grep 'Size is ' |\ 348 | cut -d\ -f3-4 |\ 349 | sed 's/,//g') 350 | echo -n "$SIZE" 351 | } 352 | 353 | This can be used to easily resample one raster to the dimensions of another: 354 | 355 | gdalwarp -ts $(gdal_size bigraster.tif) -r cubicspline smallraster.tif resampled_smallraster.tif 356 | 357 | _Extent Functions_ 358 | These extent functions echo the extent of the given file in the order/format expected by gdal_translate -projwin. 359 | (Originally from [Linfiniti](http://linfiniti.com/2009/09/clipping-rasters-with-gdal-using-polygons/)). 360 | 361 | function gdal_extent() { 362 | if [ -z "$1" ]; then 363 | echo "Missing arguments. Syntax:" 364 | echo " gdal_extent " 365 | return 366 | fi 367 | EXTENT=$(gdalinfo $1 |\ 368 | grep "Upper Left\|Lower Right" |\ 369 | sed "s/Upper Left //g;s/Lower Right //g;s/).*//g" |\ 370 | tr "\n" " " |\ 371 | sed 's/ *$//g' |\ 372 | tr -d "[(,]") 373 | echo -n "$EXTENT" 374 | } 375 | 376 | function ogr_extent() { 377 | if [ -z "$1" ]; then 378 | echo "Missing arguments. Syntax:" 379 | echo " ogr_extent " 380 | return 381 | fi 382 | EXTENT=$(ogrinfo -al -so $1 |\ 383 | grep Extent |\ 384 | sed 's/Extent: //g' |\ 385 | sed 's/(//g' |\ 386 | sed 's/)//g' |\ 387 | sed 's/ - /, /g') 388 | EXTENT=`echo $EXTENT | awk -F ',' '{print $1 " " $4 " " $3 " " $2}'` 389 | echo -n "$EXTENT" 390 | } 391 | 392 | function ogr_layer_extent() { 393 | if [ -z "$2" ]; then 394 | echo "Missing arguments. Syntax:" 395 | echo " ogr_extent " 396 | return 397 | fi 398 | EXTENT=$(ogrinfo -so $1 $2 |\ 399 | grep Extent |\ 400 | sed 's/Extent: //g' |\ 401 | sed 's/(//g' |\ 402 | sed 's/)//g' |\ 403 | sed 's/ - /, /g') 404 | EXTENT=`echo $EXTENT | awk -F ',' '{print $1 " " $4 " " $3 " " $2}'` 405 | echo -n "$EXTENT" 406 | } 407 | 408 | Extents can be passed directly into a gdal_translate command like so: 409 | 410 | gdal_translate -projwin $(ogr_extent boundingbox.shp) input.tif clipped_output.tif 411 | 412 | or 413 | 414 | gdal_translate -projwin $(gdal_extent target_crop.tif) input.tif clipped_output.tif 415 | 416 | This can be a useful way to quickly crop one raster to the same extent as another. Add these to your ~/.bash_profile file for easy terminal access. 417 | 418 | 419 | Sources 420 | --- 421 | 422 | 423 | 424 | 425 | 426 | 427 | 428 | 429 | 430 | 431 | 432 | 433 | 434 | 435 | 436 | 437 | 438 | 439 | 440 | 441 | 442 | 443 | 444 | 445 | 446 | 447 | 448 | 449 | 450 | 451 | 452 | 453 | 454 | 455 | 456 | --------------------------------------------------------------------------------