I have a time series of satellite images (5 bands) and want to classify them by kmeans in R. My script is working fine (loop through my images, convert the images to data.frame, cluster them, and convert it back to a raster):
for (n in files) {
image <- stack(n)
image <- clip(image,subset)
###classify raster
image.df <- as.data.frame(image)
cluster.image <- kmeans(na.omit(image.df), 10, iter.max = 10, nstart = 25) ### kmeans, with 10 clusters
#add back NAs using the NAs in band 1 (identic NA positions in all bands), see http://stackoverflow.com/questions/12006366/add-back-nas-after-removing-them/12006502#12006502
image.df.factor <- rep(NA, length(image.df[,1]))
image.df.factor[!is.na(image.df[,1])] <- cluster.image$cluster
#create raster output
clusters <- raster(image) ## create an empty raster with same extent than "image"
clusters <- setValues(clusters, image.df.factor) ## fill the empty raster with the class results
plot(clusters)
}
My problem is: I can't compare the classification results to each other because the cluster assignents differ from image to image. For example, "water" is in the first image cluster number 1, in the next 2 and in the third 10, making it impossible to compare the water results between the dates.
How can I fix the cluster assignment?
Can I specify a fixed starting point for all image (hoping that water is always detected first and thus classified as 1)?
And if yes, how?