将像素矩阵转换为R中的变量(数据帧)

时间:2016-06-11 19:39:42

标签: r matrix

我正在寻找一种解决方案,将图像的每个像素转换为数据帧的变量。

有大约2500个输入图像,分辨率为320x280px,并被读入带有readJPEG()的矩阵。文件名包含有关稍后应对其进行分类的变量的信息。

file_list <- list.files("D:/path/to/images", full.names=TRUE)
# Extract person number and eye position from file names
file_names <- sapply(strsplit(file_list, split = '/'), "[", 8)
person_list <- substr(file_names, 1 ,3)
person_class <- as.factor(person_list)

# Read pixel matrices from image files
pixelMatrices = lapply(X=file_list, FUN= function(x) readJPEG(file_list))
entryCount <- length(file_list)

# Setting up a proper data set 
eyes = data.frame(pos= numeric(entryCount))
eyes$person <- person_class
eyes$pixels <- pixelMatrices

这导致数据框中每个对象有2个变量(人,像素)。但我希望有一个具有320 * 280 + 1个变量的数据框。每个像素一个和因子类。

我尝试了不同的方法,例如取消列表矩阵

test <- as.data.frame(x = unlist(pixelMatrices[1]))
test <- unlist(pixelMatrices[1])
test <- as.data.frame(pixelMatrices[1])

但没有给出正确的结果。到目前为止,我唯一的(几乎)工作方法是对所有像素进行for循环,并逐行插入数据集,如下所示:

 count <- length(file_list)
imageWidth = 320;
imageHeight = 280;
variableCount = imageHeight * imageWidth + 1

images <- as.data.frame(matrix(seq(count),nrow=count,ncol=variableCount ))
images[1] <- eyes$person
for(i in 1:count) {
  img <- readJPEG(file_list[i])
  image <- c(img)
  images[i, 2:variableCount] <- image
}

但for循环非常慢。那么用~2500 obj获得结果数据帧的最佳方法是什么? 89601变量?

1 个答案:

答案 0 :(得分:1)

考虑在mapply()调用中展平矩阵,迭代地将person_class添加到pixelMatrices的每个对应转换数据帧。然后运行do.call()以将绑定行绑定到最终数据帧。 Mapply确保person_class中的每个元素都将与连接的矩阵对齐:

combinedata <- function(x,y){
                   # FLATTEN MATRIX AND TRANSPOSE ACROSS MANY COLUMNS
                   temp <- data.frame(t(as.vector(x)))
                   temp$person_class <- y
                   return(temp)
               }

# WIDE LIST
dfList <- mapply(combinedata, pixelMatrices, person_class)

# LONG LIST CONVERSION FOR DO.CALL()
dfList <- lapply(1:entryCount, function(i) data.frame(dfList[,i]))

# ROW BIND UNDERLYING DATA FRAMES
finaldf <- do.call(rbind, dfList)