Anuncio: Todos los proyectos no comerciales registrados para usar Earth Engine antes del 15 de abril de 2025 deben verificar su elegibilidad no comercial para mantener el acceso a Earth Engine.
Los objetos ee.Image tienen un conjunto de métodos relacionales, condicionales y booleanos para
construir expresiones de toma de decisiones. Los resultados de estos métodos son útiles para limitar el análisis a ciertos píxeles o regiones a través del enmascaramiento, el desarrollo de mapas clasificados y la reasignación de valores.
Operadores relacionales y booleanos
Entre los métodos relacional, se incluyen los siguientes:
eq(), gt(), gte(), lt() y lte()
Entre los métodos booleanos, se incluyen los siguientes:
Para realizar comparaciones por píxeles entre imágenes, usa operadores relacionales. Para extraer áreas urbanizadas en una imagen, este ejemplo usa operadores relacionales para establecer umbrales en los índices espectrales, combinando los umbrales con el operador and:
Como se ilustra en este ejemplo, el resultado de los operadores relacionales y booleanos es verdadero (1) o falso (0). Para enmascarar los 0, puedes enmascarar la imagen binaria resultante con selfMask().
NDVI y NDWI bajos (en blanco) de Landsat 8, San Francisco, California, EE.UU.
Las imágenes binarias que muestran los operadores relacionales y booleanos se pueden usar con operadores matemáticos. En este ejemplo, se crean zonas de urbanización en una imagen de luces nocturnas con operadores relacionales y add():
Observa que, en el ejemplo de expresión anterior, se hace referencia a la banda de interés con la función b(), en lugar de un diccionario de nombres de variables. Obtén más información sobre las expresiones de imágenes en esta página. El uso de operadores matemáticos o una expresión producirá el mismo resultado.
Zonas arbitrarias de imágenes nocturnas de 2012 de París, Francia.
Otra forma de implementar operaciones condicionales en imágenes es con el operador where(). Ten en cuenta la necesidad de reemplazar los píxeles enmascarados por otros datos. En el siguiente ejemplo, los píxeles nublados se reemplazan por píxeles de una imagen sin nubes con where():
[null,null,["Última actualización: 2025-07-25 (UTC)"],[[["\u003cp\u003e\u003ccode\u003eee.Image\u003c/code\u003e objects have relational, conditional, and boolean methods for constructing decision-making expressions for image analysis.\u003c/p\u003e\n"],["\u003cp\u003eRelational operators (eq, gt, gte, lt, lte) enable per-pixel comparisons between images, useful for tasks like thresholding and masking.\u003c/p\u003e\n"],["\u003cp\u003eBoolean operators (and, or, not) combine and modify relational expressions, allowing for complex image analysis logic.\u003c/p\u003e\n"],["\u003cp\u003eConditional operators, such as \u003ccode\u003ewhere()\u003c/code\u003e, facilitate the replacement of pixel values based on specified conditions, like replacing cloudy pixels with clear ones.\u003c/p\u003e\n"],["\u003cp\u003e\u003ccode\u003eexpression()\u003c/code\u003e provides a flexible way to implement conditional operations using ternary operators, offering similar functionality to mathematical and conditional operators.\u003c/p\u003e\n"]]],[],null,["# Relational, Conditional, and Boolean Operations\n\n|---------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------|\n| [Run in Google Colab](https://colab.research.google.com/github/google/earthengine-community/blob/master/guides/linked/generated/image_relational.ipynb) | [View source on GitHub](https://github.com/google/earthengine-community/blob/master/guides/linked/generated/image_relational.ipynb) |\n\n`ee.Image` objects have a set of relational, conditional, and boolean methods for\nconstructing decision-making expressions. The results of these methods are useful for limiting\nanalysis to certain pixels or regions through masking, developing classified maps, and value\nreassignment.\n\nRelational and boolean operators\n--------------------------------\n\n**Relational** methods include:\n\n`eq()`, `gt()`, `gte()`, `lt()`, and\n`lte()`\n\n**Boolean** methods include:\n\n### Code Editor (JavaScript)\n\n`and()`,`or()`, and `not()`\n\n### Colab (Python)\n\n`And()`,`Or()`, and `Not()`\n\nTo perform per-pixel comparisons between images, use relational operators. To\nextract urbanized areas in an image, this example uses relational operators to threshold\nspectral indices, combining the thresholds with the *and* operator:\n\n### Code Editor (JavaScript)\n\n```javascript\n// Load a Landsat 8 image.\nvar image = ee.Image('LANDSAT/LC08/C02/T1_TOA/LC08_044034_20140318');\n\n// Create NDVI and NDWI spectral indices.\nvar ndvi = image.normalizedDifference(['B5', 'B4']);\nvar ndwi = image.normalizedDifference(['B3', 'B5']);\n\n// Create a binary layer using logical operations.\nvar bare = ndvi.lt(0.2).and(ndwi.lt(0));\n\n// Mask and display the binary layer.\nMap.setCenter(-122.3578, 37.7726, 12);\nMap.setOptions('satellite');\nMap.addLayer(bare.selfMask(), {}, 'bare');\n```\nPython setup\n\nSee the [Python Environment](/earth-engine/guides/python_install) page for information on the Python API and using\n`geemap` for interactive development. \n\n```python\nimport ee\nimport geemap.core as geemap\n```\n\n### Colab (Python)\n\n```python\n# Load a Landsat 8 image.\nimage = ee.Image('LANDSAT/LC08/C02/T1_TOA/LC08_044034_20140318')\n\n# Create NDVI and NDWI spectral indices.\nndvi = image.normalizedDifference(['B5', 'B4'])\nndwi = image.normalizedDifference(['B3', 'B5'])\n\n# Create a binary layer using logical operations.\nbare = ndvi.lt(0.2).And(ndwi.lt(0))\n\n# Define a map centered on San Francisco Bay.\nmap_bare = geemap.Map(center=[37.7726, -122.3578], zoom=12)\n\n# Add the masked image layer to the map and display it.\nmap_bare.add_layer(bare.selfMask(), None, 'bare')\ndisplay(map_bare)\n```\n\nAs illustrated by this example, the output of relational and boolean operators is\neither true (1) or false (0). To mask the 0's, you can mask the resultant binary image\nwith itself using `selfMask()`.\nLow NDVI and low NDWI (white) from Landsat 8, San Francisco, California, USA.\n\nThe binary images that are returned by relational and boolean operators can be used with\nmathematical operators. This example creates zones of urbanization in a nighttime lights\nimage using relational operators and `add()`:\n\n### Code Editor (JavaScript)\n\n```javascript\n// Load a 2012 nightlights image.\nvar nl2012 = ee.Image('NOAA/DMSP-OLS/NIGHTTIME_LIGHTS/F182012');\nvar lights = nl2012.select('stable_lights');\n\n// Define arbitrary thresholds on the 6-bit stable lights band.\nvar zones = lights.gt(30).add(lights.gt(55)).add(lights.gt(62));\n\n// Display the thresholded image as three distinct zones near Paris.\nvar palette = ['000000', '0000FF', '00FF00', 'FF0000'];\nMap.setCenter(2.373, 48.8683, 8);\nMap.addLayer(zones, {min: 0, max: 3, palette: palette}, 'development zones');\n```\nPython setup\n\nSee the [Python Environment](/earth-engine/guides/python_install) page for information on the Python API and using\n`geemap` for interactive development. \n\n```python\nimport ee\nimport geemap.core as geemap\n```\n\n### Colab (Python)\n\n```python\n# Load a 2012 nightlights image.\nnl_2012 = ee.Image('NOAA/DMSP-OLS/NIGHTTIME_LIGHTS/F182012')\nlights = nl_2012.select('stable_lights')\n\n# Define arbitrary thresholds on the 6-bit stable lights band.\nzones = lights.gt(30).add(lights.gt(55)).add(lights.gt(62))\n\n# Define a map centered on Paris, France.\nmap_zones = geemap.Map(center=[48.8683, 2.373], zoom=8)\n\n# Display the thresholded image as three distinct zones near Paris.\npalette = ['000000', '0000FF', '00FF00', 'FF0000']\nmap_zones.add_layer(\n zones, {'min': 0, 'max': 3, 'palette': palette}, 'development zones'\n)\ndisplay(map_zones)\n```\n\nConditional operators\n---------------------\n\nNote that the code in the previous example is equivalent to using a\n[ternary operator](http://en.wikipedia.org/wiki/%3F:) implemented by\n`expression()`:\n\n### Code Editor (JavaScript)\n\n```javascript\n// Create zones using an expression, display.\nvar zonesExp = nl2012.expression(\n \"(b('stable_lights') \u003e 62) ? 3\" +\n \": (b('stable_lights') \u003e 55) ? 2\" +\n \": (b('stable_lights') \u003e 30) ? 1\" +\n \": 0\"\n);\nMap.addLayer(zonesExp,\n {min: 0, max: 3, palette: palette},\n 'development zones (ternary)');\n```\nPython setup\n\nSee the [Python Environment](/earth-engine/guides/python_install) page for information on the Python API and using\n`geemap` for interactive development. \n\n```python\nimport ee\nimport geemap.core as geemap\n```\n\n### Colab (Python)\n\n```python\n# Create zones using an expression, display.\nzones_exp = nl_2012.expression(\n \"(b('stable_lights') \u003e 62) ? 3 \"\n \": (b('stable_lights') \u003e 55) ? 2 \"\n \": (b('stable_lights') \u003e 30) ? 1 \"\n ': 0'\n)\n\n# Define a map centered on Paris, France.\nmap_zones_exp = geemap.Map(center=[48.8683, 2.373], zoom=8)\n\n# Add the image layer to the map and display it.\nmap_zones_exp.add_layer(\n zones_exp, {'min': 0, 'max': 3, 'palette': palette}, 'zones exp'\n)\ndisplay(map_zones_exp)\n```\n\nObserve that in the previous expression example, the band of interest is referenced using\nthe `b()` function, rather than a dictionary of variable names. Learn more\nabout image expressions on\n[this page](/earth-engine/guides/image_math#expressions). Using either mathematical\noperators or an expression will produce the same result.\nArbitrary zones of 2012 nightlights imagery for Paris, France.\n\nAnother way to implement conditional operations on images is with the\n`where()` operator. Consider the need to replace masked pixels with some\nother data. In the following example, cloudy pixels are replaced by pixels from a\ncloud-free image using `where()`:\n\n### Code Editor (JavaScript)\n\n```javascript\n// Load a cloudy Sentinel-2 image.\nvar image = ee.Image(\n 'COPERNICUS/S2_SR/20210114T185729_20210114T185730_T10SEG');\nMap.addLayer(image,\n {bands: ['B4', 'B3', 'B2'], min: 0, max: 2000},\n 'original image');\n\n// Load another image to replace the cloudy pixels.\nvar replacement = ee.Image(\n 'COPERNICUS/S2_SR/20210109T185751_20210109T185931_T10SEG');\n\n// Set cloudy pixels (greater than 5% probability) to the other image.\nvar replaced = image.where(image.select('MSK_CLDPRB').gt(5), replacement);\n\n// Display the result.\nMap.setCenter(-122.3769, 37.7349, 11);\nMap.addLayer(replaced,\n {bands: ['B4', 'B3', 'B2'], min: 0, max: 2000},\n 'clouds replaced');\n```\nPython setup\n\nSee the [Python Environment](/earth-engine/guides/python_install) page for information on the Python API and using\n`geemap` for interactive development. \n\n```python\nimport ee\nimport geemap.core as geemap\n```\n\n### Colab (Python)\n\n```python\n# Load a cloudy Sentinel-2 image.\nimage = ee.Image('COPERNICUS/S2_SR/20210114T185729_20210114T185730_T10SEG')\n\n# Load another image to replace the cloudy pixels.\nreplacement = ee.Image(\n 'COPERNICUS/S2_SR/20210109T185751_20210109T185931_T10SEG'\n)\n\n# Set cloudy pixels (greater than 5% probability) to the other image.\nreplaced = image.where(image.select('MSK_CLDPRB').gt(5), replacement)\n\n# Define a map centered on San Francisco Bay.\nmap_replaced = geemap.Map(center=[37.7349, -122.3769], zoom=11)\n\n# Display the images on a map.\nvis_params = {'bands': ['B4', 'B3', 'B2'], 'min': 0, 'max': 2000}\nmap_replaced.add_layer(image, vis_params, 'original image')\nmap_replaced.add_layer(replaced, vis_params, 'clouds replaced')\ndisplay(map_replaced)\n```"]]