Search code examples
javascriptgoogle-earth-engine

How to modify a rasterlayers band in Google Earth Engine?


I want to scale the bands of a satellite image with respect to the known scaling factors. In Google Earth Engine I can execute the following line:

image.select(nir).multiply(0.0000275).add(-0.2);

In the documentation of these functions it is not clear to me if multiply and add modify the original image.

However, if I try the following line, I get an rvalue error, because the property is read-only:

image.select(nir) = image.select(nir).multiply(0.0000275).add(-0.2);

Of cause I could assign the first statement to a completely new image, but then I'll miss all other bands.

So what is actually the effect of the first statement?


Solution

  • In the documentation of these functions it is not clear to me if multiply and add modify the original image.

    In Earth Engine, almost nothing you can do modifies an existing thing. The rare exceptions are functions that do things like creating or deleting assets.

    So what is actually the effect of the first statement?

    The Earth Engine client constructs an expression according to your direction, and then discards it because you didn't do anything with it.

    image.select(nir) = image.select(nir).multiply(0.0000275).add(-0.2);
    

    The way to achieve this effect is

    image = image.addBands({
      srcImg: image.select("nir").multiply(0.0000275).add(-0.2),
      overwrite: true,
    });
    

    Note that this is still not modifying an image. When Earth Engine executes this, it creates a new image that has a different band; the original image is unchanged. And in your JavaScript (client side), the effect is to replace the not-yet-executed EE expression in image with an expression that has more arithmetic in it.

    The “overwrite” doesn't mean a modification in-place either; it simply means “let the band in the output image take the name nir, even though there is already a band in the input image named nir”, whereas the default behavior would be for the new image to have both bands, with the new one named nir_1.