Está en la página 1de 104

Procesamiento y análisis de

datos espaciales en
GRASS GIS

Dra. Verónica Andreo

1 / 49
Ejercicio: Clasi cación supervisada
basada en objetos con datos SPOT


2 / 49
Contenidos

3 / 49
Contenidos
Mejoramiento del contraste (ecualización del histograma)

3 / 49
Contenidos
Mejoramiento del contraste (ecualización del histograma)
Calcular índices espectrales y texturas de GLCM

3 / 49
Contenidos
Mejoramiento del contraste (ecualización del histograma)
Calcular índices espectrales y texturas de GLCM
Segmentación manual (ensayo y error)

3 / 49
Contenidos
Mejoramiento del contraste (ecualización del histograma)
Calcular índices espectrales y texturas de GLCM
Segmentación manual (ensayo y error)
Segmentación con USPO

3 / 49
Contenidos
Mejoramiento del contraste (ecualización del histograma)
Calcular índices espectrales y texturas de GLCM
Segmentación manual (ensayo y error)
Segmentación con USPO
Cómputo de las estadísticas de los segmentos

3 / 49
Contenidos
Mejoramiento del contraste (ecualización del histograma)
Calcular índices espectrales y texturas de GLCM
Segmentación manual (ensayo y error)
Segmentación con USPO
Cómputo de las estadísticas de los segmentos
Colecta y etiquetado de datos de entrenamiento y validación

3 / 49
Contenidos
Mejoramiento del contraste (ecualización del histograma)
Calcular índices espectrales y texturas de GLCM
Segmentación manual (ensayo y error)
Segmentación con USPO
Cómputo de las estadísticas de los segmentos
Colecta y etiquetado de datos de entrenamiento y validación
Clasi cación supervisada por Machine Learning

3 / 49
Contenidos
Mejoramiento del contraste (ecualización del histograma)
Calcular índices espectrales y texturas de GLCM
Segmentación manual (ensayo y error)
Segmentación con USPO
Cómputo de las estadísticas de los segmentos
Colecta y etiquetado de datos de entrenamiento y validación
Clasi cación supervisada por Machine Learning
Validación

3 / 49
Datos para el ejercicio

SPOT 6
VIS - NIR (6 m)
PAN (1.5 m)
Datos corregidos y
fusionados

4 / 49
 Datos y código para la sesión 

Descargar los datos SPOT desde el aula virtual y


mover a la carpeta $HOME/gisdata
Descargar el código para seguir el ejercicio

5 / 49
 Tareas
Crear un mapset obia_spot en el location
posgar2007_4_cba e importar la imagen SPOT desde
la GUI forzando la resolución a 1.5m
Alinear la región a la extensión y resolución de alguna de
las bandas importadas
Mostrar la combinación RGB color natural (1: azul, 2:
verde, 3: rojo, 4: NIR)
Hacer una ecualización de histograma para mejorar el
contraste de visualización
6 / 49
Importar datos y visualizar
#!/bin/bash
#######################################################################
# Commands for the OBIA exercise within IG MSc Course Image Processing
# Author: Veronica Andreo based on Grippa et al 2017.
# Date: July, 2020
#######################################################################
 
 
#
# Create mapset and import data
#
 
 
# create mapset
g.mapset -c mapset=obia_spot
 
# import pansharpened SPOT data
r.import input=$HOME/gisdata/SPOT_20180621_PANSHARP_p.tif \
t t SPOT 20180621 PANSHARP \

7 / 49
Importar datos y visualizar
# Date: July, 2020
#######################################################################
 
 
#
# Create mapset and import data
#
 
 
# create mapset
g.mapset -c mapset=obia_spot
 
# import pansharpened SPOT data
r.import input=$HOME/gisdata/SPOT_20180621_PANSHARP_p.tif \
output=SPOT_20180621_PANSHARP \
resolution=value \
resolution_value=1.5
 
# import SPOT PAN band
i i $ / i d / if \
Crear mapset

7 / 49
Importar datos y visualizar
# Create mapset and import data
#
 
 
# create mapset
g.mapset -c mapset=obia_spot
 
# import pansharpened SPOT data
r.import input=$HOME/gisdata/SPOT_20180621_PANSHARP_p.tif \
output=SPOT_20180621_PANSHARP \
resolution=value \
resolution_value=1.5
 
# import SPOT PAN band
r.import input=$HOME/gisdata/SPOT_20180621_PAN.tif \
output=SPOT_20180621_PAN \
resolution=value \
resolution_value=1.5

Importar bandas multi-espectrales

7 / 49
Importar datos y visualizar
 
# import pansharpened SPOT data
r.import input=$HOME/gisdata/SPOT_20180621_PANSHARP_p.tif \
output=SPOT_20180621_PANSHARP \
resolution=value \
resolution_value=1.5
 
