在 R 中计算二进制光栅图像中的对象 [英] Counting objects in binary raster image in R

查看:60
本文介绍了在 R 中计算二进制光栅图像中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个栅格:

r <- raster(ncol=10, nrow=10)
set.seed(0)
values(r) <- runif(ncell(r))

我从栅格中选择前 10% 并更改为二进制:

From the raster I select the top 10% and change to binary:

r_10<-r[[1]]>=quantile(r,.90)

从这个子集栅格 r_10 中,所有绿色像素都具有相同的值 1.我想改变这些值,方法是将像素或像素组识别为对象,并用新的标签标记每个新对象ID.新栅格应具有与此示例图像类似的值:

From this subset raster r_10 all green pixels have the same value of 1. I would like to change these values, by identifying pixels or groups of pixels as objects and labeling every new object with a new ID. The new raster should have values like this example image:

某些对象可以有多个像素,并且它们都应该具有相同的对象 ID(例如数字 8).

Some objects can have multiple pixels, and they all should have the same object ID (like number 8).

如何在 R 中编写代码?我想使用某种边缘检测或 Sobel 过滤器,但无法弄清楚.

How can I code this up in R? I thought to use some sort of edge detection, or Sobel filter, but cant figure it out.

这是一个类似的帖子,不一样,但它在python中,我需要在 R 中实现它.

Here is a similar post, not the same, but its in python, and I need to implement this in R.

欢迎任何替代解决方案.

Any alternative solutions are welcome.

推荐答案

我相信有多种方法可以回答这个问题(计算机视觉和 GIS).这是针对手头问题的 GIS 解决方案(在此处找到):

I am sure there are multiple ways to answer this questions (computer vision and GIS). Here is an GIS solution (found here) to the problem at hand:

# Create raster data
r <- raster(ncol=10, nrow=10)
set.seed(0)
values(r) <- runif(ncell(r))

# Select top 10% of highest values and convert to binary
r_10<-r[[1]]>=quantile(r,.90)
r_10[r_10==0]<-NA

# Vectorize
Vector_r_10<-rasterToPolygons(r_10)
plot(Vector_r_10)

# Add new Obj_ID class
Vector_r_10$Obj_ID<-1:nrow(Vector_r_10)

# Identify neighboring pixels
nb<-poly2nb(Vector_r_10)

# Create regions
create_regions <- function(data) {
  group <- rep(NA, length(data))
  group_val <- 0
  while(NA %in% group) {
    index <- min(which(is.na(group)))
    nb <- unlist(data[index])
    nb_value <- group[nb]
    is_na <- is.na(nb_value)
    if(sum(!is_na) != 0){
      prev_group <- nb_value[!is_na][1]
      group[index] <- prev_group
      group[nb[is_na]] <- prev_group
    } else {
      group_val <- group_val + 1
      group[index] <- group_val
      group[nb] <- group_val
    }
  }
  group
}
region<-create_regions(nb)

# Union on new regions
pol_rgn<-spCbind(Vector_r_10,region)
New_Vector_r_10<-unionSpatialPolygons(pol_rgn,region)
New_Vector_r_10<-as(New_Vector_r_10,"SpatialPolygonsDataFrame")
plot(New_Vector_r_10)

现在这是一个 shapefile,但对我来说它很好.也可以随时将其转换回光栅.

This is a shapefile now, but for my purpose its fine. One can always convert this back to raster as well.

这篇关于在 R 中计算二进制光栅图像中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