Search code examples
rcolorspixelraster

R - extract georeferenced raster pixel color


I would like to extract the color values for each pixel of a georeferenced raster image using R. I need those pixel colors later to plot a tif (or geotif) as mentioned in a previous question (see R - original colours of georeferenced raster image using ggplot2- and raster-packages). Due to the fact that raster images with data-band cannot implicitly use the band-values to assign colors to them (not able to represent pattern fills), I defenitely need those pixel colors. I already know how to access the colortable where all possible 256 colors are listed in a vector. However, they are not mapped in this form. Here is the code which I use to load the raster image and extract the unmapped colortable:

raster1 <- raster(paste(
       workingDir, "/HUEK200_Durchlaessigkeit001_proj001.tif",
       sep="", collapse=""))
raster1.pts <- rasterToPoints(raster1)
raster1.df <- data.frame(raster1.pts)
colTab <- attr(raster1, "legend")@colortable

Thank you for your help!


Solution

  • I have posted an answer under the question which I have cited in my question here. The solution applies to both question-threads, so I don't repeat it here completely:

    R - original colours of georeferenced raster image using ggplot2- and raster-packages

    It turned out, that the first data-band of my spatial raster image object exactly reflected the colors. I used a vector of with all unique possible values in the raster to reference to the respective colors in colTab. This is not directly possible because values starting from 0 which is not a valid index in R. I simply introduced named indices to cope with it. Now, only colors with indices listed in valTab will be passed as colours-parameter for the scaled fill and the plotted result is the georeferenced raster image with its original colors.