# import SPOT PAN band
r.import input=$HOME/gisdata/SPOT_20180621_PAN.tif \
output=SPOT_20180621_PAN \
resolution=value \
resolution_value=1.5
 
# align region to one of the raster bands
g.region -p raster=SPOT_20180621_PANSHARP.1 \
save=obia_full
 
 
#
Importar banda pancromática

7 / 49
Importar datos y visualizar
resolution_value=1.5
 
# import SPOT PAN band
r.import input=$HOME/gisdata/SPOT_20180621_PAN.tif \
output=SPOT_20180621_PAN \
resolution=value \
resolution_value=1.5
 
# align region to one of the raster bands
g.region -p raster=SPOT_20180621_PANSHARP.1 \
save=obia_full
 
 
#
# Display RGB with enhanced contrast
#
 
 
# set grey color table to RGB bands
Alinear región y guardar la con guración

7 / 49
Importar datos y visualizar
# align region to one of the raster bands
g.region -p raster=SPOT_20180621_PANSHARP.1 \
save=obia_full
 
 
#
# Display RGB with enhanced contrast
#
 
 
# set grey color table to RGB bands
r.colors \
map=SPOT_20180621_PANSHARP.1,SPOT_20180621_PANSHARP.2,SPOT_20180621_P
color=grey
 
# display RGB
d.mon wx0
d.rgb red=SPOT_20180621_PANSHARP.3 \
green=SPOT 20180621 PANSHARP.2 \
Establecer grey como paleta de colores para bandas RGB

7 / 49
Importar datos y visualizar
 
 
# set grey color table to RGB bands
r.colors \
map=SPOT_20180621_PANSHARP.1,SPOT_20180621_PANSHARP.2,SPOT_20180621_P
color=grey
 
# display RGB
d.mon wx0
d.rgb red=SPOT_20180621_PANSHARP.3 \
green=SPOT_20180621_PANSHARP.2 \
blue=SPOT_20180621_PANSHARP.1
 
# enhance contrast
i.colors.enhance red=SPOT_20180621_PANSHARP.3 \
green=SPOT_20180621_PANSHARP.2 \
blue=SPOT_20180621_PANSHARP.1 \
strength=95

Mostrar composición RGB

7 / 49
Importar datos y visualizar
 
# display RGB
d.mon wx0
d.rgb red=SPOT_20180621_PANSHARP.3 \
green=SPOT_20180621_PANSHARP.2 \
blue=SPOT_20180621_PANSHARP.1
 
# enhance contrast
i.colors.enhance red=SPOT_20180621_PANSHARP.3 \
green=SPOT_20180621_PANSHARP.2 \
blue=SPOT_20180621_PANSHARP.1 \
strength=95
 
 
#
# Are there NULL values?
#
 

Ecualización de colores

7 / 49
Composición RGB 321 color natural - SPOT 6

8 / 49
 Hay valores nulos? 
#!/bin/bash
#######################################################################
# Commands for the OBIA exercise within IG MSc Course Image Processing
# Author: Veronica Andreo based on Grippa et al 2017.
# Date: July, 2020
#######################################################################
 
 
#
# Create mapset and import data
#
 
 
# create mapset
g.mapset -c mapset=obia_spot
 
# import pansharpened SPOT data
r.import input=$HOME/gisdata/SPOT_20180621_PANSHARP_p.tif \
SPOT 20 8062 PANSHARP \

 Si hubiera valores nulos, se deben rellenar antes de comenzar 

9 / 49
 Hay valores nulos? 
# enhance contrast
i.colors.enhance red=SPOT_20180621_PANSHARP.3 \
green=SPOT_20180621_PANSHARP.2 \
blue=SPOT_20180621_PANSHARP.1 \
strength=95
 
 
#
# Are there NULL values?
#
 
 
# one band
r.univar map=SPOT_20180621_PANSHARP.2
 
# joint stats for all the bands
r.univar \
map=SPOT_20180621_PANSHARP.1,SPOT_20180621_PANSHARP.2,SPOT_20180621_P
 

Valores nulos en una banda

 Si hubiera valores nulos, se deben rellenar antes de comenzar 


9 / 49
 Hay valores nulos? 
#
# Are there NULL values?
#
 
 
# one band
r.univar map=SPOT_20180621_PANSHARP.2
 
# joint stats for all the bands
r.univar \
map=SPOT_20180621_PANSHARP.1,SPOT_20180621_PANSHARP.2,SPOT_20180621_P
 
 
#
# Generate variables from raw data
#
 
 
# ti t t ti i d
Valores nulos en varias bandas

 Si hubiera valores nulos, se deben rellenar antes de comenzar 


