0

I'm getting the error 'subtract is not a function', when I try to substract two images from each other, and eventually get the difference in the NDVI. Both images have an NDVI band with an NDVI value. My input are images, not image collections (which would trigger this error). My code looks like this:

// Mosaic the Imagecollection and clip it to the AOI
var S2_pre_mosaic = S2_pre.mosaic().clip(geometry).copyProperties(S2_pre);
print(S2_pre_mosaic, 'S2_pre_mosaic')

var S2_post_mosaic = S2_post.mosaic().clip(geometry).copyProperties(S2_post);
print(S2_post_mosaic, 'S2_post_mosaic');

// Create a Difference Image from both Images 
var diff_img = S2_pre_mosaic.subtract(S2_post_mosaic);
print(diff_img, 'diff_img');

I've noticed that if I exclude the 'copyProperties' argument earlier in the code, then the subtract function works - I honestly don't understand why though.

The problem is that later, I want to plot the results using diff_img as the imageCollection, and if ImageProperties are missing, then I get this error:

var dndvi = ui.Chart.image.series(
  diff_img.select('nd'), 
  geometry, 
  ee.Reducer.mean(),
  20)   
  .setOptions({
          title: 'dNDVI',
          hAxis: {title: 'Date', titleTextStyle: {italic: false, bold: true}},
          vAxis: {title: 'NDVI',titleTextStyle: {italic: false, bold: true}},
  });
print(dndvi)

Error: "system:time_start"

Any ideas how to solve the above?

1 Answer 1

1

I've noticed that if I exclude the 'copyProperties' argument earlier in the code, then the subtract function works - I honestly don't understand why though.

In the docs you'll see that ee.Image.copyProperties returns an Element rather than an Image. Earth Engine throws an error because Element.subtract is not a function.

Any ideas how to solve the above?

Earth Engine "forgets" that your mosaics are images when you use copyProperties, so you need to "remind" it by explicitly casting them back to images:

var S2_pre_mosaic = ee.Image(S2_pre.mosaic().clip(geometry).copyProperties(S2_pre));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.