问题
I'm trying to get the number of images in an image collection in the Google Earth Engine (GEE) code editor. The image collection filteredCollection
contains all Landsat 8 images on GEE that cover Greenwich (just an example).
The number of images is printed as 113 but it doesn't appear to be of type integer and I can't coerce it to an integer either. Here's what that looks like:
var imageCollection = ee.ImageCollection("LANDSAT/LC8_SR");
var point = ee.Geometry.Point([0.0, 51.48]);
var filteredCollection = imageCollection.filterBounds(point);
var number_of_images = filteredCollection.size();
print(number_of_images); // prints 113
print(number_of_images > 1); // prints false
print(+number_of_images); // prints NaN
print(parseInt(number_of_images, 10)); // prints NaN
print(Number(number_of_images)); // prints NaN
print(typeof number_of_images); // prints object
print(number_of_images.constructor); // prints <Function>
print(number_of_images.constructor.name); // prints Ik
var number_of_images_2 = filteredCollection.length;
print(number_of_images_2); // prints undefined
Any idea what's happening here and how I can get the number of images in the collection as an integer?
P.S.: Collection.size() is the recommended function for getting the number of images in the GEE docs.
回答1:
This is due to the GEE architecture, the way the GEE client and server side interact with each other. You can read about it in the docs.
But in short:
If you're writing Collection.size()
, you're basically building a JSON
object on your side (client) which doesn't contain any info per-se. Once you're invoking the print
function, you're sending the JSON
object to the server side where it gets evaluated and returns the output. This also applies to any other function where you include your variable number_of_images
. If the function is evaluated on the server side it will work (because it will be evaluated there), if the function is only executed locally (as number_of_images > 1
), it will fail.
This has also a "big" implication on how to use loops in GEE, which is better described in the docs (link above).
So as for a solution:
You can use the function .getInfo()
which basically retrieves the result from the Server an lets you assign it to a variable.
So
var number_of_images = filteredCollection.size().getInfo();
will get you where you want. This method is to be used with caution, as stated in the docs:
You shouldn't use
getInfo()
unless you absolutely need to. If you call getInfo() in your code, Earth Engine will open the container and tell you what's inside, but it will block the rest of your code until that's done
HTH
来源:https://stackoverflow.com/questions/43948008/convert-what-looks-like-a-number-but-isnt-to-an-integer-google-earth-engine