Google Earth Engine – Calculate Distance to Target Pixels in Google Earth Engine

distancegoogle-earth-engineimageinverse-distance-weightedraster

I am having a water body raster in the form "0" as water pixels values and rest of the area is "masked". I want to have my output in the form of an image such that each point in the image will represent distance from its nearest waterbody pixels.

I tried calculating eucledian distance from the water body pixels having the band name as "waterClass". No error came also the output came as masked.

Not sure what is the correct approach? The dataset used is – JRC/GSW1_3/YearlyHistory

var water = ee.Image(Water_bodies.filterBounds(goalpara).sort("CLOUD_COVERAGE_ASSESMENT").first().clip(goalpara));
Map.addLayer(water,{},'water')
var dist= water.select('waterClass')
  .distance({kernel:ee.Kernel.euclidean(100), skipMasked:true})
print('dist', dist);
Map.addLayer(dist, {}, 'distance');
var imageVisParam = {"opacity":1,
                    "bands":["distance"],
                    "max":11.180339887498949,
                    "palette":["22ff20","1a35ff","ffa925","ff0a36","2fe1ff","fd4bff"]};
Map.addLayer(dist, imageVisParam, 'distance1');

Here is my input-

enter image description here

And how I want my Output-

enter image description here

Best Answer

The ee.Image.distance method assumes that your target pixels have a non-zero value. You have stated that your target pixel value is currently zero, so you'll need to make it non-zero. Additionally, you are setting the skipMasked parameter to true, which will not provide distance-to-target calculations for masked pixels; all of your non-target pixels are masked, you need to .unmask(0) them or set skipMasked to false. Your code might look something like this (untested).

var water = Water_bodies.filterBounds(goalpara)
  .sort("CLOUD_COVERAGE_ASSESMENT")
  .first()
  .clip(goalpara);
Map.addLayer(water, null, 'water')

var dist = water.select('waterClass').eq(0)
  .distance({kernel: ee.Kernel.euclidean(100), skipMasked: false})
print('dist', dist);

Map.addLayer(dist, null, 'distance');
var imageVisParam = {"opacity": 1,
                     "bands": ["distance"],
                     "max": 11.180339887498949,
                     "palette": ["22ff20","1a35ff","ffa925",
                                 "ff0a36","2fe1ff","fd4bff"]};
Map.addLayer(dist, imageVisParam, 'distance1');