9 / 49
Índices espectrales y texturas GLCM
#!/bin/bash
#######################################################################
# Commands for the OBIA exercise within IG MSc Course Image Processing
# Author: Veronica Andreo based on Grippa et al 2017.
# Date: July, 2020
#######################################################################
 
 
#
# Create mapset and import data
#
 
 
# create mapset
g.mapset -c mapset=obia_spot
 
# import pansharpened SPOT data
r.import input=$HOME/gisdata/SPOT_20180621_PANSHARP_p.tif \
t t SPOT 20180621 PANSHARP \

10 / 49
Índices espectrales y texturas GLCM
r.univar \
map=SPOT_20180621_PANSHARP.1,SPOT_20180621_PANSHARP.2,SPOT_20180621_P
 
 
#
# Generate variables from raw data
#
 
 
# estimate vegetation index
i.vi \
output=SPOT_20180621_NDVI \
viname=ndvi \
red=SPOT_20180621_PANSHARP.3 \
nir=SPOT_20180621_PANSHARP.4
 
# install i.wi
g.extension i.wi

Estimar NDVI

10 / 49
Índices espectrales y texturas GLCM
output=SPOT_20180621_NDVI \
viname=ndvi \
red=SPOT_20180621_PANSHARP.3 \
nir=SPOT_20180621_PANSHARP.4
 
# install i.wi
g.extension i.wi
 
# estimate water index
i.wi \
output=SPOT_20180621_NDWI \
winame=ndwi_mf \
green=SPOT_20180621_PANSHARP.2 \
nir=SPOT_20180621_PANSHARP.4
 
# set ndwi color palette
r.colors map=SPOT_20180621_NDWI color=ndwi
 
# ti t t t
Instalar extensión i.wi y estimar NDWI

10 / 49
Índices espectrales y texturas GLCM
g.extension i.wi
 
# estimate water index
i.wi \
output=SPOT_20180621_NDWI \
winame=ndwi_mf \
green=SPOT_20180621_PANSHARP.2 \
nir=SPOT_20180621_PANSHARP.4
 
# set ndwi color palette
r.colors map=SPOT_20180621_NDWI color=ndwi
 
# estimate textures measures
r.texture \
input=SPOT_20180621_PAN \
output=SPOT_20180621 \
size=7 \
distance=3 \
method=idm,asm
Establecer la paleta de colores ndwi

10 / 49
Índices espectrales y texturas GLCM
_ \
green=SPOT_20180621_PANSHARP.2 \
nir=SPOT_20180621_PANSHARP.4
 
# set ndwi color palette
r.colors map=SPOT_20180621_NDWI color=ndwi
 
# estimate textures measures
r.texture \
input=SPOT_20180621_PAN \
output=SPOT_20180621 \
size=7 \
distance=3 \
method=idm,asm
 
# set color table to grey for texture bands
r.colors -e map=SPOT_20180621_IDM color=grey
r.colors -e map=SPOT_20180621_ASM color=grey
 
# f l t ith ll 4 b d
Estimar medidas de textura: IDM y ASM

10 / 49
Índices espectrales y texturas GLCM
# estimate textures measures
r.texture \
input=SPOT_20180621_PAN \
output=SPOT_20180621 \
size=7 \
distance=3 \
method=idm,asm
 
# set color table to grey for texture bands
r.colors -e map=SPOT_20180621_IDM color=grey
r.colors -e map=SPOT_20180621_ASM color=grey
 
# frame plot with all 4 bands
d.mon cairo out=obia_frames.png width=400 height=300 resolution=4
 
d.frame -c frame=first at=0,50,0,50
d.rast map=SPOT_20180621_NDVI
d.text text='NDVI' color=black font=sans size=10

Establecer paleta grey para bandas de textura

10 / 49
Índices espectrales y texturas GLCM a partir de bandas SPOT

11 / 49
Sobre qué banda calculamos las texturas?

12 / 49
Si no contamos con una banda pancromática,
podemos crearla promediando las bandas visibles

# create pan-vis from RGB (if no pan available)


R=SPOT_20180621_PANSHARP.3
G=SPOT_20180621_PANSHARP.2
B=SPOT_20180621_PANSHARP.1
 
r.mapcalc \
expression="PANVIS = round(($R + $G + $B) / 3)"

13 / 49
Segmentación
Búsqueda de umbrales de sub y sobre-segmentación
#!/bin/bash
#######################################################################
# Commands for the OBIA exercise within IG MSc Course Image Processing
# Author: Veronica Andreo based on Grippa et al 2017.
# Date: July, 2020
#######################################################################
 
 
#
# Create mapset and import data
#
 
 
# create mapset
g.mapset -c mapset=obia_spot
 
