我正在使用magick软件包对R keras进行图像分类。当我开始训练图像时,它以100%的错误结束:
Error in names(feature_matrix) <- paste0("pixel", c(1:img_size)):'names' attribute[2500] must be the same length as vector [0]
我阅读了magick软件包,似乎将图像转换为矩阵是img_matrix <- graying[0]
我不明白我在编码中做错了什么。如果有人可以帮助我。
谢谢。
library(keras)
library(magick)
library(stringr)
library(pbapply)
# Set image size
width <- 50
height <- 50
extract_feature <- function(dir_path, width, height, labelsExist = T) {
img_size <- width * height
## List images in path
images_names <- list.files(dir_path)
if(labelsExist){
## Select only cats or dogs images
catdog <- str_extract(images_names, "^(cat|dog)")
# Set cat == 0 and dog == 1
key <- c("cat" = 0, "dog" = 1)
y <- key[catdog]
}
print(paste("Start processing", length(images_names), "images"))
## This function will resize an image, turn it into greyscale
feature_list <- pblapply(images_names, function(imgname) {
## Read image
img <- image_read(file.path(dir_path, imgname))
## Resize image
img_resized <- _image_resize(img, "50x50")
## Set to grayscale (normalized to max)
grayimg <- image_data(img_resized, channel="gray",frame=1)
## Get the image as a matrix
img_matrix <- grayimg[0]
## Coerce to a vector (row-wise)
img_vector <- as.vector(t(img_matrix))
return(img_vector)
})
## bind the list of vector into matrix
feature_matrix <- do.call(rbind, feature_list)
feature_matrix <- as.data.frame(feature_matrix)
## Set names
names(feature_matrix) <- paste0("pixel", c(1:img_size))
if(labelsExist){
return(list(X = feature_matrix, y = y))
}else{
return(feature_matrix)
}
}
# Takes approx. 15min
trainData <- extract_feature("train/", width, height)