how to download images using google earth engine's python API - python

I am using Google's Earth Engine API to access LandSat images.
The program is as given below,
import ee
ee.Initialize()
Load a landsat image and select three bands.
landsat = ee.Image('LANDSAT/LC8_L1T_TOA
/LC81230322014135LGN00').select(['B4', 'B3', 'B2']);
Create a geometry representing an export region.
geometry = ee.Geometry.Rectangle([116.2621, 39.8412, 116.4849, 40.01236]);
Export the image, specifying scale and region.
export.image.toDrive({
image: landsat,
description: 'imageToDriveExample',
scale: 30,
region: geometry
});
it throws the following error.
Traceback (most recent call last):
File "e6.py", line 11, in <module>
export.image.toDrive({
NameError: name 'export' is not defined
Please Help. I am unable to find the right function to download images.

If you are using the python API, you have to use the 'batch' submodule. The default behaviour is to save to your google drive. You can specify your bounding box as a list of coordinates as well:
llx = 116.2621
lly = 39.8412
urx = 116.4849
ury = 40.01236
geometry = [[llx,lly], [llx,ury], [urx,ury], [urx,lly]]
task_config = {
'description': 'imageToDriveExample',
'scale': 30,
'region': geometry
}
task = ee.batch.Export.image(landsat, 'exportExample', task_config)
task.start()
This should generate a file called 'exportExample.tif' in your GoogleDrive top folder.
Also note that the semicolons at the end of each line are not necessary in python.

To build on Ben's answer, you can also use:
geometry = ee.Geometry.Rectangle([116.2621, 39.8412, 116.4849, 40.01236])
from your original post, but add the following line beneath it so the coordinates are in the correct format for the task_config-->Region field:
geometry = ee.Geometry.Rectangle([116.2621, 39.8412, 116.4849, 40.01236])
geometry = geometry['coordinates'][0]
It prevents a "task_config" formatting mismatch when you get to here:
task = ee.batch.Export.image(landsat, 'exportExample', task_config)
This will allow you to use the given function from the API, but it will extract the coordinates in such a way that you can use them in the approach suggested by Ben above.

There is a typo in your code, Export should start from the capital letter. See documentation.

Where do you specify the dates? Is there any good, quick, documentation or tutorial for Python? seems there are plenty about JavaScript one!

There is good, quick example of python api.You can check this link. There is 1 post for download satellite image using python api.

Related

How to create a Wind Rose in KML format (google earth) using Python

I need to create a Wind Rose KML file to be opened in google earth with as (similar to) the following pictures.
I can create wind roses using windrose python module, like this one:
And I know how to create KML points and lines in python using simplekml module like this one:
Does anyone know any package capable of doing that?
or any idea of how to do it?
If you use matplotlib when draw windrose, try to save the fig with following opthons.
plt.axis('off')
plt.savefig('windrose.png', bbox_inches='tight', pad_inches=0, transparent=True)
After you got the image file, generate ground overlay code in kml.
import simplekml
kml = simplekml.Kml(open=1)
doc = kml.newdocument(name='sample', open=1, visibility=0)
ground = doc.newgroundoverlay(name='windrose example')
ground.icon.href = 'windrose.png'
ground.altitudemode = simplekml.AltitudeMode.absolute
ground.altitude = 500.0
ground.latlonbox.north = 38.031368255615234
ground.latlonbox.south = 37.11344909667969
ground.latlonbox.east = 141.5791015625
ground.latlonbox.west = 140.4208984375
ground.visibility = 1
kml.save('sample.kml')
Each values are need to adjust.
Please refer following, if you'd like to know more about ground overlay.
https://developers.google.com/kml/documentation/altitudemode#absolute
Open Google Earth.
Draw a static picture\chart like wanted one over a map.
Save it into a KML file.
Open with any text editor.
It must show you an example which lead you to generate a valid KML with your data.

Saving area within a shape (rectangle) as image from multiple powerpoint slides

I'm attempting to grab an image of diagrams constructed within a rectangle on a power point slide deck. I found python-pptx and am able to identify the shapes on each slide. Is there any way to expand this to take a snapshot of the area within the rectangle shape and export it as an image?
# Auto grab the photos created in Powerpoint
from pptx import Presentation
prs = Presentation('ex.pptx')
for slide in prs.slides:
print(slide)
for shape in slide.shapes:
print(shape)
# Identify shape on each slide, find area within, and save as .png
I think you're going to be best off looking at a COM32 type of solution, either writing something in VBA or possibly using the win32com library in Python if you really want a Python solution.
Either way this is going to fire up a "live" PowerPoint application instance and basically run it by remote control. That sort of thing isn't a great idea server-side, but if it's just for personal productivity it might work fine.
python-pptx can't do this sort of thing and probably never will. The rendering engine needs to get involved in this type of work and python-pptx is strictly a .pptx file editor/generator.
With Aspose.Slides for Python, you can easily save presentation shapes to images. The following code example shows you how to save all charts from a presentation to PNG images:
import aspose.slides as slides
import aspose.slides.charts as charts
import aspose.pydrawing as draw
with slides.Presentation("example.pptx") as presentation:
for slide_index, slide in enumerate(presentation.slides):
for shape_index, shape in enumerate(slide.shapes):
# Looking for charts, for example.
if isinstance(shape, charts.Chart):
# Get a chart image.
with shape.get_thumbnail() as chart_image:
# Save the chart image to PNG.
image_path = "chart_image_{}_{}.png".format(slide_index, shape_index)
chart_image.save(image_path, draw.imaging.ImageFormat.png)
Aspose.Slides for Python is a paid product, but you can get a temporary license or use it in a trial mode to evaluate all features for managing presentations. Alternatively, you can use Aspose.Slides Cloud SDK for Python. This package provides a REST-based API for managing presentations as well. The code example below shows you how to do the same using Aspose.Slides Cloud:
import asposeslidescloud
import aspose.pydrawing as draw
from asposeslidescloud.apis.slides_api import SlidesApi
from asposeslidescloud.models import *
slides_api = SlidesApi(None, "my_client_id", "my_client_secret")
file_name = "example.pptx"
# Upload the presentation to the default storage.
with open(file_name, "rb") as file_stream:
slides_api.upload_file(file_name, file_stream)
# Get the number of slides.
slides_info = slides_api.get_slides(file_name)
slide_count = len(slides_info.slide_list)
for slide_index in range(1, slide_count + 1):
# Get the number of shapes on the current slide.
shapes_info = slides_api.get_shapes(file_name, slide_index)
shape_count = len(shapes_info.shapes_links)
for shape_index in range(1, shape_count + 1):
shape = slides_api.get_shape(file_name, slide_index, shape_index)
# Looking for charts, for example.
if shape.type == "Chart":
# Get the chart as a PNG image.
image_path = slides_api.download_shape(file_name, slide_index, shape_index, ShapeExportFormat.PNG)
print("A chart image was saved to " + image_path)
This is also a paid product, but you can make 150 free API calls per month for any purposes.
I work as a Support Developer at Aspose and can answer your questions of these libraries on Aspose.Slides forum.

Is it possible to get download URLs for each image in image collection using Earth Engine API for python?

I've seen this question asked before but seemed to be focused on exporting to GDrive, I want to export/download the images to my computer rather than google drive.
I am trying to download each image from a image collection using earth engine's python api.
Following their examples, it is easy enough to grab a single image and get the download URL:
image1 = ee.Image('CGIAR/SRTM90_V4')
path = image1.getDownloadUrl({
'scale': 30,
'crs': 'EPSG:4326',
'region': '[[-120, 35], [-119, 35], [-119, 34], [-120, 34]]'})
print(path)
This gives me a URL from which I can download the image.
Similarly for an image collection, I can get the image collection using:
collection = (ee.ImageCollection('LANDSAT/LE07/C01/T1')
.filterDate(datetime.datetime(2002, 11, 8),
datetime.datetime(2002, 11, 15)))
Is it possible to iterate through each image and get each download URL? I.e. want to grab imagery of the same area once a month or something like that without using google drive. For now I left the question simple, but will clip the image to my area and perform other manipulations as necessary before download.
I found this question here: How to iterate over and download each image in an image collection from the Google Earth Engine python api
but wasn't able to come up with a final solution...
Help would be appreciated!
You can do this:
data = images.toList(images.size());
for i in range(43): #This is the number of images in the images collection
image = ee.Image(data.get(i));
#image = image.select(["B2","B3","B4","B8","B12"])
path = image.getDownloadUrl({
'scale' : scale,
'crs' : 'EPSG:4326',
'region' : polys})
print(path)
You could check this code which I based the above code from.
It is in javascript, but the same concept
https://github.com/Yichabod/natural_disaster_pred/blob/master/image_download_script.js
. The commented out code is what you are interesed in

How to change the recognition language

Using Google vision from here I was successfully able to create a client and an image using vision.Client() and client.image(content=data) respectively. And then send my image using image.detect_text(), attempting to read the digits within the image. however Google-vision has been inaccurate and I heard, from this question, that by setting the language to another (non-latin) language would help with this.
But that is where I am stuck, I'm not sure where to set the languageHints, and yes I have seen this link to the documentation of the AnnotateImageRequest, but I am still confused as to where this comes in.
I am not an expert in this but the following seems to work for me:
First you create an image_context object, as follows:
image_context = types.ImageContext(language_hints =["en"])
Then you call text_detection with the image_context you created as parameter, as follows:
response = client.text_detection(image=image, image_context=image_context)
image_context = vision.ImageContext(language_hints =["en"])
response = client.text_detection(image=image, image_context=image_context)

Download data from Natural Earth and OpenStreetMap for Cartopy

I'm trying to use cartopy to plot several maps and I want to use them offline. Cartopy has a data directory,
import cartopy.config
cartopy.config
{'data_dir': '/home/user/.local/share/cartopy',
'downloaders': {('shapefiles',
'gshhs'): <cartopy.io.shapereader.GSHHSShpDownloader at 0x7f3ee33ee7d0>,
('shapefiles',
'natural_earth'): <cartopy.io.shapereader.NEShpDownloader at 0x7f3ee33ee710>},
'pre_existing_data_dir': '',
'repo_data_dir': '/home/user/bin/virtualenvs/mobi/local/lib/python2.7/site-packages/cartopy/data'}
So I believe that i can download the maps from Natural Earth site. How can I structure this data on this directory so cartopy would not use the internet to plot? And how can I do the same for OpenStreetMap data?
(Partial answer only)
At Natural Earth web site, http://www.naturalearthdata.com/downloads/, you can find all the downloadable files.
For example, this link provides low resolution data: http://www.naturalearthdata.com/downloads/110m-physical-vectors/
One of the data files on that page has this link address:
http://www.naturalearthdata.com/http//www.naturalearthdata.com/download/110m/physical/ne_110m_coastline.zip
This piece of code will download that file (if it is not readily available on the computer):-
import cartopy
fname = cartopy.io.shapereader.natural_earth( \
resolution='110m', \
category='physical', \
name='110m_coastline')
fname is full pathname of the downloaded file.
You dont need to arrange the download location for cartopy. It already has default location that you can find by:
cartopy.config['data_dir'] # usually 'C:\\Users\\username\\.local\\share\\cartopy'
You can check out the files you downloaded and see how they are structured in that location.
Next time when you use cartopy function cartopy.io.shapereader.natural_earth (with default config) it will use the local files if they are available.
I had Faced similar issue wherein, with cartopy, the plt.gca().coastlines() was triggering the download of a zip file from external server, but the download was failing as internet connectivity was absent.
/home/apps/CARTOPY/0.16.0/lib64/python2.7/site-packages/Cartopy-0.16.0-py2.7-linux-x86_64.egg/cartopy/io/__init__.py:260: DownloadWarning: Downloading: http://naciscdn.org/naturalearth/110m/physical/ne_110m_coastline.zip
warnings.warn('Downloading: {}'.format(url), DownloadWarning)
I manually downloaded the zip file , and extracted under - ~/.local/share/cartopy/shapefiles/natural_earth/physical.
~/.local/share/cartopy/shapefiles/natural_earth/physical> ls
ne_110m_coastline.README.html ne_110m_coastline.cpg ne_110m_coastline.prj ne_110m_coastline.shx
ne_110m_coastline.VERSION.txt ne_110m_coastline.dbf ne_110m_coastline.shp
then after renaming/removing "ne_" prefix from some files, i was able to solve this issue.
~/PLOT_TEST> ls ~/.local/share/cartopy/shapefiles/natural_earth/physical/
110m_coastline.cpg 110m_coastline.dbf 110m_coastline.prj 110m_coastline.shp 110m_coastline.shx ne_110m_coastline.README.html ne_110m_coastline.VERSION.txt
I have prepared a code in where you can download the the shapefiles from natural earth and then convert them into a dataframe. Pay attention, the country coordinates in natural earth are in polygon and multi-polygon format. In the case of dealing with Rivers which are linestring you need to modify the code.
You might need to manipulate the "name" with your desired filename like "coastlines". Find more information in the following link:
https://www.naturalearthdata.com/downloads/
import cartopy.io.shapereader as shpreader
ne_earth_countries = shpreader.natural_earth(resolution = '10m',
category = 'cultural',
name='admin_0_countries')
countries = shpreader.Reader(ne_earth_countries).records()
def extract_geom_meta(country):
coords = np.empty(shape=[0,2])
for geom in country.geometry:
coords = np.append(coords, geom.exterior.coords, axis=0)
country_name = country.attributes["ADMIN"]
return [country_name, coords]
WorldDF = pd.DataFrame([extract_geom_meta(country) for country in countries],
columns=['countries','coordinates'])
CountryDF = pd.concat([pd.DataFrame(WorldDF['coordinates'][country_idx])
for country_idx in range(len(WorldDF))]).reset_index()
CountryDF['Label'] = CountryDF.apply(lambda row: 1 if row['index'] == 0
else 0,axis=1).cumsum()-1
CountryDF['Country'] = CountryDF['Label'].apply(lambda row: WorldDF.countries[row])
CountryDF.rename(columns={0:'Longitude', 1:'Latitude'},inplace=True)
print(CountryDF.head())

Categories