如何在R中使用丛集功能移除像素丛集

如何在R中使用丛集功能移除像素丛集

本文介绍了如何在R中使用丛集功能移除像素丛集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想删除形成大簇的像素,只保留小簇进行分析(即获取像素数和位置).首先,我应用一个滤镜将所有像素值都降低到0.66以下的像素都涂成白色.然后,我在R中使用了函数clump().该模型可以工作,但我不能仅删除大型群集.我不明白丛集函数的工作原理.

I would like to remove the pixels that form a large cluster and keep only the small cluster to analyse (means get pixels number and locations). First I apply a filter to color in white all pixels that has a value lower to 0.66. Then I use the function clump() in R. The model works but I cannot remove only the large cluster. I do not understand how clump function works.

初始图片:

结果图像:plot_r是像素值<将0.66更改为0.plot_rc是clump()函数之后的结果.正如观察到的那样,我不能仅删除较大的像素簇(在图像plot_r的顶部).我更改了值(代码中为700),但没有更好的方法,怎么办?

Results image: plot_r is the image where the pixels with value < 0.66 are changed to 0. plot_rc is the results after clump() function. As observed I cannot remove only the large cluster of pixels (on top of the image plot_r). I changed the value (700 in the code) but not better, how to do?

代码在这里:

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,然后使用结果掩盖原始栅格

Replace the clumps with the number of cells they consist of and then set the larger one (here more than 100 cells) to NA, and use the result to mask the original raster

rs <- subs(rc, data.frame(f))
rsc <- reclassify(rs, cbind(100,Inf,NA))
m <- mask(b, rsc)
plotRGB(m)

这篇关于如何在R中使用丛集功能移除像素丛集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 07:03