rdataframecimg

How To Convert an XY-RGB dataframe into a Image [cimg type]


Using imager library, I have a dataframe that has the following information about the image in the columns:

I'm trying to convert this dataframe into a cimg to store it on disk as image -after I finished my processing on the dataframe-.

I tried using as.cimg to do the conversion as instructed in the docs https://rdrr.io/cran/imager/man/as.cimg.data.frame.html

But It does not support RGB argument and takes instead a value argument representing all colors, how can I convert RGB into value or how is this value calculated so I could rebuild it with my code from RGB components?

Here is an example to try with

install.packages('imager')
library(imager)
im <- load.image("~/any_image.png")
df_image <- as.data.frame(im, wide="c") # that's the same structure as my dataframe
# need to convert that back to an image

here is a head sample of my df

  x y       c.1       c.2       c.3
1 1 1 0.8588235 0.7058824 0.4039216
2 2 1 0.9019608 0.7254902 0.4549020
3 3 1 0.8862745 0.7294118 0.4313725
4 4 1 0.8745098 0.7254902 0.4117647
5 5 1 0.8823529 0.7019608 0.4039216
6 6 1 0.8941176 0.7333333 0.4509804

Solution

  • If I'm reading the ?cimg help page corrrectly, you would need a time variable for video, and then can stack the rgb data in a single value column. Then reading the ?as.cimg page, it appears you would also need to specify the number of color dimensions with c=3. I do have a png plot from a previous SO answer in my working directory, so I unlisted the three rgb columns as a single vector and called as.cimg with appropriate parameters for the structure:

    im <- load.image( file.choose())
    df_image <- as.data.frame(im, wide="c")
    head(df_image)
      x y c.1 c.2 c.3
    1 1 1   1   1   1
    2 2 1   1   1   1
    3 3 1   1   1   1
    4 4 1   1   1   1
    5 5 1   1   1   1
    6 6 1   1   1   1
    ?as.cimg
    str(df_image)
    #-----------------------
    'data.frame':   230400 obs. of  5 variables:
     $ x  : int  1 2 3 4 5 6 7 8 9 10 ...
     $ y  : int  1 1 1 1 1 1 1 1 1 1 ...
     $ c.1: num  1 1 1 1 1 1 1 1 1 1 ...
     $ c.2: num  1 1 1 1 1 1 1 1 1 1 ...
     $ c.3: num  1 1 1 1 1 1 1 1 1 1 ...
    #--------------
    length(unique(df_image$x))
    #[1] 480
    length(unique(df_image$y))
    #[1] 480
    my_cimg <- as.cimg(unlist(df_image[3:5]),x=480,y=480,cc=3) #480x480 RGB
    plot(my_cimg)
    

    enter image description here

    str(my_cimg)
    # 'cimg' num [1:480, 1:480, 1, 1:3] 1 1 1 1 1 1 1 1 1 1 ...