Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
calculate toa reflectance for Planet Labs data - not an ideal script, but you get the idea
import os
import argparse
from bs4 import BeautifulSoup
import rasterio
SUFFIX = '_BGRN_Analytic'
BASEPATH = '/Users/robinkraft/gitlab/change/hackathon/robin/data/'
def parse_xml(path):
xml = open(path, 'r').read()
soup = BeautifulSoup(xml, 'lxml')
return soup
def get_coefs(soup):
raw_coefs = soup.find_all('ps:reflectancecoefficient')
coefs = {}
for i in range(len(raw_coefs)):
idx = i + 1
coefs[idx] = float(raw_coefs[i].get_text('ps:reflectancecoefficient'))
return coefs
def convert2ref(band, band_num, coefs):
coef = coefs[band_num]
return band * coef
def rad2ref(img, coefs):
bands = {}
for i in range(img.count):
band_num = i + 1
band = img.read(band_num)
bands[band_num] = convert2ref(band, band_num, coefs)
return bands
def gen_paths(img_id, suffix, basepath):
xml_path = '{}{}_metadata.xml'.format(img_id, suffix)
xml_path = os.path.join(basepath, xml_path)
src_path = '{}{}.tif'.format(img_id, suffix)
src_path = os.path.join(basepath, src_path)
out_path = '{}{}_reflectance.tif'.format(img_id, suffix)
src_path = os.path.join(basepath, src_path)
return dict(xml=xml_path, src=src_path, out=out_path)
def save_ref(src, out_path, coefs):
kwargs = src.meta
# Update kwargs (change in data type)
kwargs.update(
dtype=rasterio.float32,
count = src.count)
bands = rad2ref(src, coefs)
with rasterio.open(out_path, 'w', **kwargs) as dst:
for b in bands.keys():
dst.write_band(b, bands[b].astype(rasterio.float32))
pass
def main(img_id):
paths = gen_paths(img_id, SUFFIX, BASEPATH)
soup = parse_xml(paths['xml'])
coefs = get_coefs(soup)
src = rasterio.open(paths['src'])
save_ref(src, paths['out'], coefs)
return
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--id', help='Image id for the image to be processed')
args = parser.parse_args()
main(args.id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment