I am trying to convert a feature collection to a binary image as described in Creating binary image from FeatureCollection in Google Earth Engine.

However, the result is an image with only one value and not a binary image as expected.

Here is my code

//Load PAs Feature Collection filtered to Country
var PAs=ee.FeatureCollection("WCMC/WDPA/current/polygons").filter(ee.Filter.eq('ISO3', 'HND'));

// define ROI
var limites =ee.FeatureCollection("FAO/GAUL/2015/level0");
var roi= limites.filter(ee.Filter.eq('ADM0_NAME', 'Honduras'));

// background image
var HND0 = ee.Image.constant(1).clip(roi)
// replacement values
var PAs1 = ee.Image.constant(0).clip(PAs).clip(roi)
// foreground
var PAs_bin= HND0.where({test:PAs1, value:PAs1});

var distPAsVisPar = {min:0,

Map.addLayer(HND0, {palette:['black']}, 'Background');
Map.addLayer(PAs1, {palette:['green']}, 'Foreground');
Map.addLayer(PAs_bin.clip(roi), distPAsVisPar, 'distance PAs fixed');


Any suggestions to fix this?


You wrote HND0.where({test:PAs1, value:PAs1}).

where replaces pixels in an image wherever the test image's value is nonzero. But PAs1 is always zero (or masked). To get a useful result, you can use the mask of PAs1 instead:

var PAs_bin = HND0.where({test: PAs1.mask(), value: PAs1});

However, a better way to do this might be to mosaic the images. The mosaic operator takes the last unmasked pixel across a collection, so you can use it to overlay images:

var PAs_bin = ee.ImageCollection([

Note that I had to add .int() to convert the constant images to all have the same band type. Also, it's more efficient to use .clipToCollection() whenever the shape you're clipping to is a FeatureCollection.

A further refinement would be to avoid running clipToCollection(roi) twice:

var PAs_bin = ee.ImageCollection([

There is no need in Earth Engine to clip all of the input images to an operation. It doesn't save processing time; in fact, it would usually be slower than clipping the output, because pixel processing always starts with the requested output pixels and works backwards to find the needed inputs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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