# import pansharpened SPOT data
r.import input=$HOME/gisdata/SPOT_20180621_PANSHARP_p.tif \
SPOT 20 8062 PANSHARP \
14 / 49
Segmentación
Búsqueda de umbrales de sub y sobre-segmentación
d.frame c frame=fourth at=50,100,50,100
d.rast map=SPOT_20180621_ASM
d.text text='ASM' color=white font=sans size=10
 
d.mon -r
 
 
#
# Segmentation: manual trial and error for threshold values determinati
#
 
 
# create imagery group (only bands)
i.group group=spot_bands \
input=SPOT_20180621_PANSHARP.1,SPOT_20180621_PANSHARP.2,SPOT_20180621
 
# set smaller region
g.region -p \
n=6525171 s=6523179 \
Crear grupo con las bandas únicamente
14 / 49
Segmentación
Búsqueda de umbrales de sub y sobre-segmentación
# Segmentation: manual trial and error for threshold values determinati
#
 
 
# create imagery group (only bands)
i.group group=spot_bands \
input=SPOT_20180621_PANSHARP.1,SPOT_20180621_PANSHARP.2,SPOT_20180621
 
# set smaller region
g.region -p \
n=6525171 s=6523179 \
w=4390557 e=4393257 \
save=obia_subset
 
# run segmentation - small threshold
i.segment \
group=spot_bands \
output=segment_001\
threshold=0 01 \
De nir una región más pequeña y salvarla
14 / 49
Segmentación
Búsqueda de umbrales de sub y sobre-segmentación
# set smaller region
g.region -p \
n=6525171 s=6523179 \
w=4390557 e=4393257 \
save=obia_subset
 
# run segmentation - small threshold
i.segment \
group=spot_bands \
output=segment_001\
threshold=0.01 \
memory=2000
# convert output to vector
r.to.vect -tv input=segment_001 \
output=segment_001 \
type=area
 
# run segmentation - larger threshold
i.segment \

Ejecutar una segmentación con umbral pequeño


14 / 49
Segmentación
Búsqueda de umbrales de sub y sobre-segmentación
# convert output to vector
r.to.vect -tv input=segment_001 \
output=segment_001 \
type=area
 
# run segmentation - larger threshold
i.segment \
group=spot_bands \
output=segment_005 \
threshold=0.05 \
memory=2000
# convert output to vector
r.to.vect -tv \
input=segment_005 \
output=segment_005 \
type=area
 
 
#
Ejecutar una segmentación con umbral más grande
14 / 49
Sobre-segmentado Sub-segmentado

15 / 49
 Tarea

Se animan a probar con otros valores y en otras regiones?

16 / 49
Segmentación
Búsqueda automática de umbrales por optimización
i.segment.uspo
Altamente intensivo para un área grande y muchas
combinaciones de parámetros
Limitar el tamaño de la región computacional
Limitar el rango de los parámetros
Crear superpixels para usarlos como semillas
Cortar la imagen en tiles (i.cutlines) y paralelizar la
USPO
17 / 49
Generación de semillas
i.superpixels.slic
También puede utilizarse para la segmentación real
Muy rápido para reagrupar pequeñas cantidades de
píxeles similares
Usar para reducir el número de píxeles en un factor
de 4-5 y acelerar i.segment.uspo
Baja compactación para mantener la separación
espectral

18 / 49
USPO con superpixels como semillas
#!/bin/bash
#######################################################################
# Commands for the OBIA exercise within IG MSc Course Image Processing
# Author: Veronica Andreo based on Grippa et al 2017.
# Date: July, 2020
#######################################################################
 
 
#
# Create mapset and import data
#
 
 
# create mapset
g.mapset -c mapset=obia_spot
 
# import pansharpened SPOT data
r.import input=$HOME/gisdata/SPOT_20180621_PANSHARP_p.tif \
t t SPOT 20180621 PANSHARP \

19 / 49
USPO con superpixels como semillas
# convert output to vector
r.to.vect -tv \
input=segment_005 \
output=segment_005 \
type=area
 
 
#
# Superpixels
#
 
 
# install i.superpixels.slic
g.extension i.superpixels.slic
 
# run superpixel segm to use as seeds
i.superpixels.slic \
input=spot_bands \
output=superpixels \
Instalar la extensión

19 / 49
USPO con superpixels como semillas
# Superpixels
#
 
 
# install i.superpixels.slic
g.extension i.superpixels.slic
 
# run superpixel segm to use as seeds
i.superpixels.slic \
input=spot_bands \
output=superpixels \
step=2 \
compactness=0.7 \
memory=2000
 
 
#
# Segmentation with USPO
#
Ejecutar i.superpixels.slic con bajo valor de compactación

19 / 49
RGB y resultado de la ejecución de i.superpixels.slic

20 / 49
Cuántas semillas se generaron? Qué factor de reducción se
consigue en comparación a usar todos los pixeles?

Dar una mirada a r.info y g.region


