我有两个光栅图像。一个具有值(img)和其他分段索引(分段):
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])
}
答案 0 :(得分:1)
这是一个选项。一切都可以矢量化。不需要for-loop。
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