條件我想加速這個代碼在R.加快循環和其中R
的輸入是一個數組3x3x3的含有整數和基於該鄰居,如果它們都爲零,替換它們用於各個數。
輸出是帶有新值的數組「mask_roi」。
###### Start here
list_neig = array(0, dim = c(3,3,3))
mask_roi = array(sample(c(0,1,2),27,replace=T), dim = c(3,3,3))
values_mask = array(1:27, dim = c(3,3,3))
values_mask_melted = melt(values_mask, varnames=c("x","y","z"))
### Tranform the 3D Matrix in a data.table wit 4 columns position and value
image_melted <- melt(mask_roi, varnames=c("x","y","z")) # 4 columns: x, y, z, value
image_melted$box = rownames(image_melted)
image_melted_non_zeros<-image_melted[!(image_melted$value==0),]
box_neigbors = vector("list", nrow(image_melted))
for (i in 1:(nrow(image_melted_non_zeros))){
cat(i,"\n")
x = image_melted_non_zeros[i,1]
y = image_melted_non_zeros[i,2]
z = image_melted_non_zeros[i,3]
box_neigbors[[image_melted_non_zeros[i,5]]] <- list(nearestNeighbors(values_mask, elem = c(x,y,z), dist = 1,dim = c(3,3,3)))
}
我也做了「box_neighbors」向量,就包括在這裏展示如何得到它,我們需要從這裏到最後快。這個想法是,檢查所有不同的體素,並檢查他所有的鄰居。如果他的鄰居是零,他會有相同的價值,如果不是零,保持原來的。
for (i in 1:(nrow(image_melted_non_zeros))){
cat(i,"\n")
x = image_melted_non_zeros[i,1]
y = image_melted_non_zeros[i,2]
z = image_melted_non_zeros[i,3]
number_of_nei = length(box_neigbors[[image_melted_non_zeros[i,5]]][[1]])
value_vozel = mask_roi[x,y,z] # it will give this new value
for (j in 1:number_of_nei){
nei_number = box_neigbors[[image_melted_non_zeros[i,5]]][[1]][j]
xx = image_melted[nei_number,1]
yy = image_melted[nei_number,2]
zz = image_melted[nei_number,3]
value_nei = mask_roi[xx,yy,zz]
if(value_nei == 0){
mask_roi[xx,yy,zz] = value_vozel
}
}
}
我需要爲256x256x256陣列而不是3x3x3做這個。
非常感謝!
nearestNeighbors <- function(ary, elem, dist, dims){
usedims <- mapply(function(el, d) {
seq(max(1, el - dist), min(d, el + dist))
}, elem, dims, SIMPLIFY=FALSE)
df <- as.matrix(do.call('expand.grid', usedims))
ndist <- sqrt(apply(df, 1, function(x) sum((x - elem)^2)))
ret <- df[which(ndist > 0 & ndist <= dist),,drop = FALSE]
return(ary[ret])
}
你從哪個包裏獲得'melt'? –
@BryanGoggin,'melt'來自'reshape'。 – Qaswed
你能幫我解決這個@ r2evans嗎?你是那個人! – DemetriusRPaula