############################################################### # Clear Memory rm(list=ls()) # WARNING: This deletes everything!!!!! ############################################### ########## K-means Image Clustering ########## ############################################### # Download image from the web myurl <- "https://upload.wikimedia.org/wikipedia/commons/thumb/7/7b/Earth_Western_Hemisphere.jpg/145px-Earth_Western_Hemisphere.jpg" z <- tempfile() download.file(myurl,z,mode="wb") # Load package for reading jpeg image library("jpeg") image <- readJPEG(z) # Read the image file.remove(z) # cleanup # OR download image and load # image <- readJPEG("image.jpg") # Obtain the dimension image_Dim <- dim(image) image_Dim ############## Data Formatting ################ # Create data frames and assign RGB vectors RGB <- data.frame( x = rep(1:image_Dim[2], each = image_Dim[1]), y = rep(image_Dim[1]:1, image_Dim[2]), R = as.vector(image[,,1]), G = as.vector(image[,,2]), B = as.vector(image[,,3])) ############# Image Plotting Frame ################# # ggplot theme to be used plotTheme <- function() { theme( panel.background = element_rect(size = 3, colour = "black",fill = "white"), axis.ticks = element_line(size = 3), panel.grid.major = element_line(colour = "gray90", linetype = "dashed"), panel.grid.minor = element_line(colour = "gray90", linetype = "dashed"), axis.title.x = element_text(size = rel(1.0), face = "bold"), axis.title.y = element_text(size = rel(1.0), face = "bold"), plot.title = element_text(size = 15, face = "bold",vjust = 1.0)) } ############# Plot Original Image ################# # Load package library("ggplot2") #library("raster") ggplot (data = RGB, aes(x = x, y = y)) + geom_point(colour = rgb(RGB[c("R", "G", "B")])) + labs(title = "Original Image: Colorful Dragon") + xlab("x") + ylab("y") + plotTheme() ############# K-means Clustering ################# K_Clusters <- 4 kMeans <- kmeans(RGB[, c("R", "G", "B")], centers = K_Clusters) kColours <- rgb(kMeans$centers[kMeans$cluster,]) ############# Plot Clustered Image ################# ggplot (data = RGB, aes(x = x, y = y)) + geom_point(colour = kColours) + labs(title = paste("k-Means Clustering of", K_Clusters, "Colours")) + xlab("x") + ylab("y") + plotTheme() ############################################################### ###############################################################