Satellite imagery analysis

In this article, I propose to have a look at a casual imagery analysis. 

There are various exponential advancements in the space industry that makes access to space easier and less expensive and the various applications from traffic and crops to oil tanks monitoring and so forth. The purpose of this article is technical.

Let’s dive in: 

Satellite Imagery Analysis

Setup

  • Planet’s Python Client API
  • before installing Rasterio make sure numpy is already installed
  • Rasterio: for organizing and storing gridded raster datasets as satellite imagery (GeoTIFF, Numpy N-dimensional arrays, GeoJSON.numpy)
  • matplotlib
  • requests (you might not need to if you already have miniconda installed: ‘$ pip install requests Requirement already satisfied: requests in /miniconda3/envs/…’ )

Data Extraction

If you are a planeteer, you’ll get your data from Planet Explorer, of course, the 14 days trial.

Now, time to get the data. And I am proud to say that, at this moment in time, this is the most complete version that you will find online:

Get to your Jupyter Notebook and start typing:

from planet import api
   client = api.ClientV1()

Get your coordinates with this fast hack: at geojson.io and choose your area of interest and copy-paste your coordinates below:

# I have picked some Silicon Valley, San Francisco, CA, USA, coordinates:
    geojson_geometry = {
      "type": "Polygon",
      "coordinates": [
              [
                [
                  -122.43576049804688,
                  37.51299386065851
                ],
                [
                  -122.34786987304686,
                  37.155938651244625
                ],
                [
                  -122.07595825195312,
                  36.948794297566366
                ],
                [
                  -121.8878173828125,
                  37.18110808791507
                ],
                [
                  -122.43576049804688,
                  37.51299386065851
                ]
              ]
            ]
          }

You might want to make sure that you get the right data: setting up the time frame of clouds, by adding some filters:

# get images that overlap with our area of interest 
    geometry_filter = {
      "type": "GeometryFilter",
      "field_name": "geometry",
      "config": geojson_geometry
    }

    # get images acquired within a date range
    date_range_filter = {
      "type": "DateRangeFilter",
      "field_name": "acquired",
      "config": {
        "gte": "2018-08-31T00:00:00.000Z", 
        "lte": "2018-09-01T00:00:00.000Z"
      }
    }#or you can pick any other times, wider time-frames, though it might contain a lot more data..    # only get images which have <50% cloud coverage
    cloud_cover_filter = {
      "type": "RangeFilter",
      "field_name": "cloud_cover",
      "config": {
        "lte": 0.5
      }
    }

    # combine our geo, date, cloud filters
    combined_filter = {
      "type": "AndFilter",
      "config": [geometry_filter, date_range_filter, cloud_cover_filter]
    }

Make sure you’ve got your API key from Planet’s Account.

import os
    import json
    import requests
    from requests.auth import HTTPBasicAuth

    os.environ['PL_API_KEY']='HERE YOU INPUT YOU API Key'

    # API Key stored as an env variable
    PLANET_API_KEY = os.getenv('PL_API_KEY') 
    
    # will get a 4 band image with spectral data for Red, Green, Blue and Near-infrared values
    item_type = "PSScene4Band"

    # API request object
    search_request = {
      "interval": "day",
      "item_types": [item_type], 
      "filter": combined_filter
    }

    # fire off the POST request
    search_result = 
      requests.post(
        'https://api.planet.com/data/v1/quick-search',
        auth=HTTPBasicAuth(PLANET_API_KEY, ''),
        json=search_request)

    print(json.dumps(search_result.json(), indent=1))

To download a photo, you need to pick one and set the asset type: ‘analytic’ or ‘analytic_dn’(which is Planet old format), as well as the activation status needs to be “active”. Just have patience, it might take a few minutes (3 to 5 min).

# extract image IDs only
image_ids = [feature['id'] for feature in search_result.json()['features']]
print(image_ids)

# For demo purposes, just grab the first image ID
id0 = image_ids[0]
id0_url = 'https://api.planet.com/data/v1/item-types/{}/items/{}/assets'.format(item_type, id0)

# Returns JSON metadata for assets in this ID. Learn more: planet.com/docs/reference/data-api/items-assets/#asset
result = 
  requests.get(
    id0_url,
    auth=HTTPBasicAuth(PLANET_API_KEY, '')
  )

# List of asset types available for this particular satellite image
print(result.json().keys())

# This is "inactive" if the "analytic" asset has not yet been activated; otherwise 'active'
print(result.json()['analytic_dn']['status'])

Then activate it:

# activate the asset for download:
links = result.json()[u"analytic_dn"]["_links"]
self_link = links["_self"]
activation_link = links["activate"]

# Request activation of the 'analytic' asset:
activate_result = 
  requests.get(
    activation_link,
    auth=HTTPBasicAuth(PLANET_API_KEY, '')
  )

And while saying ‘Activating’ you can probe if ready with:

activation_status_result = 
  requests.get(
    self_link,
    auth=HTTPBasicAuth(PLANET_API_KEY, '')
  )

print(activation_status_result.json()["status"])

When ‘Active’, download it:

# Image can be downloaded by making a GET with your Planet API key, from here:
download_link = activation_status_result.json()["location"]
print(download_link)

And check your download folder. If you don’t have the right app to view a .tiff, don’t get alarmed if the image looks blank in your regular image viewer. Also make sure you have enough space on disc.

Please find the entire code here. All you’ll have to do is pick your own coordinates, instead of spending hours figuring the above.

Active data will be only from California, USA. You might find other active data (like for example Romania, though it will be available for areas bigger than 10K Square Kilometres which will turn an error message for exceeding your monthly download limit.


Data Trouble Shooting (hopefully you won’t need it):

Leave A Comment

All fields marked with an asterisk (*) are required