47 votes
Accepted

how to take cell size from raster using python or GDAL or RASTERIO

With PyQGIS ras = QgsRasterLayer("raster.tif") pixelSizeX= ras.rasterUnitsPerPixelX() pixelSizeY = ras.rasterUnitsPerPixelY() print pixelSizeX 2.11668210081 print pixelSizeY 2.11685012701 With GDAL ...
gene's user avatar
  • 54.8k
37 votes
Accepted

numpy array to GTiff using rasterio without source raster

This ended up being more straightforward than I thought, with all of the capabilities lying in the rasterio.open function. Here is an example using a proj4 string instead of wkt. import rasterio ...
Bryce Frank's user avatar
  • 1,312
33 votes
Accepted

Using Rasterio or GDAL to stack multiple bands without using subprocess commands

Using rasterio you could do import rasterio file_list = ['file1.tif', 'file2.tif', 'file3.tif'] # Read metadata of first file with rasterio.open(file_list[0]) as src0: meta = src0.meta # ...
Loïc Dutrieux's user avatar
27 votes
Accepted

How can I superimpose a geopandas dataframe on a raster plot?

For me it works if I pass the matplotlib ax object explicitly to rasterio.plot.show: fig, ax = plt.subplots(figsize=(15, 15)) rasterio.plot.show(raster, ax=ax) countries.plot(ax=ax, facecolor='none', ...
joris's user avatar
  • 3,893
26 votes

Make shapefile from raster-bounds in Python

With shapely box and GeoPandas import rasterio as rio ra = rio.open("raster.tif") bounds = ra.bounds Convert bounds to shapely geometry from shapely.geometry import box geom = box(*bounds) print(...
gene's user avatar
  • 54.8k
25 votes
Accepted

Get a window from a raster in rasterio using coordinates instead of row/column offsets, width and height

Use the rasterio.windows.from_bounds function. No need for a class or mixin. import rasterio from rasterio.windows import from_bounds with rasterio.open(filepath) as src: rst = src.read(1, window=...
user2856's user avatar
  • 65.6k
21 votes
Accepted

Finding pixel location in raster using coordinates?

A rasterio way of doing this is pretty simple. Note this requires your raster be in the same projection as your coordinates. You can of course project your coordinates on the fly, but that's another ...
user2856's user avatar
  • 65.6k
20 votes
Accepted

Getting pixel values at single point using rasterio

The Python API method that supports the rio-sample command is documented here: https://rasterio.readthedocs.io/en/latest/api/rasterio._io.html#rasterio._io.DatasetReaderBase.sample src.sample() takes ...
sgillies's user avatar
  • 9,036
20 votes
Accepted

Rasterio: Use case for src.meta vs. src.profile when reading and writing rasters?

The meta property contains the basic raster metadata. The profile property is a super set of meta which includes dataset creation options (i.e inc. tiling, block size, compression etc...). You would ...
user2856's user avatar
  • 65.6k
20 votes
Accepted

Converting NetCDF dataset array to GeoTiff using rasterio Python

I would recommend looking into rioxarray for your dataset. You can open your dataset like so: import rioxarray import xarray xds = xarray.open_dataset('D:\Weather data\et_01012018.nc') If your CRS ...
snowman2's user avatar
  • 7,321
18 votes
Accepted

Creating an in memory rasterio Dataset from numpy array

Note: You can use rasterio.features.geometry_mask to mask your numpy array without writing a dataset (example). Otherwise if you want to use rasterio.mask.mask, you can create a DatasetReader manually ...
user2856's user avatar
  • 65.6k
16 votes

Using Rasterio or GDAL to stack multiple bands without using subprocess commands

If using GDAL 2.1+ it's as simple as gdal.BuildVRT then gdal.Translate: from osgeo import gdal outvrt = '/vsimem/stacked.vrt' #/vsimem is special in-memory virtual "directory" outtif = '/tmp/stacked....
user2856's user avatar
  • 65.6k
15 votes
Accepted

Extracting data from a raster

You can use rioxarray for this: import rioxarray from pyproj import Transformer # convert coordinate to raster projection lon = 15.174866 lat = 43.169129 rds = rioxarray.open_rasterio("C:/path-to-...
snowman2's user avatar
  • 7,321
14 votes

Using GeoPandas with rasterstats for zonal statistic gives error

For anyone else that stumbles upon this you can do: To get just one stat: gdf['mean'] = pd.DataFrame( zonal_stats( vectors=gdf['geometry'], raster='raster.tif', stats='...
jwilson8767's user avatar
14 votes
Accepted

Plot shapefile on top of raster using plot and imshow from matplotlib

I added that recipe to the rasterio documentation. Since it was such a simple shape, in this case I just unzipped the coords in the single record contained by the shapefile. That is, x, y = zip(*...
jdmcbr's user avatar
  • 904
14 votes

Creating an in memory rasterio Dataset from numpy array

I wrote a wrapper for rasterio.mask.mask that accepts numpy arrays as inputs. def mask_raster_with_geometry(raster, transform, shapes, **kwargs): """Wrapper for rasterio.mask.mask ...
Luna's user avatar
  • 241
14 votes
Accepted

Convert GeoJSON to GeoPandas GeoDataframe

With a list of GeoJSON-like Python geo interface geometries, simply use shapely.geometry.shape (GeoPandas uses shapely, see also Python Geo_interface applications) from shapely.geometry import shape ...
gene's user avatar
  • 54.8k
13 votes

Rasterio: tool for creating mosaic?

import rasterio import numpy as np from rasterio.merge import merge from rasterio.plot import show src1 = rasterio.open('/path/to/your/raster1') src2 = rasterio.open('/path/to/your/raster2') # ...
Charlie Parr's user avatar
  • 1,946
13 votes
Accepted

How to split multiband image into image tiles using Rasterio?

Below is a simple example (rasterio 1.0.0 or later, won't work in 0.3.6). There might be better/simpler ways (and there is an easier way if your raster is internally tiled and the tile block sizes ...
user2856's user avatar
  • 65.6k
13 votes

Finding pixel location in raster using coordinates?

Another way to do this is to use the rasterio.transform.rowcol() method described in the rasterio transform docs. Example: import numpy as np import rasterio xs = np.array([130.5, 146.0]) ys = np....
Graham S's user avatar
  • 263
13 votes
Accepted

Displaying GeoTIFF file in Python

Yes. It is just an issue related with the parameters. Without vmin and vmax, matplotlib uses nodata value as minimum value, and stretches the color map. So, you need to specify min and max value: ...
Kadir Şahbaz's user avatar
12 votes
Accepted

Merging rasters with rasterio in blocks to avoid MemoryError?

I finally solved the problem by using numpy.memmap to create a memory-map to an array stored in a binary file on disk and then processing the input rasters in windows and blocks. It might be slower ...
umbe1987's user avatar
  • 3,785
12 votes
Accepted

Using rasterio to crop image using pixel coordinates instead of geographic coordinates

You can use a window -rasterio.windows.Window to read by pixel offsets. The georeferencing can be easily calculated from the window using the source dataset window_transform method. import random ...
user2856's user avatar
  • 65.6k
11 votes
Accepted

Crop a raster using rasterio and geopandas

The issue is resolved. The issue was I misread the documentation. On a second read, the rasterio.mask documentation clearly states that polygons should be a list of GeoJSON-like dicts. I found the ...
rosswin's user avatar
  • 371
11 votes
Accepted

rasterio "invalid dtype: 'bool'"

Yes, you can write a one bit raster with rasterio*. You need to: write to a format that supports a 1bit dataset, such as GeoTIFF; ensure your numpy array is np.uint8/ubyte so rasterio doesnt raise ...
user2856's user avatar
  • 65.6k
11 votes
Accepted

How to clip an xarray to a smaller extent given the lat/lon coordinates?

min_lon = -24.995 min_lat = 25.05 max_lon = 45.50 max_lat = 71.55 cropped_ds = ds.sel(lat=slice(min_lat,max_lat), lon=slice(min_lon,max_lon))
Paula's user avatar
  • 126
11 votes

Mask xarray dataset using a shapefile

Masking NetCDF time series data from shapefile using Python You can use rioxarray. Here is an example: https://corteva.github.io/rioxarray/stable/examples/clip_geom.html import rioxarray import ...
snowman2's user avatar
  • 7,321
11 votes
Accepted

"Copy" Image coordinates to another image that is nd.array

Save result array (rf_array) as in the following lines: rf_array = df_join['Prediction'].values # returns numpy.ndarray rf_array = rf_array.reshape(img.shape[0], img.shape[1]) # rf_array = rf_array....
Kadir Şahbaz's user avatar
10 votes
Accepted

Reading S3 Sentinel-2 image files with rasterio

I believe you are using the wrong bucket name. It should be s3://sentinel-s2-l1c, not s3://sentinel-pds Try: url = 's3://sentinel-s2-l1c/tiles/10/S/DG/2015/12/7/0/B01.jp2' See more info here: http:/...
Grega M.'s user avatar
  • 764
10 votes

Add bands' name and description to the Metadata when stacking using rasterio

If using rasterio >= 1.0, use the dataset.set_band_description(self, bidx, value) method and dataset.descriptions property. Sets the description of a dataset band. Parameters ---------- bidx : int ...
user2856's user avatar
  • 65.6k

Only top scored, non community-wiki answers of a minimum length are eligible