将多个图像(3D阵列)存储到4D阵列中,以R表示,用于循环



我试图平均获得3张图片。我制作了一个函数来实现这一点,但在进行一些图像操作后,我在存储每个图像时都遇到了问题。我得到一个错误:

Warning messages:
1: In b$b_arr[i] <- m :  number of items to replace is not a multiple of replacement length
2: In b$b_arr[i] <- m :  number of items to replace is not a multiple of replacement length
3: In b$b_arr[i] <- m :  number of items to replace is not a multiple of replacement length

这是我以前做的代码。我知道我可以手动做这件事,但我想做一个函数(并了解这个for循环的问题(。

library(OpenImageR)

imgs <- c("img1.png", "img2.png", "img3.png")
b <- data.frame(conc = imgs,
b_arr = array(dim = c(length(imgs),831, 651, 3)))
base_fun <- functienter code hereon(imgs) {
for (i in 1:length(imgs)) {
m <- readImage(imgs[i])
m[ , , 2] = 0
m[ , , 3] = 0
m <- cropImage(m, new_width = 250:1080, 
new_height = 650:1300, 
type = 'user_defined')
b$b_arr[i] <<- m
}
avg_b <<- (b$b_arr[1,,,] +  b$b_arr[2,,,] +  b$b_arr[3,,,])/3
}

base_fun(img)

在代码中,问题是b是维度为3乘2的data.frame。这意味着b_arr列实际上是三个4维数组。

我没有任何图像,但下面的代码应该可以工作。

library(OpenImageR)
imgs <- c("img1.png", "img2.png", "img3.png")
b <- lapply(imgs, function(x){
img <- readImage(x)
cropImage(img, new_width = 250:1080, new_height = 650:1300, type = 'user_defined')
})
# Convert list to array
b_arr <- array(dim = c( length(imgs), 831, 651, 3))
for(i in seq(length(imgs))
b_arr[,, i] <- b[[i]]
# calculate the mean across the first dimension (why?)
apply(b_arr, 1, mean)

Oliver的答案很有效(只做了一些小的修改(,但我发现了如何在函数中做到这一点(有助于提高可扩展性和可读性(。

b <- function(imgs) {
b <<- array(dim = c(length(imgs), w_to-w_from+1, h_to-h_from+1, 3))
for (i in seq(length(imgs))) {
m <- readImage(imgs[i])
m[ , , 2] = 0
m[ , , 3] = 0
m <- cropImage(m, new_width = w_from:w_to, 
new_height = h_from:h_to, type = 'user_defined')
b[i,,,] <<- m
}
m_avg <<- (b[1,,,] +  b[2,,,] +  b[3,,,])/3
}

最新更新