This document visualizes K-means clustering on the colors of a particular image design to determine the most important colors needed.
get_plots <- function(img_path, kk) {
mural <- readJPEG(img_path)
# reshape image into a data frame
df = data.frame(
red = matrix(mural[,,1], ncol=1),
green = matrix(mural[,,2], ncol=1),
blue = matrix(mural[,,3], ncol=1)
)
### compute the k-means clustering
K = kmeans(df,kk)
df$label = K$cluster
### Replace the color of each pixel in the image with the mean
### R,G, and B values of the cluster in which the pixel resides:
# get the coloring
colors = data.frame(
label = 1:nrow(K$centers),
R = K$centers[,"red"],
G = K$centers[,"green"],
B = K$centers[,"blue"]
)
# merge color codes on to df
# IMPORTANT: we must maintain the original order of the df after the merge!
df$order = 1:nrow(df)
df = merge(df, colors)
df = df[order(df$order),]
df$order = NULL
#Get Hex Colors and Percentage of Each
kct <- df %>%
mutate(hex = rgb(R,G,B)) %>%
group_by(hex) %>%
summarise(ct = n()) %>%
mutate(pct = scales::percent(ct/sum(ct)))
# get mean color channel values for each row of the df.
R = matrix(df$R, nrow=dim(mural)[1])
G = matrix(df$G, nrow=dim(mural)[1])
B = matrix(df$B, nrow=dim(mural)[1])
# reconstitute the segmented image in the same shape as the input image
mural.segmented = array(dim=dim(mural))
mural.segmented[,,1] = R
mural.segmented[,,2] = G
mural.segmented[,,3] = B
img_S = rasterGrob(mural.segmented)
return(list(#original_plot=g1,segmented_plot = g2,
segmented_img=img_S,
Clrs = kct,
TWSS = K$tot.withinss
))
}
##Execute Run the defined Function to get tables and Images
pt <- proc.time()
w <- as.numeric()
for (i in 1:20) {
g <- get_plots("/Users/newuser/Downloads/mur2.jpeg",i)
grid.arrange(g[[1]], nrow=1)
ggsave(paste("seg_Outp_img4_k",i,".png",sep=""), g[[1]])
cat("\n")
cat("## Num Colors: ", i, "\n")
print(
tagList(
datatable(g[[2]])
)
)
cat("\n")
w[i] <- g[[3]]
}
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Warning: did not converge in 10 iterations
## Saving 7 x 5 in image
## Warning: did not converge in 10 iterations
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Warning: did not converge in 10 iterations
## Saving 7 x 5 in image
## Warning: did not converge in 10 iterations
## Saving 7 x 5 in image
## Saving 7 x 5 in image
wdf <- data.frame(k=1:10, wss = w)
gg <- ggplot(wdf, aes(x=k, y=wss)) +
geom_line() +
geom_point()
gg