Search code examples
rfunctionraster

How to write a function that opens a raster whose filename matches with cell value in a dataframe?


Using R, I aim to write a piece of code that would look into dataframe named df, check cell value in column IMG, and open a .jpg raster from another folder whose name would match IMG (plus the jpg extension).

Ultimately I would want the function also to calculate the number of black pixels in that image and save the result in either a new dataframe (with the IMG/filename included in one column, and number of black pixels in another), or to the old dataframe df in a new column and in corresponding row.

I can't figure out how to even start, and thus I have no even remotely functioning code yet. I know how to write very basic loop functions, and I believe I will be able to get the code finished if someone would direct me to the right direction...

Here is the dataframe from which I would like to check the file names. There is altogether 300 rows and thus 300 images, so while it would be doable manually too, it would take a lot of time and I am rather intrigued how this would be done by code.

> head(df)
        plot  IMG
1   Kure-0-3 2927
51  Kure-1-3 2924
149 Hope-0-1 2757
170 Hope-1-2 2758
217 Hope-1-1 2756
290 Kure-1-1 2747

// Edit for clarification: I want the function to check cell value in column IMG, for example 2927, and open a raster (from another folder) that has the same filename, in this case 2927.jpg. After calculating how many black pixels it has and saving the result in the same or another dataframe, I want to go for the next row, see that the cell value is 2924, open raster 2924.jpg, do the same calculation, and so on. For now it is, however, enough if someone could help me how to do that first part :)

Thank you for your help in advance. Any help, even "check this question here" or "this page describes some stuff that might be useful to you", is highly appreciated.

// Here is one example picture


Solution

  • Assuming that by 'black pixels' you mean missing values, this code below will do what you need.

    library(raster)
    
    data_key          <- data.frame(IMG = 2900:3000)
    data_key$filepath <- paste0(data_key$IMG, '.jpg')
    
    setwd('directory with the rasters in it')
    
    my_rasters            <- lapply(data_key$filepath, raster)
    
    Black_pixels          <- lapply(my_rasters, function(x){length(which(is.na(x[,])))})
    
    data_key$black_pixels <- Black_pixels