Introduction to Planet API
In [ ]:
import os, json, requests
from requests.auth import HTTPBasicAuth
from pprint import pprint
os.environ['PL_API_KEY'] = '7d8af35b6e944f33bb5e33ada32ab4a0'
PL_API_KEY = os.getenv('PL_API_KEY')
PL_AUTH = HTTPBasicAuth(PLANET_API_KEY, '')
# Setup Planet Data API base URL
BASE_URL = "https://api.planet.com/data/v1"
#Setup the session
session = requests.Session()
In [ ]:
roi_data = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
-118.2967472076416,
34.00578318672437
],
[
-118.22739601135252,
34.00578318672437
],
[
-118.22739601135252,
34.07846940942791
],
[
-118.2967472076416,
34.07846940942791
],
[
-118.2967472076416,
34.00578318672437
]
]
]
}
}
]
}
In [ ]:
roi_geom = roi_data['features'][0]['geometry']
In [ ]:
roi_geom
In [ ]:
# Filters to download data
In [ ]:
geom_filter = {
'type': 'GeometryFilter',
'field_name': 'geometry',
'config': roi_geom
}
date_range_filter = {
'type': 'DateRangeFilter',
'field_name': 'acquired', #meaning, captured by satellite
'config': {
"gte": "2016-03-01T00:00:00.000Z",
"lte": "2016-09-01T00:00:00.000Z"
}
}
cloud_cover_filter = {
'type':'RangeFilter',
'field_name': 'cloud_cover',
'config': {
"lte":0.1
}
}
combined_filter = {
'type': 'AndFilter',
'config': [geom_filter, date_range_filter, cloud_cover_filter]
}
Request data¶
In [ ]:
# PLANET_API_KEY = '7d8af35b6e944f33bb5e33ada32ab4a0'
ITEM_TYPE = 'PSScene4Band'
SEARCH_URL = 'https://api.planet.com/data/v1/quick-search'
ASSET_TYPE = 'analytic'
# api request object
search_request = {
'interval': 'day',
'item_types': [ITEM_TYPE],
'filter': combined_filter
}
# send the POST request
search_result = requests.post(SEARCH_URL,
auth=PL_AUTH,
json=search_request)
# print(json.dumps(search_result.json(), indent=1))
#
In [ ]:
In [ ]:
print(search_result.json().keys())
pprint(search_result.json()['_links'])
In [ ]:
features = search_result.json()['features']
print('number of images retrieved: ', len(features))
scene_ids = [features[idx]['id'] for idx in range(len(features))]
scene_links = [f['_links'] for f in features]
pprint([(scene_id, scene_link)
for (scene_id, scene_link) in zip(scene_ids[:5], scene_links[:5])])
In [ ]:
id0 = img_ids[0]
id0_url = f'https://api.planet.com/data/v1/item-types/{item_type}/items/{id0}/assets'
print('id0_url: ', id0_url)
In [ ]:
def get_asset_url(item_type,scene_id):
return f'https://api.planet.com/data/v1/item-types/{item_type}/items/{scene_id}/assets'
print(ASSET_URL(ITEM_TYPE, id0))
In [ ]:
# which assets are available for this image?
result = requests.get(
id0_url,
auth=PL_AUTH
).json()
pprint(result.keys())
Clip scenes to AOI¶
In [ ]:
#clip API request payload
CLIP_URL = 'https://api.planet.com/compute/ops/clips/v1'
clip_payload = {
'aoi': roi_geom,
'targets': [{'item_id': sid,
'item_type': ITEM_TYPE,
'asset_type': ASSET_TYPE} for sid in scene_ids[:1]
]
}
pprint(clip_payload['targets'])
In [ ]:
# Request clip operation on target scenes
clip_response = requests.post(
CLIP_URL,
auth=PL_AUTH,
json=clip_payload)
In [ ]:
result_url = clip_response
In [ ]:
check_state_request = requests.get(
clip_response.json()['_links']['_self'],
auth=PL_AUTH)
In [ ]:
if check_state_request.json()['state'] == 'succeeded':
clip_download_url = check_state_request.json()['_links']['results'][0]
In [ ]:
clip_download_url
In [ ]:
clip_download_response = requests.get(clip_download_url, stream=True)
with open('./output/temp.zip', 'wb') as w:
for data in tqdm(clip_download_response.iter_content()):
w.write(data)
In [ ]:
#unzip
zipped = zipfile.ZipFile('./output/temp.zip')
zipped.extractall('./output/temp')
In [ ]:
!ls output
!unzip output/temp.zip
Activation and Downloading¶
In [ ]:
def activate(scene_ids, item_links,
item_type=ITEM_TYPE, asset_type=ASSET_TYPE):
for scene_id in scene_ids:
head_asset_url = get_asset_url(item_type, scene_id)
asset_response = responses.get
In [ ]:
#is this image's analytic asset already activated?
print(result['analytic'].keys())
print(result['analytic']['status'])
In [ ]:
# let's activate this asset for download
# some useful links
links = result['analytic']['_links'];print(links)
self_link = links['_self']
activation_link = links['activate']
In [ ]:
# request the activation of this asset
activate_result = requests.get(
activation_link,
auth=PL_AUTH
)
In [ ]:
# check if the asset is activated
activation_status_result = requests.get(
self_link,
auth=PL_AUTH
)
In [ ]:
activation_status_result = activation_status_result.json()
In [ ]:
pprint(activation_status_result)
In [ ]:
# download link
dlink = activation_status_result['location']
print('download link: \n', dlink)
In [ ]:
dlink_response = requests.get(
dlink, stream=True)
In [ ]:
import zipfile
from tqdm import tqdm
In [ ]:
# scene_id = '20160715_174333_0e0e'
scene_id = 'sample'
outname = f'./output/{scene_id}.zip'
with open(outname, 'wb') as w:
for data in tqdm(dlink_response.iter_content()):
w.write(data)
In [ ]:
dlink_result.json()
View downloaded image using rasterio¶
In [ ]:
import rasterio as rio
from rasterio.plot import reshape_as_image, reshape_as_raster
import matplotlib.pyplot as plt
%matplotlib inline
import pdb
In [ ]:
fname = './images/20160731_174506_0e30_3B_AnalyticMS.tif'
img = None
with rio.open(fname, 'r') as ds:
# pdb.set_trace()
b,g,r,n = ds.read()
img = np.dstack([r,g,b])
# img = reshape_as_image(ds.read())
plt.imshow(img)
In [ ]:
f,ax = plt.subplots(3,1,figsize=(20,20))
ax = ax.flatten()
for i,cimg in enumerate([r,g,b]):
ax[i].hist(np.histogram(cimg))
In [ ]:
temp = np.dstack([b,g]); print(temp.shape)