21 / 49
USPO con superpixels como semillas
#!/bin/bash
#######################################################################
# Commands for the OBIA exercise within IG MSc Course Image Processing
# Author: Veronica Andreo based on Grippa et al 2017.
# Date: July, 2020
#######################################################################
 
 
#
# Create mapset and import data
#
 
 
# create mapset
g.mapset -c mapset=obia_spot
 
# import pansharpened SPOT data
r.import input=$HOME/gisdata/SPOT_20180621_PANSHARP_p.tif \
t t SPOT 20180621 PANSHARP \

22 / 49
USPO con superpixels como semillas
input spot_bands \
output=superpixels \
step=2 \
compactness=0.7 \
memory=2000
 
 
#
# Segmentation with USPO
#
 
 
# install extensions
g.extension r.neighborhoodmatrix
g.extension i.segment.uspo
 
# run segmentation with uspo
i.segment.uspo group=spot_bands \
output=uspo_parameters.csv \

Instalar las extensiones

22 / 49
USPO con superpixels como semillas
 
# install extensions
g.extension r.neighborhoodmatrix
g.extension i.segment.uspo
 
# run segmentation with uspo
i.segment.uspo group=spot_bands \
output=uspo_parameters.csv \
region=obia_subset \
seeds=superpixels \
segment_map=segs \
threshold_start=0.005 \
threshold_stop=0.05 \
threshold_step=0.005 \
minsizes=3 number_best=5 \
memory=2000 processes=4
 
# convert to vector the rank1
r to vect -tv \
Ejecutar la segmentación con optimización

22 / 49
USPO con superpixels como semillas
seeds=superpixels \
segment_map=segs \
threshold_start=0.005 \
threshold_stop=0.05 \
threshold_step=0.005 \
minsizes=3 number_best=5 \
memory=2000 processes=4
 
# convert to vector the rank1
r.to.vect -tv \
input=segs_obia_subset_rank1 \
output=segs \
type=area
 
 
#
# Extraer estadisticas de los segmentos
#

Convertir el "mejor" resultado a vector

22 / 49
Zoom al resultado de ejecutar la segmentación con USPO

23 / 49
Cuántos segmentos obtuvieron?

Dar una mirada a v.info

24 / 49
Estadísticas: i.segment.stats
#!/bin/bash
#######################################################################
# Commands for the OBIA exercise within IG MSc Course Image Processing
# Author: Veronica Andreo based on Grippa et al 2017.
# Date: July, 2020
#######################################################################
 
 
#
# Create mapset and import data
#
 
 
# create mapset
g.mapset -c mapset=obia_spot
 
# import pansharpened SPOT data
r.import input=$HOME/gisdata/SPOT_20180621_PANSHARP_p.tif \
t t SPOT 20180621 PANSHARP \

25 / 49
Estadísticas: i.segment.stats
# convert to vector the rank1
r.to.vect -tv \
input=segs_obia_subset_rank1 \
output=segs \
type=area
 
 
#
# Extraer estadisticas de los segmentos
#
 
 
# install extensions
g.extension i.segment.stats
g.extension r.object.geometry
 
# extract stats for segments
i.segment.stats \
map=segs_obia_subset_rank1 \

Instalar las extensiones

25 / 49
Estadísticas: i.segment.stats
#
 
 
# install extensions
g.extension i.segment.stats
g.extension r.object.geometry
 
# extract stats for segments
i.segment.stats \
map=segs_obia_subset_rank1 \
rasters=SPOT_20180621_ASM,SPOT_20180621_IDM,SPOT_20180621_NDVI,SPOT_2
raster_statistics=mean,stddev \
area_measures=area,perimeter,compact_circle,compact_square \
vectormap=segs_stats \
processes=4
 
 
#
# Generate ground truth points and label them
Ejecutar i.segment.stats

25 / 49
Tabla de atributos con las estadísticas estimadas para cada objeto

26 / 49
Datos de entrenamiento
#!/bin/bash
#######################################################################
# Commands for the OBIA exercise within IG MSc Course Image Processing
# Author: Veronica Andreo based on Grippa et al 2017.
# Date: July, 2020
#######################################################################
 
 
#
# Create mapset and import data
#
 
 
# create mapset
g.mapset -c mapset=obia_spot
 
# import pansharpened SPOT data
r.import input=$HOME/gisdata/SPOT_20180621_PANSHARP_p.tif \
t t SPOT 20180621 PANSHARP \

27 / 49
Datos de entrenamiento
rasters=SPOT_20180621_ASM,SPOT_20180621_IDM,SPOT_20180621_NDVI,SPOT_2
raster_statistics=mean,stddev \
area_measures=area,perimeter,compact_circle,compact_square \
vectormap=segs_stats \
processes=4
 
 
#
# Generate ground truth points and label them
#
 
 
# get info of labeled points
v.info labeled_points
 
