Reading raster file with rasterio library in Python
Reading raster files with Rasterio¶
Raster data is made up of pixels (also referred to as grid cells).\ You can find different raster file format in this link https://gdal.org/drivers/raster/index.html\ Raster data is made up of pixels (also referred to as grid cells).\ Raster grid format is data model for satellite data and other remote sensing data. For raster positions, it’s simple to understand cell size. Most common file formats include for example TIFF and GeoTIFF, ASCII Grid and Erdas Imagine .img -files.
import rasterio
import os
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# Open the file:
fp = 'C:/Users/POSITIVE/Downloads/Senegal_PVOUT_poster-map_1200x800mm-300dpi_v20191017.tif'
raster = rasterio.open(fp)
# Check type of the variable 'raster'
type(raster)
d:\programm files\python 3 8 6\lib\site-packages\rasterio\__init__.py:229: NotGeoreferencedWarning: Dataset has no geotransform set. The identity matrix may be returned. s = DatasetReader(path, driver=driver, sharing=sharing, **kwargs)
rasterio.io.DatasetReader
Reading raster file properties¶
# Projection
raster.crs
print(raster.crs)
None
# Affine transform (how raster is scaled, rotated, skewed, and/or translated)
raster.transform
Affine(1.0, 0.0, 0.0,
0.0, 1.0, 0.0)
# Dimensions
print(raster.width)
print(raster.height)
14173 9448
# Number of bands
raster.count
4
# Bounds of the file
raster.bounds
BoundingBox(left=0.0, bottom=9448.0, right=14173.0, top=0.0)
# Driver (data format)
raster.driver
'GTiff'
# No data values for all channels
raster.nodatavals
(None, None, None, None)
# All Metadata for the whole raster dataset
raster.meta
{'driver': 'GTiff',
'dtype': 'uint8',
'nodata': None,
'width': 14173,
'height': 9448,
'count': 4,
'crs': None,
'transform': Affine(1.0, 0.0, 0.0,
0.0, 1.0, 0.0)}
Band and band statistics¶
# Read the raster band as separate variable
band1 = raster.read(1)
# Check type of the variable 'band'
print(type(band1))
# Data type of the values
print(band1.dtype)
<class 'numpy.ndarray'> uint8
band1
array([[255, 255, 255, ..., 255, 255, 254],
[255, 255, 255, ..., 255, 255, 254],
[255, 255, 255, ..., 255, 255, 254],
...,
[255, 255, 255, ..., 255, 255, 254],
[255, 255, 255, ..., 255, 255, 254],
[255, 255, 255, ..., 255, 255, 254]], dtype=uint8)
# Read all bands
array = raster.read()
# Calculate statistics for each band
stats = []
for band in array:
stats.append({
'min': band.min(),
'mean': band.mean(),
'median': np.median(band),
'max': band.max()})
# Show stats for each channel
stats
[{'min': 0, 'mean': 245.5374154940226, 'median': 255.0, 'max': 255},
{'min': 0, 'mean': 206.06856842442843, 'median': 255.0, 'max': 255},
{'min': 0, 'mean': 179.89878021906986, 'median': 255.0, 'max': 255},
{'min': 252, 'mean': 254.9997883299231, 'median': 255.0, 'max': 255}]
Visualizing raster layer¶
from rasterio.plot import show
# Plot band 1
show((raster, 1))
<AxesSubplot:>
Let’s see how the different bands look like by placing them next to each other:
# Initialize subplots
fig, (ax1, ax2, ax3) = plt.subplots(ncols=3, nrows=1, figsize=(10, 4), sharey=True)
# Plot Red, Green and Blue (rgb)
show((raster, 4), cmap='Reds', ax=ax1)
show((raster, 3), cmap='Greens', ax=ax2)
show((raster, 1), cmap='Blues', ax=ax3)
# Add titles
ax1.set_title("Red")
ax2.set_title("Green")
ax3.set_title("Blue")
Text(0.5, 1.0, 'Blue')
Histogram of raster data¶
from rasterio.plot import show_hist
show_hist(raster, bins=50, lw=0.0, stacked=False, alpha=0.3,
histtype='stepfilled', title="Histogram")
Masking and Clipping raster data¶
One common task in raster processing is to clip raster files based on a Polygon. The following example shows how to clip a large raster based on a bounding box.
from rasterio.mask import mask
from shapely.geometry import box
import geopandas as gpd
from fiona.crs import from_epsg
import pycrs
# Visualize the NIR band
show(raster, 4)
<AxesSubplot:>
Comments
Post a Comment