简体   繁体   中英

Convert image to CSV with 8*8 pixel using R programmimg

library("EBImage")
img <- readImage("sample.jpg")    
img <- channel(img, "grey")
write.csv(t(img), "sample.csv", row.names = FALSE)

I'm using the above code to convert my image to csv.My image size is 32*32 and i got 1024 features(columns) in csv with 1 observation. But I want to take an 8*8 block from the whole image and write each 8*8 block as an observation. so finally i should have 64 features and 16 observations.

  # Main loop. Loop over each image
  for(i in 1:length(images))
  {
    # Read image
    img <- readImage(images[i])
    # Get the image as a matrix
    img_matrix <- img@.Data
    # Coerce to a vector
    img_vector <- as.vector(t(img_matrix))


  }


  # Write out dataset
  write.csv(img_vector, out_file, row.names = FALSE)

Sure there is a more effectively way to do this but you could do it linearly (perhaps not the way that you need it) with a triple for cycle:

#Instalation of this package is a little special
source("https://bioconductor.org/biocLite.R")
biocLite("EBImage")
library("EBImage")
img <- readImage("sample.jpg")    
img <- channel(img, "grey")

img0 <- as.vector(img)

new_img<-matrix(ncol=64,nrow=16)

for(i in 1:16){
  for(j in 1:8){
    for(k in 1:8){
      new_img[i,8*(j-1)+k]<-img0[[64*(i-1)+8*(j-1)+k]]
    }
  }
}

write.csv(new_img, "sample.csv", row.names = FALSE)

But if you 8*8 blocks are like the squares of a cuadricule the for cycles should go as:

img0 <- as.vector(img)

new_img<-matrix(ncol=64)
for(i in 1:4){
  for(j in 1:4){
    vec=vector()
      for(k in 1:8){
        for(l in 1:8){
          vec=c(vec,img0[[256*(i-1)+8*(j-1)+32*(k-1)+l]])
      }
    }
    new_img=rbind(new_img,vec)

  }
}
new_img=new_img[-1,]

32x32示例图片

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM