Exemple #1
0
def exportWithoutDate(layer, vizParams, output_name):
    if clipper != None:
        layer = clip_mask(layer)
    try:
        Map.centerObject(layer, 8)
    except:
        pass
    #Map.addLayer(layer, vizParams, '{}_{}'.format(prefix, output_name))
    export(layer, "{}_{}".format(prefix, output_name))
Exemple #2
0
def help_calculate(filter_data, date, vizParams, output_name, expression):
    data = filter_data
    if expression != None:
        layer = eval(expression)
    else:
        layer = data
    if clipper != None:
        layer = clip_mask(layer)
    try:
        Map.centerObject(layer, 8)
    except:
        pass
    #Map.addLayer(layer, vizParams, '{}_{}_{}'.format(prefix, date, output_name))
    export(layer, "{}_{}_{}".format(prefix, date, output_name))
Exemple #3
0
    return image.addBands(ndvi).addBands(mndwi).addBands(evi).addBands(lswi)


# Map the function over one year of data.
L8sr = ee.ImageCollection('LANDSAT/LC08/C01/T1_SR') \
    .filterDate('2019-01-01', '2019-12-31') \
    .filter(ee.Filter.lt("CLOUD_COVER", 30)) \
    .map(maskL8sr)
L8sr = L8sr.median().clip(ThaiBinh)

# Compute multiple indices
L8col = compute_indices(L8sr)
print(L8col)

# Display the results.
Map.centerObject(ThaiBinh, 9)
Map.addLayer(L8sr, {'bands': ['B4', 'B3', 'B2'], 'min': 0, 'max': 0.3})
# Map.addLayer(image, imageVisParam, 'True colour image')
classNames = Mangrove.merge(Shrimp).merge(Residence).merge(Water).merge(
    Agriculture).merge(Other).merge(Evergreen)
#print(classNames)
bands = L8col.bandNames()
training = L8col.select(bands).sampleRegions({
    'collection': classNames,
    'properties': ['landcover'],
    'scale': 30
})

#print(training)
classifier = ee.Classifier.randomForest(100).train({
    'features': training,
Exemple #4
0
# GitHub URL: https://github.com/giswqs/qgis-earthengine-examples/tree/master/Filter/filter_string_starts_with.py

import ee
from ee_plugin import Map


states = ee.FeatureCollection('TIGER/2018/States')

# Select states its name starting with 'Al'
selected = states.filter(ee.Filter.stringStartsWith('NAME', 'Al'))


Map.centerObject(selected, 6)
Map.addLayer(ee.Image().paint(selected, 0, 2), {'palette': 'yellow'}, 'Selected')
Exemple #5
0
import ee
from ee_plugin import Map
#Filtrar por Pais
coleccionLimites = ee.FeatureCollection("USDOS/LSIB/2017")
filtropais = coleccionLimites.filter(ee.Filter.eq('COUNTRY_NA', 'Mexico'))
Map.centerObject(filtropais,6)
#Importar Coleccion SENTINEL 5P
sentinel5P = ee.ImageCollection("COPERNICUS/S5P/NRTI/L3_NO2")
#Obtener Concentracion de NO2
NO2 = sentinel5P.filterDate("2019-08-01","2019-08-30").select("NO2_column_number_density")\
.max().clip( filtropais)
Map.addLayer(NO2,{'min':0,'max':0.0002,'palette':['black', 'blue', 'purple', 'cyan', 'green', 'yellow', 'red']},"NO2")


# GitHub URL: https://github.com/giswqs/qgis-earthengine-examples/tree/master/Visualization/landsat_symbology.py

import ee
from ee_plugin import Map

geometry = ee.Geometry.Point([-122.30287513732901, 37.441115780341605])

landsat = ee.ImageCollection("LANDSAT/LC08/C01/T1") \
    .filterDate('2016-01-01', '2017-01-01') \
    .filterBounds(geometry)

composite = ee.Algorithms.Landsat.simpleComposite(**{
    'collection': landsat,
    'asFloat': True
})

rgbVis = {'bands': ["B4", "B3", "B2"], 'min': 0, 'max': 0.3}
nirVis = {'bands': ["B5", "B4", "B3"], 'min': 0, 'max': [0.5, 0.3, 0.3]}
tempVis = {
    'bands': ["B10"],
    'min': 280,
    'max': 310,
    'palette': ["blue", "red", "orange", "yellow"]
}

Map.addLayer(composite, rgbVis, "RGB")
Map.addLayer(composite, nirVis, "False Color")
Map.addLayer(composite, tempVis, "Thermal")

Map.centerObject(ee.FeatureCollection(geometry), 10)
waterSurface = ee.Image('JRC/GSW1_0/GlobalSurfaceWater')
waterChange = waterSurface.select('transition')
# Select Permanent Water Only:
Permanent_Water = 1  # value 1 represents pixels of permenant water, no change
waterMask = waterChange.eq(
    Permanent_Water)  # Water mask boolean = 1 to detect whater bodies
# Map.setCenter(24.43874, 61.58173, 10)
# Map.addLayer(waterMask, {}, 'Water Mask')
# Map.centerObject(masked)
OnlyLakes = waterMask.updateMask(waterMask)

roi = ee.Geometry.Polygon([[[22.049560546875, 61.171214253920965],
                            [22.0330810546875, 60.833021871926185],
                            [22.57415771484375, 60.83168327936567],
                            [22.5714111328125, 61.171214253920965]]])

classes = OnlyLakes.reduceToVectors(
    **{
        'reducer': ee.Reducer.countEvery(),
        'geometry': roi,
        'scale': 30,
        'maxPixels': 1e10
    })
simpleClasses = classes.geometry().simplify(50)

Map.centerObject(ee.FeatureCollection(roi), 10)
Map.addLayer(ee.Image().paint(classes, 0, 2), {'palette': 'red'}, "original")
Map.addLayer(ee.Image().paint(simpleClasses, 0, 2), {'palette': 'blue'},
             "simplified")
Exemple #8
0
import ee 
from ee_plugin import Map 

geometry = ee.Geometry.Point([5.7788, 52.7005])

# Get the VV collection.
collectionVV = ee.ImageCollection('COPERNICUS/S1_GRD') \
    .filter(ee.Filter.eq('instrumentMode', 'IW')) \
    .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV')) \
    .filter(ee.Filter.eq('orbitProperties_pass', 'DESCENDING')) \
    .select(['VV'])

# Create a 3 band stack by selecting from different periods (months)
im1 = ee.Image(collectionVV.filterDate('2016-04-01', '2016-05-30').mean())
im2 = ee.Image(collectionVV.filterDate('2016-06-01', '2016-08-31').mean())
im3 = ee.Image(collectionVV.filterDate('2016-09-01', '2016-11-30').mean())

Map.centerObject(geometry, 13)
Map.addLayer(im1.addBands(im2).addBands(im3), {'min': -25, 'max': 0}, 'VV stack')

# Get the VH collection.
collectionVH = ee.ImageCollection('COPERNICUS/S1_GRD') \
    .filter(ee.Filter.eq('instrumentMode', 'IW')) \
    .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VH')) \
    .select(['VH'])
# Collection max.  Zoom to Shanghai for an interesting visualization.
Map.addLayer(collectionVH.max(), {'min': -25, 'max': 0}, 'max value', False)

Exemple #9
0
# GitHub URL: https://github.com/giswqs/qgis-earthengine-examples/tree/master/FeatureCollection/select_by_strings.py

import ee
from ee_plugin import Map

#!/usr/bin/env python
"""Select by strings

"""

# Select states with "A" in its name
fc = ee.FeatureCollection('TIGER/2018/States') \
    .filter(ee.Filter.stringContains('STUSPS', 'A'))

image = ee.Image().paint(fc, 0, 2)
Map.centerObject(fc, 6)
Map.addLayer(image, {'palette': 'FF0000'}, '*A*')

# Select states its name starting with 'A'
fc = ee.FeatureCollection('TIGER/2018/States') \
    .filter(ee.Filter.stringStartsWith('STUSPS', 'A'))

image = ee.Image().paint(fc, 0, 2)
Map.addLayer(image, {'palette': '0000FF'}, 'A*')
Exemple #10
0
import ee
from ee_plugin import Map

# Load and display a Landsat TOA image.
image = ee.Image('LANDSAT/LC08/C01/T1_TOA/LC08_044034_20140318')
Map.addLayer(image, {'bands': ['B4', 'B3', 'B2'], 'max': 0.3}, 'Landsat 8')

# Create an arbitrary rectangle as a region and display it.
region = ee.Geometry.Rectangle(-122.2806, 37.1209, -122.0554, 37.2413)
Map.centerObject(ee.FeatureCollection(region), 13)
Map.addLayer(ee.Image().paint(region, 0, 2), {}, 'Region')

# Get a dictionary of means in the region.  Keys are bandnames.
mean = image.reduceRegion(**{
    'reducer': ee.Reducer.mean(),
    'geometry': region,
    'scale': 30
})

print(mean.getInfo())
    def run(self):
        """Run method that performs all the real work"""
        #ee.Initialize()
        # Create the dialog with elements (after translation) and keep reference
        # Only create GUI ONCE in callback, so that it will only load when the plugin is started
        if self.first_start == True:
            self.first_start = False
            self.dlg = Sentinel2DownloadDialog()
        # Add base map
        base_map = QgsProject.instance().mapLayersByName('Google Satellite')
        if len(base_map) == 0:
            urlWithParams = 'type=xyz&url=https://mt1.google.com/vt/lyrs%3Ds%26x%3D%7Bx%7D%26y%3D%7By%7D%26z%3D%7Bz%7D&zmax=19&zmin=0'
            rlayer = QgsRasterLayer(urlWithParams, 'Google Satellite', 'wms')
            if rlayer.isValid():
                QgsProject.instance().addMapLayer(rlayer)
            else:
                self.iface.messageBar().pushMessage(
                    "Không mở được bản đồ nền!",
                    level=Qgis.Success,
                    duration=5)

        self.laydanhsachtinh()
        self.dlg.comboTinh.currentIndexChanged.connect(self.laydanhsachhuyen)
        self.dlg.comboHuyen.currentIndexChanged.connect(self.laydanhsachxa)
        self.tohopmau()

        self.dlg.show()

        result = self.dlg.exec_()

        if result:
            #Get date
            batdau = self.dlg.dateBdau.date()
            ketthuc = self.dlg.dateKthuc.date()
            bd_date = str(batdau)
            kt_date = str(ketthuc)
            # Get info
            tinhchon = self.dlg.comboTinh.currentText()
            huyenchon = self.dlg.comboHuyen.currentText()
            xachon = self.dlg.comboXa.currentText()
            mtinh = int(self.laymacode()['tcode'])
            mhuyen = int(self.laymacode()['hcode'])
            mxa = int(self.laymacode()['xcode'])

            may = int(self.dlg.inputMay.text())
            khoang = int(self.dlg.inputKhoang.text())

            ngayBatdau = str(self.layngay(bd_date))
            ngayKetthuc = str(self.layngay(kt_date))

            hcxvn = ee.FeatureCollection("users/nguyenvanthi/RGX_WGS84")
            commune = hcxvn.filter(ee.Filter(ee.Filter.eq('MATINH', mtinh))) \
                .filter(ee.Filter(ee.Filter.eq('MAHUYEN', mhuyen))) \
                .filter(ee.Filter(ee.Filter.eq('MAXA', mxa)))
            #Get buffer

            sbuffer = int(self.dlg.inputBuffer.text())

            if sbuffer == 0:
                commune_buffered = commune
            else:
                commune_buffered = commune.geometry().buffer(sbuffer)

            #Band combinations
            rgbMethod = self.dlg.comboRGB.currentIndex()
            if rgbMethod == 0:
                bands = ['B4', 'B3', 'B2']  # Natural Color
            elif rgbMethod == 1:
                bands = ['B8', 'B4', 'B3']  # Color Infrared
            elif rgbMethod == 2:
                bands = ['B12', 'B8A', 'B4']  # Short-wave Infrared
            elif rgbMethod == 3:
                bands = ['B11', 'B8', 'B2']  # Agriculture
            elif rgbMethod == 4:
                bands = ['B12', 'B11', 'B2']  # Geology
            else:
                bands = ['B4', 'B3', 'B1']  # Bathymetric

            S2_Collection = ee.ImageCollection("COPERNICUS/S2") \
                .filterDate(ngayBatdau, ngayKetthuc).select(bands) \
                .filterBounds(commune_buffered) \
                .filterMetadata('CLOUDY_PIXEL_PERCENTAGE', "less_than", may) \
                .sort('CLOUD_COVERAGE_ASSESSMENT', True)
            #Get the first image in the collection
            S2 = S2_Collection.first()

            vizParams = {
                'bands': bands,
                'min': 0,
                'max': 2000,
                'gamma': 0.8
            }

            image_date1 = ee.Date(
                S2.get('system:time_start')).format('Y-M-d').getInfo()

            soluonganh = S2_Collection.size().getInfo()

            tmp = self.khoangngay(image_date1, khoang)

            S22 = ee.ImageCollection("COPERNICUS/S2").filterDate(tmp['bd'], tmp['kt']) \
                .select(bands) \
                .filterBounds(commune_buffered) \
                .median()\
                .clip(commune_buffered)
            Map.centerObject(commune, 14)
            Map.addLayer(
                S2.clip(commune_buffered), vizParams,
                "S2_" + str(xachon) + "_" + image_date1 + " (Ảnh đơn)")
            Map.addLayer(
                S22, vizParams,
                "S2_" + str(xachon) + "_" + image_date1 + " (Tập hợp)")
            Map.addLayer(commune_buffered, {'color': 'red'},
                         "RG_" + str(xachon), False, 0.2)

            ### Save image to Google Drive3

            ### Message bar info
            self.iface.messageBar().pushMessage(
                "Mở thành công ảnh Sentiel-2 của " + xachon + " " + huyenchon +
                " " + tinhchon + "!",
                level=Qgis.Success,
                duration=10)

            pass
Exemple #12
0
import ee
from ee_plugin import Map

roi = ee.FeatureCollection('TIGER/2018/States') \
  .filter(ee.Filter.eq('STUSPS', 'ND'))

dataset = ee.ImageCollection('USDA/NAIP/DOQQ') \
                  .filter(ee.Filter.date('2016-01-01', '2017-12-31'))\
                  .filterBounds(roi)
TrueColor = dataset.select(['N', 'R', 'G']).mosaic()
TrueColorVis = {
    'min': 0.0,
    'max': 255.0,
}
# Map.setCenter(-73.9958, 40.7278, 15)
Map.centerObject(roi, 8)
Map.addLayer(TrueColor, TrueColorVis, 'True Color')
Exemple #13
0
    forested = forested.map(lambda f: f.set('R', 0).set('G', 136).set('B', 55))

    pond = fc.filter(ee.Filter.eq('WETLAND_TY', 'Freshwater Pond'))
    pond = pond.map(lambda f: f.set('R', 104).set('G', 140).set('B', 192))

    lake = fc.filter(ee.Filter.eq('WETLAND_TY', 'Lake'))
    lake = lake.map(lambda f: f.set('R', 19).set('G', 0).set('B', 124))

    riverine = fc.filter(ee.Filter.eq('WETLAND_TY', 'Riverine'))
    riverine = riverine.map(
        lambda f: f.set('R', 1).set('G', 144).set('B', 191))

    fc = ee.FeatureCollection(
        emergent.merge(forested).merge(pond).merge(lake).merge(riverine))

    base = ee.Image(0).mask(0).toInt8()
    img = base.paint(fc, 'R') \
        .addBands(base.paint(fc, 'G')
                  .addBands(base.paint(fc, 'B')))
    return img


fromFT = ee.FeatureCollection("users/wqs/Pipestem/Pipestem_HUC10")
Map.addLayer(ee.Image().paint(fromFT, 0, 2), {}, 'Watershed')
huc8_id = '10160002'
nwi_asset_path = 'users/wqs/NWI-HU8/HU8_' + huc8_id + '_Wetlands'  # NWI wetlands for the clicked watershed
clicked_nwi_huc = ee.FeatureCollection(nwi_asset_path)
nwi_color = nwi_add_color(clicked_nwi_huc)
Map.centerObject(clicked_nwi_huc, 10)
Map.addLayer(nwi_color, {'gamma': 0.3, 'opacity': 0.7}, 'NWI Wetlands Color')
Exemple #14
0
# GitHub URL: https://github.com/giswqs/qgis-earthengine-examples/tree/master/FeatureCollection/merge_feature_collections.py

import ee
from ee_plugin import Map


SD = ee.FeatureCollection('TIGER/2018/States') \
    .filter(ee.Filter.eq('STUSPS', 'SD'))

ND = ee.FeatureCollection('TIGER/2018/States') \
    .filter(ee.Filter.eq('STUSPS', 'ND'))

states = SD.merge(ND)
Map.centerObject(states, 6)
Map.addLayer(ee.Image().paint(states, 0, 2), {}, 'Dakotas')
# print(states.size().getInfo())
import ee
from ee_plugin import Map

# Define an arbitrary region in which to compute random points.
region = ee.Geometry.Rectangle(-119.224, 34.669, -99.536, 50.064)

# Create 1000 random points in the region.
randomPoints = ee.FeatureCollection.randomPoints(region)

# Display the points.
Map.centerObject(randomPoints)
Map.addLayer(randomPoints, {}, 'random points')
        'maxPixels': 1e9
    })
    return std_value


dataset = ee.Image('USGS/NED')
dem = dataset.select('elevation')
# dem = ee.Image('srtm90_v4')
vis_params = {'min': 0, 'max': 3000}
Map.addLayer(dem, vis_params, 'NED', False)

roi = ee.Geometry.Polygon(
    [[[-120.18204899532924, 38.53481618819663],
      [-120.18204899532924, 36.54889033300136],
      [-116.75431462032924, 36.54889033300136],
      [-116.75431462032924, 38.53481618819663]]])

image = dem.clip(roi)
Map.centerObject(image, 9)
Map.addLayer(image, vis_params, 'DEM')

scale = image.projection().nominalScale()
print("Resolution: ", scale.getInfo())

scale = 30

print("Minimum value: ", minValue(image, scale).get('elevation').getInfo())
print("Maximum value: ", maxValue(image, scale).get('elevation').getInfo())
print("Average value: ", meanValue(image, scale).get('elevation').getInfo())
print("Standard deviation: ", stdValue(image, scale).get('elevation').getInfo())
Exemple #17
0
import ee
from ee_plugin import Map

point = ee.Geometry.Point([1.5, 1.5])
Map.addLayer(point, {'color': '1eff05'}, 'point')

lineString = ee.Geometry.LineString([[-35, -10], [35, -10], [35, 10],
                                     [-35, 10]])
Map.addLayer(lineString, {'color': 'FF0000'}, 'lineString')

linearRing = ee.Geometry.LinearRing([[-35, -10], [35, -10], [35, 10],
                                     [-35, 10], [-35, -10]])
Map.addLayer(linearRing, {'color': 'ee38ff'}, 'linearRing')

rectangle = ee.Geometry.Rectangle([-40, -20, 40, 20])
Map.addLayer(rectangle, {'color': 'ffa05c'}, 'rectangle')

polygon = ee.Geometry.Polygon([[[-5, 40], [65, 40], [65, 60], [-5, 60],
                                [-5, 60]]])

planarPolygon = ee.Geometry(polygon, None, False)

Map.addLayer(polygon, {'color': 'FF0000'}, 'geodesic polygon')
Map.addLayer(planarPolygon, {'color': '000000'}, 'planar polygon')

Map.centerObject(polygon)
           .map(MaskL8sr)\
           .map(L8_NDVI)

#Get information on the returned images: Nbr of images returned per Collection, acquisition date, bands....
count_images_L8 = aft_L8.size()
count_images_L5 = bef_L5.size()
print("Your LANDSAT-8 query returned", count_images_L8.getInfo(), "images")
print("Your LANDSAT-5 query returned", count_images_L5.getInfo(), "images")

image = aft_L8.first()
image_date = image.date().format('YYYY-MM-dd').getInfo()
image_bands = image.bandNames().getInfo()
print ("This image was acquired on", image_date, "and has the following bands:",image_bands)

#Show a random Landsat-8 image from the collection
Map.centerObject(AOI, 8)
Map.addLayer (image.visualize(bands = ['B4', 'B3', 'B2'], min= 0, max= 3000, gamma= 1.4))

# Compute statisctis (mean, StDev) and NDVI change/anomalie 
bef_mean_NDVI = bef_L5.select ('L5_NDVI').mean()
aft_mean_NDVI = aft_L8.select ('L8_NDVI').mean() 
bef_stDev_NDVI = bef_L5.select ('L5_NDVI').reduce (ee.Reducer.stdDev())

ndviChange = ((aft_mean_NDVI.subtract(bef_mean_NDVI))\
                  .divide(bef_mean_NDVI))\
                  .multiply(100)\
                  .rename('ndviChange')\
                  .clip(AOI);

                                
ndviAnomaly = ((aft_mean_NDVI.subtract(bef_mean_NDVI))\
Exemple #19
0
# Define a palette for the IGBP classification.
igbpPalette = [
    'aec3d4',  # water
    '152106',
    '225129',
    '369b47',
    '30eb5b',
    '387242',  # forest
    '6a2325',
    'c3aa69',
    'b76031',
    'd9903d',
    '91af40',  # shrub, grass
    '111149',  # wetlands
    'cdb33b',  # croplands
    'cc0013',  # urban
    '33280d',  # crop mosaic
    'd7cdcc',  # snow and ice
    'f7e084',  # barren
    '6f6f6f'  # tundra
]

# Display the input and the classification.
Map.centerObject(roi, 10)
Map.addLayer(input, {'bands': ['B3', 'B2', 'B1'], 'max': 0.4}, 'landsat')
Map.addLayer(classified, {
    'palette': igbpPalette,
    'min': 0,
    'max': 17
}, 'classification')
import ee
from ee_plugin import Map

# Load a raw Landsat scene and display it.
raw = ee.Image('LANDSAT/LC08/C01/T1/LC08_044034_20140318')
Map.centerObject(raw, 10)
Map.addLayer(raw, {
    'bands': ['B4', 'B3', 'B2'],
    'min': 6000,
    'max': 12000
}, 'raw')

# Convert the raw data to radiance.
radiance = ee.Algorithms.Landsat.calibratedRadiance(raw)
Map.addLayer(radiance, {'bands': ['B4', 'B3', 'B2'], 'max': 90}, 'radiance')

# Convert the raw data to top-of-atmosphere reflectance.
toa = ee.Algorithms.Landsat.TOA(raw)

Map.addLayer(toa, {'bands': ['B4', 'B3', 'B2'], 'max': 0.2}, 'toa reflectance')
import ee
from ee_plugin import Map

# Load a cloudy Landsat scene and display it.
cloudy_scene = ee.Image('LANDSAT/LC08/C01/T1_TOA/LC08_044034_20140926')
Map.centerObject(cloudy_scene)
Map.addLayer(cloudy_scene, {
    'bands': ['B4', 'B3', 'B2'],
    'max': 0.4
}, 'TOA', False)

# Add a cloud score band.  It is automatically called 'cloud'.
scored = ee.Algorithms.Landsat.simpleCloudScore(cloudy_scene)

# Create a mask from the cloud score and combine it with the image mask.
mask = scored.select(['cloud']).lte(20)

# Apply the mask to the image and display the result.
masked = cloudy_scene.updateMask(mask)
Map.addLayer(masked, {'bands': ['B4', 'B3', 'B2'], 'max': 0.4}, 'masked')

# Load a Landsat 8 composite and set the SENSOR_ID property.
mosaic = ee.Image(ee.ImageCollection('LANDSAT/LC8_L1T_8DAY_TOA').first()) \
  .set('SENSOR_ID', 'OLI_TIRS')

# Cloud score the mosaic and display the result.
scored_mosaic = ee.Algorithms.Landsat.simpleCloudScore(mosaic)
Map.addLayer(scored_mosaic, {
    'bands': ['B4', 'B3', 'B2'],
    'max': 0.4
}, 'TOA mosaic', False)
import ee
from ee_plugin import Map

# get a single feature
countries = ee.FeatureCollection("USDOS/LSIB_SIMPLE/2017")
country = countries.filter(ee.Filter.eq('country_na', 'Ukraine'))
Map.addLayer(country, {'color': 'orange'}, 'feature collection layer')

# TEST: center feature on a map
Map.centerObject(country)
import ee
from ee_plugin import Map

# Center the map on an image.

image = ee.Image('LANDSAT/LC08/C01/T1/LC08_044034_20130603')
Map.addLayer(image, {'bands': ['B4', 'B3', 'B2'], 'max': 20000})
Map.centerObject(image)
Exemple #24
0
print(img2017)

# NDVI can be calculated using expression
# # NDVI for 2014
ndvi2014 = img2014.expression('(NIR - RED) / (NIR + RED)', {
    'NIR': img2014.select('B4'),
    'RED': img2014.select('B3')
})

# NDVI can be calculated using math operation
# # NDVI for 2017
ndvi2017 = img2017.select('B4').subtract(img2017.select('B3')) \
.divide(img2017.select('B4').add(img2017.select('B3')))

# Load the land mask from the SRTM DEM.
landMask = ee.Image('CGIAR/SRTM90_V4').mask()

# Analyzing the difference
ndviChange = ndvi2017.subtract(ndvi2014)

# Updating the land mask
ndviUp = ndviChange.updateMask(landMask)

# Ploting in map layer
Map.centerObject(ndvi2017, 9)
Map.addLayer(ndviUp, {
    'min': -0.3,
    'max': 0.3,
    'palette': ['FFFFFF', '0000FF', 'FF0000']
}, "Changes of NDVI  from 2014 to 2017")
Exemple #25
0
    def run(self):
        """Run method that performs all the real work"""
        
        def blankPaint(geometry):
            
            blank = ee.Image(0).mask(0)
            geometryDraw = blank.paint(geometry, '0000AA', 1)
            
            return geometryDraw
        # Create the dialog with elements (after translation) and keep reference
        # Only create GUI ONCE in callback, so that it will only load when the plugin is started
        if self.first_start == True:
            self.first_start = False
            self.dlg = simex_pluginDialog()

        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
      
            uf = self.dlg.selectUF.currentText()
            path = self.dlg.path.toPlainText()
            row = self.dlg.row.toPlainText()
            cloud_cover = int(self.dlg.cloudcover.cleanText())
            startdate = self.dlg.startdate.date().toString('yyyy-MM-dd') 
            enddate = self.dlg.enddate.date().toString('yyyy-MM-dd') 
            self.iface.messageBar().pushMessage('loading ...')
            geometry = path_row_am.filterMetadata('PATH', 'equals', int(path)).filterMetadata('ROW', 'equals', int(row)).geometry()
            countourGeometry = blankPaint(geometry)
            Map.centerObject(geometry, 100)
            progressMessageBar = iface.messageBar().createMessage("loading...")
            progress = QProgressBar()
            progress.setMaximum(10)
            progress.setAlignment(Qt.AlignLeft|Qt.AlignVCenter)
            progressMessageBar.layout().addWidget(progress)
            iface.messageBar().pushWidget(progressMessageBar, Qgis.Info)

            for i in range(10):
                time.sleep(1)
                progress.setValue(i + 1)
            
            parametrosColecaoL8 = { 'collectionid': 'LANDSAT/LC08/C01/T1_SR',
                    'geometry': geometry.centroid(),
                    'dateStart': ee.Date(startdate),
                    'dateEnd': ee.Date(enddate),
                    'cloud_cover': cloud_cover,
                }
            colecaoL8 = getCollection(parametrosColecaoL8).select(bandNames("l8")['bandNames'],bandNames("l8")['newNames'])\
                                        .map(getSMA).map(getNDFI)
            #nImages = colecaoL8.size().getInfo()
            #colList = colecaoL8.toList(nImages)
            #idG = 1

            listYears = list(range(int(startdate[:4]),int(enddate[:4])+1))
          
            for item in listYears:
                
                #imgYear = ee.Image(colecaoL8.filterDate(str(item) + '-01-01',str(item+1) + '-01-01').sort('cloud_cover').first())

                colYear = colecaoL8.filterDate(str(item) + '-01-01',str(item+1) + '-01-01').sort('cloud_cover').limit(3)                
                colList = colYear.toList(5)
                idG = 1

                while idG < 3:
                    
                    img = ee.Image(colList.get(idG))

                    try:
                        dictionaryInfos = ee.Dictionary({'satellite_name':img.get('satellite_name'),
                                            'date':img.get('date'),
                                            'cloud_cover':img.get('cloud_cover')}).getInfo()
                        if listYears.index(item) == len(listYears)-2:
                            status = True
                        else:
                            status = False  

                        Map.addLayer(img, {'bands': ['swir2'],'gain' : [0.2],'gamma':0.6},\
                                            'B7_' + str(dictionaryInfos['date']).replace('-','_')+'_'+dictionaryInfos['satellite_name'],status)
                    
                        Map.addLayer(img,{"bands": ['ndfi'],
                                                    "palette": ['ffffff', 'fffcff', 'fff9ff', 'fff7ff', 'fff4ff', 'fff2ff', 'ffefff', 'ffecff', 'ffeaff', 'ffe7ff',
                                                                'ffe5ff', 'ffe2ff', 'ffe0ff', 'ffddff', 'ffdaff', 'ffd8ff', 'ffd5ff', 'ffd3ff', 'ffd0ff', 'ffceff',
                                                                'ffcbff', 'ffc8ff', 'ffc6ff', 'ffc3ff', 'ffc1ff', 'ffbeff', 'ffbcff', 'ffb9ff', 'ffb6ff', 'ffb4ff',
                                                                'ffb1ff', 'ffafff', 'ffacff', 'ffaaff', 'ffa7ff', 'ffa4ff', 'ffa2ff', 'ff9fff', 'ff9dff', 'ff9aff',
                                                                'ff97ff', 'ff95ff', 'ff92ff', 'ff90ff', 'ff8dff', 'ff8bff', 'ff88ff', 'ff85ff', 'ff83ff', 'ff80ff',
                                                                'ff7eff', 'ff7bff', 'ff79ff', 'ff76ff', 'ff73ff', 'ff71ff', 'ff6eff', 'ff6cff', 'ff69ff', 'ff67ff',
                                                                'ff64ff', 'ff61ff', 'ff5fff', 'ff5cff', 'ff5aff', 'ff57ff', 'ff55ff', 'ff52ff', 'ff4fff', 'ff4dff',
                                                                'ff4aff', 'ff48ff', 'ff45ff', 'ff42ff', 'ff40ff', 'ff3dff', 'ff3bff', 'ff38ff', 'ff36ff', 'ff33ff',
                                                                'ff30ff', 'ff2eff', 'ff2bff', 'ff29ff', 'ff26ff', 'ff24ff', 'ff21ff', 'ff1eff', 'ff1cff', 'ff19ff',
                                                                'ff17ff', 'ff14ff', 'ff12ff', 'ff0fff', 'ff0cff', 'ff0aff', 'ff07ff', 'ff05ff', 'ff02ff', 'ff00ff',
                                                                'ff00ff', 'ff0af4', 'ff15e9', 'ff1fdf', 'ff2ad4', 'ff35c9', 'ff3fbf', 'ff4ab4', 'ff55aa', 'ff5f9f',
                                                                'ff6a94', 'ff748a', 'ff7f7f', 'ff8a74', 'ff946a', 'ff9f5f', 'ffaa55', 'ffb44a', 'ffbf3f', 'ffc935',
                                                                'ffd42a', 'ffdf1f', 'ffe915', 'fff40a', 'ffff00', 'ffff00', 'fffb00', 'fff700', 'fff300', 'fff000',
                                                                'ffec00', 'ffe800', 'ffe400', 'ffe100', 'ffdd00', 'ffd900', 'ffd500', 'ffd200', 'ffce00', 'ffca00',
                                                                'ffc600', 'ffc300', 'ffbf00', 'ffbb00', 'ffb700', 'ffb400', 'ffb000', 'ffac00', 'ffa800', 'ffa500',
                                                                'ffa500', 'f7a400', 'f0a300', 'e8a200', 'e1a200', 'd9a100', 'd2a000', 'ca9f00', 'c39f00', 'bb9e00',
                                                                'b49d00', 'ac9c00', 'a59c00', '9d9b00', '969a00', '8e9900', '879900', '7f9800', '789700', '709700',
                                                                '699600', '619500', '5a9400', '529400', '4b9300', '439200', '349100', '2d9000', '258f00', '1e8e00',
                                                                '168e00', '0f8d00', '078c00', '008c00', '008c00', '008700', '008300', '007f00', '007a00', '007600',
                                                                '007200', '006e00', '006900', '006500', '006100', '005c00', '005800', '005400', '005000', '004c00'],\
                                                                "min":0,"max":200},'NDFI_' + str(dictionaryInfos['date']).replace('-','_')+'_'+dictionaryInfos['satellite_name'],status)
                    
                    except Exception as e:
                    # print('Exception\n',str(e))
                        pass

                    idG = idG + 1 

            for i in range(10):
                
                time.sleep(1)
                progress.setValue(i + 1)
            
            iface.messageBar().clearWidgets()
            Map.addLayer(countourGeometry,{ 'palette': '#000000', 'opacity': 0.8 },str(path) + '_' + str(row))
            
            for item in auxLayers[dicAuxState[uf]][0]:
               
                outline = blankPaint(auxLayers[dicAuxState[uf]][item][1][1])
                Map.addLayer(outline,auxLayers[dicAuxState[uf]][item][1][3],\
                                auxLayers[dicAuxState[uf]][item][1][2], False)
# GitHub URL: https://github.com/giswqs/qgis-earthengine-examples/tree/master/FeatureCollection/column_statistics.py

import ee
from ee_plugin import Map

fromFT = ee.FeatureCollection("users/wqs/Pipestem/Pipestem_HUC10")
geom = fromFT.geometry()
Map.centerObject(fromFT)
Map.addLayer(ee.Image().paint(geom, 0, 2), {}, 'Watersheds')

print(fromFT.aggregate_stats('AreaSqKm'))

total_area = fromFT.reduceColumns(
    **{
        'reducer': ee.Reducer.sum(),
        'selectors': ['AreaSqKm']
        # weightSelectors: ['weight']
    }).getInfo()

print("Total area: ", total_area)
Exemple #27
0
}
ano = '2018'

limitCaatC5 = ee.FeatureCollection(param['assetlimit']) 
FeatColbacia = ee.FeatureCollection(param['assetBaciaC4'])

Mosaicos = ee.ImageCollection(param['assetMosaic']).filter(
                    ee.Filter.Or(
                        ee.Filter.eq("biome", 'CAATINGA'),
                        ee.Filter.eq("biome", 'CERRADO'),
                        ee.Filter.eq("biome", 'MATAATLANTICA')
                    ))\
                    .filterBounds(FeatColbacia).select(param['bandas'])\
                    .filter(ee.Filter.eq('year', int(ano))).mosaic()\
                    .clip(FeatColbacia).divide(10)

imgMap5_0 = ee.Image(param['assetCol5']).clip(limitCaatC5).select('classification_' + ano)
FeatBacias = ee.Image().byte().paint(FeatColbacia, 1, 1)
Featlimit = ee.Image().byte().paint(limitCaatC5, 1, 2)




# Map.addLayer(imgMap5_0, {min:1, max: 45, 'palette': paleta }, 'Col5')
Map.addLayer(imgMap5_0.visualize(**visualizar['visclassC5']))
# Map.addLayer(Featlimit, {'palette': '0000FF','opacity': 0.75}, 'lCaatinga')
# Map.addLayer(FeatBacias, {'palette': 'FF0000', 'opacity': 0.8}, 'Bacias')
# Map.addLayer(Mosaicos.visualize(**visualizar['visMosaic']))
#Center to point
Map.centerObject(limitCaatC5, 6)
Exemple #28
0
# GitHub URL: https://github.com/giswqs/qgis-earthengine-examples/tree/master/Tutorials/Medium/remove_colors.py

import ee 
from ee_plugin import Map 

# Credits to: Keiko Nomura, Senior Analyst, Space Intelligence Ltd
# Source: https://medium.com/google-earth/10-tips-for-becoming-an-earth-engine-expert-b11aad9e598b
# GEE JS: https://code.earthengine.google.com/?scriptPath=users%2Fnkeikon%2Fmedium%3Aremove_colours 

point = ee.Geometry.Point([2.173487088281263, 41.38710609258852])
Map.centerObject(ee.FeatureCollection(point), 11)

# Select the least cloudy image in 2019
image = ee.ImageCollection('COPERNICUS/S2_SR') \
  .filter(ee.Filter.calendarRange(2019, 2019, 'year')) \
  .filterBounds(point) \
  .sort('CLOUDY_PIXEL_PERCENTAGE', True) \
  .select(['B2', 'B3', 'B4', 'B8']) \
  .first()

# print('Image used', image)

Map.addLayer(image, {
  'bands': ['B4', 'B3', 'B2'],
  'min': 0,
  'max': 2500
}, 'RGB (True colours)')
Map.addLayer(image, {
  'bands': ['B3', 'B3', 'B3'],
  'min': 0,
  'max': 2500,
# GitHub URL: https://github.com/giswqs/qgis-earthengine-examples/tree/master/Image/cell_statistics.py

import ee 
from ee_plugin import Map 

# Load an image and select some bands of interest.
image = ee.Image('LANDSAT/LC8_L1T/LC80440342014077LGN00') \
    .select(['B4', 'B3', 'B2'])

# Reduce the image to get a one-band maximum value image.
maxValue = image.reduce(ee.Reducer.max())

# Display the result.
Map.centerObject(image, 10)
Map.addLayer(maxValue, {'max': 13000}, 'Maximum value image')

L8T1 = 'LANDSAT/LC08/C01/T1_SR'
MODIS = 'MODIS/006/MOD09GA'
S2 = 'COPERNICUS/S2_SR'

#########################/
#set date range
starta = '2019-03-01'
enda = '2019-11-30'

# Create a geodesic polygon containing Boulder, CO
reqGeometry = ee.Geometry.Polygon([
  [[43.36666667, 16.13333333], [45.91666667, 16.13333333], [45.91666667, 15.73333333], [43.36666667, 15.73333333], [43.36666667, 16.13333333]]])
# Display the polygon on the map
Map.centerObject(reqGeometry)
Map.addLayer(reqGeometry, {'color': 'FF0000'}, 'geodesic polygon')

#/Make date sequence of 15 days
start = ee.Date.fromYMD(2019,3,01)
#change the second number to how many 15 dqay sequences fit into your date range - this will provide an error if there are too many.
months = ee.List.sequence(0, 18*15, 15)

def func_rlp(d):
  return start.advance(d, 'days')

startDates = months.map(func_rlp)