Raster R – How to Invert Raster Min and Max Values Using R

rrastervalues

I have a raster with pixel values, 1 to 255 (no decimals). I want to invert their values in a way that pixels with value 1 will get value of 255, pixel with value 2 will get 254, pixel with value 3 will get 253 and vice versa (255 will become 1 and so on). Is is possible to achieve that in R? Unfortunately, I couldn't find any example. My data:

dput(is)
new("RasterLayer", file = new(".RasterFile", name = "C:\\Users\\Geography\\Desktop\\step\\imper_surf.tif", 
    datanotation = "INT1U", byteorder = "little", nodatavalue = -Inf, 
    NAchanged = FALSE, nbands = 1L, bandorder = "BIL", offset = 0L, 
    toptobottom = TRUE, blockrows = 11L, blockcols = 717L, driver = "gdal", 
    open = FALSE), data = new(".SingleLayerData", values = logical(0), 
    offset = 0, gain = 1, inmemory = FALSE, fromdisk = TRUE, 
    isfactor = FALSE, attributes = list(), haveminmax = TRUE, 
    min = 0, max = 255, band = 1L, unit = "", names = "imper_surf"), 
    legend = new(".RasterLegend", type = character(0), values = logical(0), 
        color = logical(0), names = logical(0), colortable = logical(0)), 
    title = character(0), extent = new("Extent", xmin = 582758.61, 
        xmax = 604268.61, ymin = 1005774.596, ymax = 1047384.596), 
    rotated = FALSE, rotation = new(".Rotation", geotrans = numeric(0), 
        transfun = function () 
        NULL), ncols = 717L, nrows = 1387L, crs = new("CRS", 
        projargs = "+proj=lcc +lat_0=18.88015774 +lon_0=76.75 +lat_1=16.625 +lat_2=21.125 +x_0=1000000 +y_0=1000000 +datum=WGS84 +units=m +no_defs"), 
    history = list(), z = list()) 

Best Answer

You can just use a bit of algebra to compute the new pixel values in the inverted raster. Namely, you want to subtract the values from the max value (here it is 256). Try something like this:

library('raster')

r <- raster('image.jpg')

r_inverse = r

values(r_inverse) <- 256 - values(r)

plot(r)

plot(r_inverse)

enter image description here