# copy vector to current mapset (access to tables from different mapset
g.copy vector=labeled_points@PERMANENT,labeled_points
 
# get n mber of points per class
Info básica de los puntos de entrenamiento provistos

27 / 49
Datos de entrenamiento
 
 
#
# Generate ground truth points and label them
#
 
 
# get info of labeled points
v.info labeled_points
 
# copy vector to current mapset (access to tables from different mapset
g.copy vector=labeled_points@PERMANENT,labeled_points
 
# get number of points per class
db.select \
sql="SELECT train_class,COUNT(cat) as count_class
FROM labeled_points
GROUP BY train_class"
 
Copiarse el vector al mapset obia_spot

27 / 49
Datos de entrenamiento
 
 
# get info of labeled points
v.info labeled_points
 
# copy vector to current mapset (access to tables from different mapset
g.copy vector=labeled_points@PERMANENT,labeled_points
 
# get number of points per class
db.select \
sql="SELECT train_class,COUNT(cat) as count_class
FROM labeled_points
GROUP BY train_class"
 
# select segments that are below labeled points
v.select \
ainput=segs_stats \
binput=labeled_points \
output=train segments \
Cuántos puntos de cada clase tenemos?

27 / 49
Datos de entrenamiento
g.copy vector=labeled_points@PERMANENT,labeled_points
 
# get number of points per class
db.select \
sql="SELECT train_class,COUNT(cat) as count_class
FROM labeled_points
GROUP BY train_class"
 
# select segments that are below labeled points
v.select \
ainput=segs_stats \
binput=labeled_points \
output=train_segments \
operator=overlap
 
# get info of segments
v.info train_segments
 
# add column to train segments
Seleccionar segmentos sobre los cuales tenemos puntos de entrenamiento

27 / 49
Datos de entrenamiento
FROM labeled_points
GROUP BY train_class"
 
# select segments that are below labeled points
v.select \
ainput=segs_stats \
binput=labeled_points \
output=train_segments \
operator=overlap
 
# get info of segments
v.info train_segments
 
# add column to train segments
v.db.addcolumn train_segments \
column="class int"
 
# assign label from points to segments
v distance from=train segments \
Cuántos segmentos contienen puntos de entrenamiento?

27 / 49
Selección de segmentos con puntos de entrenamiento

28 / 49
Datos de entrenamiento
#!/bin/bash
#######################################################################
# Commands for the OBIA exercise within IG MSc Course Image Processing
# Author: Veronica Andreo based on Grippa et al 2017.
# Date: July, 2020
#######################################################################
 
 
#
# Create mapset and import data
#
 
 
# create mapset
g.mapset -c mapset=obia_spot
 
# import pansharpened SPOT data
r.import input=$HOME/gisdata/SPOT_20180621_PANSHARP_p.tif \
t t SPOT 20180621 PANSHARP \

29 / 49
g
Datos de entrenamiento p
v.select \
ainput=segs_stats \
binput=labeled_points \
output=train_segments \
operator=overlap
 
# get info of segments
v.info train_segments
 
# add column to train segments
v.db.addcolumn train_segments \
column="class int"
 
# assign label from points to segments
v.distance from=train_segments \
to=labeled_points \
upload=to_attr \
column=class \

Agregar columna al vector con los segmentos para luego transferir la clase

29 / 49
Datos de entrenamiento
 
# get info of segments
v.info train_segments
 
# add column to train segments
v.db.addcolumn train_segments \
column="class int"
 
# assign label from points to segments
v.distance from=train_segments \
to=labeled_points \
upload=to_attr \
column=class \
to_column=train_class
 
# group training segments per class
db.select \
sql="SELECT class,COUNT(cat) as count_class
FROM train segments
Asignar la clase de los puntos a los segmentos

29 / 49
Datos de entrenamiento
column class int
 
# assign label from points to segments
v.distance from=train_segments \
to=labeled_points \
upload=to_attr \
column=class \
to_column=train_class
 
# group training segments per class
db.select \
sql="SELECT class,COUNT(cat) as count_class
FROM train_segments
GROUP BY class"
 
 
#
# Classification with Machine Learning
#

Cuántos segmentos de cada clase tenemos?

29 / 49
Datos de entrenamiento

Asignación de colores
interactivamente

Ir agregando valores
Seleccionar colores
Previsualizar
Guardar la paleta creada
como obia_urban para reusar
posteriormente

30 / 49
Selección y etiquetado de datos de
entrenamiento y validación

Ejecutar una clasi cación no supervisada con 10


clases
Extraer una x cantidad de puntos por clase
(r.sample.category)
Etiquetar los puntos manualmente
Usar puntos para transferir las etiquetas a los
segmentos como ya vimos

