【发布时间】:2020-02-11 01:59:03
【问题描述】:
我已将 RGB 图像分割成 3 个簇。我想使用 R 分别重新创建包含来自每个集群的索引的图像。我该怎么做?
【问题讨论】:
标签: r k-means image-segmentation indices
我已将 RGB 图像分割成 3 个簇。我想使用 R 分别重新创建包含来自每个集群的索引的图像。我该怎么做?
【问题讨论】:
标签: r k-means image-segmentation indices
您没有包含minimal reproducible example 或示例数据集,因此我假设您已经按照文章的内容做了一些事情:https://alstatr.blogspot.com/2014/09/r-k-means-clustering-on-image.html
对上述文章中的代码的一个更改可能有助于您将簇编号与每个像素相关联,如下所示:
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 ...
然后您可以使用集群值来刻面 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)
产生类似的东西:
希望这可以引导您解决问题。
【讨论】: