【问题标题】:Create a List of Vector from a vector of indexes and a raster image从索引向量和光栅图像创建向量列表
【发布时间】:2018-05-04 00:12:24
【问题描述】:

我有两个光栅图像。一个带有值(img)和另一个分段索引(segmentation):

library(raster)

img=raster(t(matrix(c(1,3,1,2,1,11,11,10,NA,NA,2,12,13,14,2,3,1,2,2,1,2,13,NA,12,0,1,2,20,21,2,3,12,13,14,3,2,21,22,21,1,1,2,3,2,2,1,1,NA,NA,1,NA,NA,13,14,NA,NA,27,6,6,5,NA,NA,NA,12,22,28,7,8,5,6,NA,NA,23,24,22,5,NA,NA,5,8,1,2,1,1,2,5,NA,NA,NA,NA,1,2,1,2,2,7,6,5,NA,NA),10,10)))

segmentation=raster(t(matrix(c(1,1,1,1,1,4,4,4,4,4,1,7,7,7,1,5,5,5,5,5,1,7,7,7,1,5,5,6,6,5,1,7,7,7,1,5,6,6,6,5,1,1,1,1,1,5,5,5,5,5,9,9,9,8,8,3,3,3,3,3,9,9,9,8,8,3,3,3,3,3,8,8,8,8,8,3,3,3,3,3,2,2,2,2,2,3,3,3,10,10,2,2,2,2,2,3,3,3,10,10),10,10)))

我需要获取一个向量列表,其中,列表的每一行代表包含NA值的段索引,每个向量包含图像值。

我可以使用 for 循环来做到这一点。但是,当使用更大的图像时,这会使我的处理速度非常慢。有没有一种方法可以在没有 for 循环或更优化的方法的情况下执行此操作?

segNumber = length(freq(segmentation)[,1]) #obtain the number of segments

NAPixels <- which(is.na(img[])) #pixels that are NA in img

segsWithNA <- vector() #initializing

segsWithNA <- unique(segmentation[NAPixels]) #segmentation index that contains NA

listOfSegmentValues <- list() #initializing

for (i in 1:length(segsWithNA)){ #For each segment that contains NA
    listOfSegmentValues[[i]] = which(segmentation[] == segsWithNA[i])
}

【问题讨论】:

    标签: r list loops vector raster


    【解决方案1】:

    这是一种选择。一切都可以矢量化。不需要 for 循环。

    library(raster)
    
    # Get the value as a vector, test if the value is NA
    NA_value <- is.na(values(img))
    
    # Label the vector with the segment number
    names(NA_value) <- values(segmentation)
    
    # Show segment number and the indices of NA
    NA_which <- which(NA_value)
    
    NA_which
    # 4   4   7   5   5   9   9   8   3   9   9   9   8   8   3   3   3   3  10  10  10  10 
    # 9  10  23  48  49  51  52  55  56  61  62  63  71  72  77  78  87  88  89  90  99 100
    
    # Split to a list
    split(NA_which, f = names(NA_which))
    # $`10`
    # 10  10  10  10 
    # 89  90  99 100 
    # 
    # $`3`
    # 3  3  3  3  3 
    # 56 77 78 87 88 
    # 
    # $`4`
    # 4  4 
    # 9 10 
    # 
    # $`5`
    # 5  5 
    # 48 49 
    # 
    # $`7`
    # 7 
    # 23 
    # 
    # $`8`
    # 8  8  8 
    # 55 71 72 
    # 
    # $`9`
    # 9  9  9  9  9 
    # 51 52 61 62 63 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-20
      • 2014-11-13
      • 1970-01-01
      • 2016-03-23
      • 1970-01-01
      • 2017-09-09
      • 2020-10-25
      • 1970-01-01
      相关资源
      最近更新 更多