## ----------------------------------------------------------------------------- library(terra) landsat5 <- rast('data/rs/centralvalley-2011LT5.tif') names(landsat5) <- c('blue', 'green', 'red', 'NIR', 'SWIR1', 'SWIR2') ## ----------------------------------------------------------------------------- ndvi <- (landsat5[['NIR']] - landsat5[['red']]) / (landsat5[['NIR']] + landsat5[['red']]) ## ----kmeans, fig.width = 8, fig.height = 4------------------------------------ # SpatExtent to crop ndvi layer e <- ext(-121.807, -121.725, 38.004, 38.072) # crop landsat by the extent ndvi <- crop(ndvi, e) ndvi # convert the raster to a data.frme nr <- as.data.frame(ndvi, cell=TRUE) str(nr) ## ----kmeansobject------------------------------------------------------------- # It is important to set the seed generator because `kmeans` initiates the centers in random locations set.seed(99) # Create 10 clusters, allow 500 iterations, start with 5 random sets using "Lloyd" method. # Do not use the first column (cell number). kmncluster <- kmeans(nr[,-1], centers=10, iter.max = 500, nstart = 5, algorithm="Lloyd") # kmeans returns an object of class "kmeans" str(kmncluster) ## ----kmeansraster------------------------------------------------------------- # Use the ndvi object to set the cluster values to a new raster knr <- rast(ndvi, nlyr=1) knr[nr$cell] <- kmncluster$cluster knr ## ----kmeansplot, fig.height=4, fig.width=9------------------------------------ # Define a color vector for 10 clusters (learn more about setting the color later) mycolor <- c("#fef65b","#ff0000", "#daa520","#0000ff","#0000ff","#00ff00","#cbbeb5", "#c3ff5b", "#ff7373", "#00ff00", "#808080") par(mfrow = c(1,2)) plot(ndvi, col = rev(terrain.colors(10)), main = "Landsat-NDVI") plot(knr, main = 'Unsupervised classification', col = mycolor, type="classes")