Reputation: 51
I have segmented an RGB image into 3 clusters. I want to recreate images containing indices from each cluster separately- using R. How can I do this?
Upvotes: 0
Views: 344
Reputation: 486
You are not including a minimal reproducible example or a sample dataset, so I will assume that you have done something along the lines of the article: https://alstatr.blogspot.com/2014/09/r-k-means-clustering-on-image.html
One change to the code, in the aforementioned article, that might help you with associating the cluster number to the each pixel, will be the following:
library(dplyr)
kClusters <- 3
# pick all distinct colors we will be using for clustering
unique_colors <- imgRGB %>% select(R, G, B) %>% distinct()
kMeans <- kmeans(unique_colors, centers = kClusters)
df <- imgRGB %>%
left_join(
# make the data frame to join with the original
bind_cols(unique_colors,
data.frame(
cluster = kMeans$cluster
)),
by = c("R", "G", "B")
)
str(df)
# 'data.frame': 420800 obs. of 6 variables:
# $ x : int 1 1 1 1 1 1 1 1 1 1 ...
# $ y : int 526 525 524 523 522 521 520 519 518 517 ...
# $ R : num 0.00392 0.00392 0.00392 0.00392 0.00392 ...
# $ G : num 0.00392 0.00392 0.00392 0.00392 0.00392 ...
# $ B : num 0.00392 0.00392 0.00392 0.00392 0.00392 ...
# $ cluster: int 2 2 2 2 2 2 2 2 2 2 ...
Then you could use the cluster values to facet a ggplot:
ggplot(data = df, aes(x = x, y = y)) +
geom_point(colour = rgb(df[c("R", "G", "B")])) +
labs(title = "Separated clusters") +
xlab("x") +
ylab("y") +
coord_fixed() +
facet_wrap(~cluster, nrow = 2)
which produces something like:
Hope this gives you a lead on how to solve your problem.
Upvotes: 3