31 / 49
# Unsupervised classification
i.group group=spot_all \
input=SPOT_20180621_ASM,SPOT_20180621_IDM,SPOT_20180621_NDVI,SPOT_201
i.cluster group=spot_all signaturefile=sig classes=10
i.maxlik group=spot_all signaturefile=sig output=uns_clas
 
# install extension
g.extension r.sample.category
 
# get n points per class
r.sample.category input=uns_clas \
output=uns_clas_points \
npoints=150
 
# Manually label points
 

32 / 49
Clasi cación con Machine learning
#!/bin/bash
#######################################################################
# Commands for the OBIA exercise within IG MSc Course Image Processing
# Author: Veronica Andreo based on Grippa et al 2017.
# Date: July, 2020
#######################################################################
 
 
#
# Create mapset and import data
#
 
 
# create mapset
g.mapset -c mapset=obia_spot
 
# import pansharpened SPOT data
r.import input=$HOME/gisdata/SPOT_20180621_PANSHARP_p.tif \
t t SPOT 20180621 PANSHARP \

33 / 49
Clasi cación con Machine learning
 
# group training segments per class
db.select \
sql="SELECT class,COUNT(cat) as count_class
FROM train_segments
GROUP BY class"
 
 
#
# Classification with Machine Learning
#
 
 
# install extension
g.extension v.class.mlR
 
# run classification
v.class.mlR -nf \
segments_map=segs_stats \
Instalar la extensión

33 / 49
Clasi cación con Machine learning
g.extension v.class.mlR
 
# run classification
v.class.mlR -nf \
segments_map=segs_stats \
training_map=train_segments \
train_class_column=class \
output_class_column=class_rf \
classified_map=classification \
raster_segments_map=segs_obia_subset_rank1 \
classifier=rf \
folds=5 partitions=10 tunelength=10 \
weighting_modes=smv \
weighting_metric=accuracy \
output_model_file=model \
variable_importance_file=var_imp.txt \
accuracy_file=accuracy.csv \
classification_results=all_results.csv \
model_details=classifier_runs.txt \

Ejecutar la clasi cación

33 / 49
Clasi cación con Machine learning
weighting_metric=accuracy \
output_model_file=model \
variable_importance_file=var_imp.txt \
accuracy_file=accuracy.csv \
classification_results=all_results.csv \
model_details=classifier_runs.txt \
r_script_file=Rscript_mlR.R \
processes=4
 
# set color table that we created interactively
r.colors \
map=classification_rf \
rules=obia_urban
 
 
#
# Validation using a new set of data
#

Establecer paleta de colores

33 / 49
Resultado de la clasi cación supervisada con Machine Learning basada en objetos

34 / 49

El proceso de clasi cación usualmente conlleva una serie
de iteraciones que implican selección de variables más
importantes, búsqueda de más/mejores datos de
entrenamiento y validación

35 / 49
Validación
Se usan datos independientes para validar las
clasi caciones
Se construye una matriz de confusión que permite
visualizar los errores por clase en los elementos que
están fuera de la diagonal
Se estiman varias medidas relacionadas a la
precisión, ej.: overall accuracy y kappa

36 / 49
Validación
Distintas opciones:
1 Generar un nuevo set de puntos y etiquetarlos
2 Separar el set de puntos etiquetados en train y test
de antemano

37 / 49
Validación en GRASS GIS
r.kappa
Necesita mapas raster como input
Transformar los segmentos de validación a
formato raster usando la columna class como
fuente de valores para los pixeles

38 / 49
 Tarea

Generar un set de validación de al menos 50 segmentos y


ejecutar r.kappa

39 / 49
Validación en GRASS GIS
#!/bin/bash
#######################################################################
# Commands for the OBIA exercise within IG MSc Course Image Processing
# Author: Veronica Andreo based on Grippa et al 2017.
# Date: July, 2020
#######################################################################
 
 
#
# Create mapset and import data
#
 
 
# create mapset
g.mapset -c mapset=obia_spot
 
# import pansharpened SPOT data
r.import input=$HOME/gisdata/SPOT_20180621_PANSHARP_p.tif \
SPOT 20 8062 PANSHARP \

40 / 49
Validación en GRASS GIS
 
# set color table that we created interactively
r.colors \
map=classification_rf \
rules=obia_urban
 
 
#
# Validation using a new set of data
#
 
 
# convert labeled test segments to raster
v.to.rast map=testing \
use=attr \
attribute_column=class \
output=testing
 
# create confusion matrix and estimate precision measures
Una vez creado el vector de segmentos con etiquetas testing, convertirlo a formato raster

40 / 49
Validación en GRASS GIS
# Validation using a new set of data
#
 
 
# convert labeled test segments to raster
v.to.rast map=testing \
use=attr \
attribute_column=class \
output=testing
 
