r - 如何使用R中的clump函数删除像素簇
问题描述
我想删除形成大簇的像素,只保留小簇进行分析(意味着获取像素数和位置)。首先,我对所有值低于 0.66 的像素应用过滤器以将其着色为白色。然后我在 R 中使用函数 clump()。模型有效,但我不能只删除大集群。我不明白丛函数是如何工作的。
初始图像:
结果图像:plot_r 是值 < 0.66 的像素变为 0 的图像。 plot_rc 是 clump() 函数后的结果。正如所观察到的,我不能只删除大的像素簇(在图像 plot_r 的顶部)。我更改了值(代码中的 700)但没有更好,怎么办?
这里的代码:
library(magick)
library(pixmap)
library(raster)
library(igraph)
f <- "https://i.stack.imgur.com/2CjCh.jpg"
x <- image_read(f)
x <- image_convert(x, format = "pgm", depth = 8)
# Save the PGM file
f <- tempfile(fileext = ".pgm")
image_write(x, path = f, format = "pgm")
# Read in the PGM file
picture <- read.pnm(file = f, cellres = 1)
str(picture)
picture@size
mat <- picture@grey
mat[mat<0.66] <- 0; x
##############################################################
##Remove clumps of pixels in R using package Raster and igraph
#Detect clumps (patches) of connected cells
r <-raster(mat)
rc <- clump(r)
#extract IDs of clumps according to some criteria
clump9 = data.frame(freq(rc))
#remove clump observations with frequency smaller/larger than N
clump9 = clump9[ ! clump9$count > 700, ]
# record IDs from clumps which met the criteria in previous step
clump9 = as.vector(clump9$value)
#replace cells with IDs which do not belong to the group of interest
rc[rc != clump9[1] & rc != clump9[2]] = NA
# converting rasterlayer to matrix
n <- as.matrix(r)
m <- as.matrix(rc)
解决方案
也许像这样
library(raster)
library(igraph)
稍微缩短你的方法
f <- "https://i.stack.imgur.com/2CjCh.jpg"
b <- brick(f)
x <- sum(b)
r <- x > 450
rc <- clump(r)
f <- freq(rc, useNA="no")
用它们组成的像元数替换团块,然后将较大的一个(这里超过 100 个像元)设置为 NA,并使用结果来掩盖原始栅格
rs <- subs(rc, data.frame(f))
rsc <- reclassify(rs, cbind(100,Inf,NA))
m <- mask(b, rsc)
plotRGB(m)
推荐阅读
- cron - 如何使用带有 cloudwatch 事件的 aws lamba 运行长时间运行的任务
- php - 为什么用bind_result重写代码后php api返回null?
- jquery - 更改图像 alt 标签实际上并没有反映在浏览器中
- javascript - 如何导入只有 JSDoc 注释的 JavaScript 模块
- javascript - Ember 应用程序中的 NodeJS 和客户端 Javascript
- python - Python - Pronote
- scala - SBT、Scala、Spark、IntelliJ
- r - 如何识别数据集中的重复子序列
- javascript - jit 编译器在 JAVASCRIPT 中是如何工作的
- android - 设备充电时 CPU 是否保持唤醒状态?