2016-06-11 166 views
2

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

有~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变量的数据框。每个像素和因子类别一个。

我试着像unlisting矩阵

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

但不给予正确的结果不同的方法。唯一的(几乎)工作的方法,我至今是一个循环上的所有像素并插入逐行到数据集,看起来像这样:

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

考虑将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) 
+0

我用你的方法试过,但我RStudio给了我下面的错误计算行几分钟后'dfList < - mapply(combinedata,pixelMatrices,person_class) ':R会话中止,R遇到一个致命错误。会议被终止。 – 4ndro1d

+0

我可以问为什么你需要那么多列?为什么不将矩阵转换为dfs而不展平并对每行重复person_class? – Parfait

+0

因为我想在之后使用PCA来查找最显着的特征。不知道我如何使用多个数据框来训练我的模型。我是R的初学者,感觉非常受限制,因为没有noob友好的教程 – 4ndro1d