# create confusion matrix and estimate precision measures
r.kappa \
classification=classification_rf \
reference=testing
 
 
#
# Alternatively...
#
Ejecutar r.kappa

40 / 49
Alternativamente, podemos separar el set de puntos
etiquetados en train y test

Vamos a 
41 / 49
#!/bin/bash
 
####################################################
# Commands for the OBIA exercise within IG MSc Cours
# Author: Veronica Andreo based on Grippa et al 2017
# Date: July, 2020
####################################################
 
 
#
# Create mapset and import data
#

42 / 49
attribute_column=class \
output=testing
 
# create confusion matrix and estimate precision mea
r.kappa \
classification=classification_rf \
reference=testing
 
 
#
# Alternatively...
#

Cargar librerías

42 / 49
r.kappa \
classification=classification_rf \
reference=testing
 
 
#
# Alternatively...
#
 
 
## Open RStudio from within GRASS terminal ##
 
# load libraries
Leer el vector desde GRASS

42 / 49
# Alternatively...
#
 
 
## Open RStudio from within GRASS terminal ##
 
# load libraries
library(rgrass7)
library(dplyr)
 
# load vector from GRASS
use sf()
Crear set de validación

42 / 49
p
 
# load libraries
library(rgrass7)
library(dplyr)
 
# load vector from GRASS
use_sf()
v <- readVECT("labeled_points")
 
# test dataset
test <- v %>%
group by(train class) %>%
Separar set de entrenamiento

42 / 49
library(dplyr)
 
# load vector from GRASS
use_sf()
v <- readVECT("labeled_points")
 
# test dataset
test <- v %>%
group_by(train_class) %>%
sample_frac(.3)
 
table(test$train_class)
Escribir los vectores a GRASS nuevamente

42 / 49
 Tarea

Ejecutar nuevamente la clasi cación usando sólo el vector


train

43 / 49
#!/bin/bash
#######################################################################
# Commands for the OBIA exercise within IG MSc Course Image Processing
# Author: Veronica Andreo based on Grippa et al 2017.
# Date: July, 2020
#######################################################################
 
 
#
# Create mapset and import data
#
 
 
# create mapset
g.mapset -c mapset=obia_spot
 
# import pansharpened SPOT data
r.import input=$HOME/gisdata/SPOT_20180621_PANSHARP_p.tif \
SPOT 20 8062 PANSHARP \

44 / 49
#
# Run classification with the train subset
#
 
 
# repeat steps described above within GRASS
 
 
#
# Validation
#
 
 
# add column to test point map
v.db.addcolumn map=test \
column="pred_class integer"
 
# query the classified map
v.what.rast map=test \
Agregar columna al vector test

44 / 49
 
 
#
# Validation
#
 
 
# add column to test point map
v.db.addcolumn map=test \
column="pred_class integer"
 
# query the classified map
v.what.rast map=test \
column=pred_class \
raster=classification_rf
 
 
#
# Confusion matrix and evaluation metrics in R
Obtener las clases predichas para los segmentos de validación

44 / 49
Validación en R
#!/bin/bash
 
#######################################################################
# Commands for the OBIA exercise within IG MSc Course Image Processing
# Author: Veronica Andreo based on Grippa et al 2017.
# Date: July, 2020
#######################################################################
 
 
#
# Create mapset and import data
#
 
 
# create mapset
g.mapset -c mapset=obia_spot
 
# import pansharpened SPOT data
i i $HOME/ i d /SPOT 20 8062 PANSHARP if \

45 / 49
Validación en R
v.db.addcolumn map=test \
column="pred_class integer"
 
# query the classified map
v.what.rast map=test \
column=pred_class \
raster=classification_rf
 
 
#
# Confusion matrix and evaluation metrics in R
#
 
 
# read the test vector
test_complete <- readVECT("test")
 
# confusion matrix and evaluation stats
library(caret)
Leer el vector test que tiene la clase predicha

45 / 49
Validación en R
p _ g
 
# query the classified map
v.what.rast map=test \
column=pred_class \
raster=classification_rf
 
 
#
# Confusion matrix and evaluation metrics in R
#
 
 
# read the test vector
test_complete <- readVECT("test")
 
# confusion matrix and evaluation stats
library(caret)
rf_CM <- confusionMatrix(as.factor(test_complete$pred_class),
as factor(test complete$train class))
Cargar la librería caret y obtener la matriz de confusión

45 / 49
 Tarea
Explorar el módulo v.kcv
Cómo se podría haber utilizado para separar los puntos
etiquetados en training y test?
Cuál es la diferencia entre dicho módulo y la separación
que realizamos en R?

Dar una mirada a v.divide.training_validation

46 / 49
47 / 49
Gracias por su atención!!

48 / 49
Próxima presentación:
Series de tiempo en GRASS GIS

Presentation powered by

49 / 49

También podría gustarte