Note
Click here to download the full example code
Extract raster values from vector file¶
Easily extract raster values from vector files (polygon/point)
Import librairies¶
import museotoolbox as mtb
import numpy as np
Load HistoricalMap dataset¶
raster,vector = mtb.datasets.load_historical_data()
Extract raster values with no vector information¶
X = mtb.processing.extract_ROI(raster,vector)
print("Vector contains {} pixels".format(X.shape[0]))
print("Raster contains {} bands per pixel".format(X.shape[1]))
Out:
Vector contains 12657 pixels
Raster contains 3 bands per pixel
Let’s suppose you want konw to extract the label of each polygon/point
X,y = mtb.processing.extract_ROI(raster,vector,'class')
uniqueLabels = np.unique(y,return_counts=True)
for label,count in zip(*uniqueLabels):
print('label {} has {} samples'.format(label,count))
Out:
label 1 has 7544 samples
label 2 has 2296 samples
label 3 has 2283 samples
label 4 has 525 samples
label 5 has 9 samples
You can put as many fields as you want, except fields of string type
X,y,g = mtb.processing.extract_ROI(raster,vector,'class','uniquefid')
print('There are a total of {} groups'.format(np.unique(g).size))
Out:
There are a total of 17 groups
Total running time of the script: ( 0 minutes 0.165 seconds)