diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..261eeb9
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/README.md b/README.md
index 9d91139..50dd9b5 100644
--- a/README.md
+++ b/README.md
@@ -3,7 +3,7 @@
An Instance Segmentation model to classify different landcover classes using raw satellite imagery.
-### Datasets
+## Datasets
Input: of Landsat 8 images Level 2 collection 2 using https://earthexplorer.usgs.gov/ web interface. \
The Multi-spectral Image consists of Blue, Green, Red, NIR, SWIR 1 and SWIR 2 corresponding to bands numbers (2, 3, 4, 5, 6, 7), respectively.
@@ -27,19 +27,78 @@ The following classes were included in label data:
- mixedwood
-### Preprocessing
+## Preprocessing
The preparation of the train data consists of extracting pairs of input und output of the train and label data. This requires the datasets to be projected in the same spatial reference. Therefore, the landsat images were reprojected to match the same spatial reference of landcover dataset. After Datasets-registration patches with fixed size were extracted to prepare the train and label data.
-### Training
+## Training
The model has u-net architecture consisting of 5 convolution and deconvolution layers. The model is trained to classify 4 different classes (water, herbs, coniferous and other) using the dice coefficient to evaluate accuracy.
The model has reached total accuracy of 89% after learning for 120 epochs.
-### Testing or using the model
+## Testing or using the model
-After the model loads the weights it can estimate raw bands images of landsat 8 using ```model.estimate_raw_landsat(path)``` as demonstrated in test.py. \
+After the model loads the weights it can estimate raw bands images of landsat 8 using ```model.estimate_raw_landsat(input_landsat_bands_normalized, visual_light_reflectance_mask, metadata)``` as demonstrated in test.py. \
The raw landsat bands should be in one folder named as their originial _Landsat Product Identifier L2_ followed by the SR\_B.TIF (e.g. LC08\_L2SP\_196024\_20210330\_20210409\_02\_T1\_SR\_B4.TIF is band 4 of the landsat product LC08\_L2SP\_196024\_20210330\_20210409\_02\_T1)
The result ```classified_landcover.tiff``` is saved as a geo-referenced one-band GeoTiff in the same folder.
+
+## OGC API Processes
+
+A pygeoapi processor is implemented in `api_processes/landcover_prediction.py`.
+
+We recommend using the asynchronous mode because of the runtime of the according prediction jobs.
+Hence, the pygeoapi configuration requires two adjustments.
+One to add the processor and another one for adding a job manager.
+Atm, we are using the provided TinyDB based one.
+
+First, we add the job manager:
+
+```yaml
+server:
+ manager:
+ name: TinyDB
+ connection: /tmp/pygeoapi-process-manager.db
+ output_dir: /tmp/
+```
+
+Use the following section to add the landsat prediction processor:
+
+```yaml
+resources:
+ landcover-prediction:
+ type: process
+ processor:
+ name: landsatpredictor.LandcoverPredictionProcessor
+```
+
+### Testing
+
+You can use the simple default configuration in `tests/config.yml` for local testing.
+
+1. It is recommended to install the latest pygeoapi version in your development venv:
+
+ ```shell
+ pip install https://github.com/geopython/pygeoapi/archive/master.zip
+ ```
+
+1. Afterwards, install this package as `editable`:
+
+ ```shell
+ pip install --editable .
+ ```
+
+1. Start a pygeoapi instance using this configuration:
+
+ ```shell
+ PYGEOAPI_CONFIG=./tests/config.yml pygeoapi serve
+ ```
+
+1. Execute an example prediction:
+
+ ```shell
+ curl -X POST "http://localhost:5000/processes/landcover-prediction/execution" \
+ -H "Content-Type: application/json" \
+ -d "{\"mode\": \"async\", \"inputs\":{\"landsat-collection-id\": \"landsat8_c2_l2\", \"bbox\": \"-111.0,64.99,-110.99,65.0\"}}"
+ ```
diff --git a/api_processes/landcover_prediction.py b/api_processes/landcover_prediction.py
deleted file mode 100644
index eeae99a..0000000
--- a/api_processes/landcover_prediction.py
+++ /dev/null
@@ -1,128 +0,0 @@
-# =================================================================
-# Copyright (C) 2021-2021 52°North Spatial Information Research GmbH
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-# http://www.apache.org/licenses/LICENSE-2.0
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-# =================================================================
-
-import logging
-
-from pygeoapi.process.base import (BaseProcessor, ProcessorExecuteError)
-
-LOGGER = logging.getLogger(__name__)
-
-
-# Process inputs: http://docs.ogc.org/DRAFTS/18-062.html#sc_process_inputs
-# Bbox: http://docs.ogc.org/DRAFTS/18-062.html#bbox-schema
-
-PROCESS_METADATA = {
- 'version': '0.1.0',
- 'id': 'landcover-prediction',
- 'title': 'Landcover prediction',
- 'description': 'Landcover prediction with landsat',
- 'keywords': ['landcover prediction', 'landsat', 'tb-17'],
- 'links': [{
- 'type': 'text/html',
- 'rel': 'canonical',
- 'title': 'information',
- 'href': 'https://github.com/geopython/pygeoapi/blob/master/pygeoapi/process/hello_world.py',
- 'hreflang': 'en-US'
- }],
- 'inputs': {
- 'landsat-collection-id': {
- 'title': 'Name',
- 'description': 'Landsat coverage collection id',
- 'schema': {
- 'type': 'string'
- },
- 'minOccurs': 1,
- 'maxOccurs': 1,
- 'metadata': None, # TODO how to use?
- 'keywords': ['landsat']
- },
- 'bbox': {
- 'title': 'Spatial bounding box',
- 'description': 'Spatial bounding box in WGS84',
- 'schema': {
- 'type': 'string'
- },
- 'minOccurs': 1,
- 'maxOccurs': 1,
- 'metadata': None,
- 'keywords': ['bbox']
- }
- },
- 'outputs': {
- 'echo': {
- 'title': 'Landcover prediction',
- 'description': 'Landcover prediction with Landsat 8 Collection 2 Level 2 for water, herbs and coniferous',
- 'schema': {
- 'type': 'object',
- 'contentMediaType': 'application/json'
- }
- }
- },
- 'example': {
- "inputs": {
- "landsat-collection-id": "landsat8_c2_l2",
- "bbox": "1,2,1,2"
- }
- }
-}
-
-
-class LandcoverPredictionProcessor(BaseProcessor):
- """Landcover Prediction Processor"""
-
- def __init__(self, processor_def):
- """
- Initialize object
-
- :param processor_def: provider definition
-
- :returns: odcprovider.processes.LandcoverPredictionProcessor
- """
-
- super().__init__(processor_def, PROCESS_METADATA)
-
- def execute(self, data):
-
- mimetype = 'application/json'
- collection_id = data.get('landsat-collection-id', None)
- bbox = data.get('bbox', '')
-
- if collection_id is None:
- raise ProcessorExecuteError('Cannot process without a collection_id')
- if bbox is None:
- raise ProcessorExecuteError('Cannot process without a bbox')
-
- LOGGER.debug('Process inputs:\n - collection_id: {}\n - bbox: {}'.format(collection_id, bbox))
- LOGGER.debug(type(bbox))
-
- # Implementation steps:
- # 1) Parse process inputs
- # 2) Get array to use for the prediction with the correct bbox
- # a) either using open data cube directly or
- # b) making a coverage request (may be slower but enables usage of external collections)
- # 3) If necessary adapt this function https://github.com/SufianZa/Landsat-classification/blob/main/u_net.py#L208 to use, e.g., array input instead of path
- # 4) Make the prediction using this method https://github.com/SufianZa/Landsat-classification/blob/main/test.py
- # 5) Correctly encode the result of 4) as process output (geotiff)
-
- outputs = [{
- 'id': 'echo',
- 'collection_id': collection_id,
- 'bbox': bbox
- }]
-
- return mimetype, outputs
-
- def __repr__(self):
- return ' {}'.format(self.name)
diff --git a/config.py b/config.py
deleted file mode 100644
index 51b1c44..0000000
--- a/config.py
+++ /dev/null
@@ -1,37 +0,0 @@
-from matplotlib import patches, pyplot as plt
-
-selected_classes = ['no_change', 'water', 'coniferous', 'herbs']
-
-original_classes = dict(no_change=0,
- water=20,
- snow_ice=31,
- rock_rubble=32,
- exposed_barren_land=33,
- bryoids=40,
- shrubland=50,
- wetland=80,
- wetlandtreed=81,
- herbs=100,
- coniferous=210,
- broadleaf=220,
- mixedwood=230)
-
-
-if len(selected_classes) == 0:
- selected_classes = list(original_classes.keys())
-model_classes = {c: idx for idx, c in enumerate(original_classes) if c in selected_classes}
-
-colors = [(0, 0, 0)] + list(plt.cm.get_cmap('Paired').colors)
-colors_legend = [patches.Patch(color=colors[i], label=c) for i, c in enumerate(original_classes) if
- c in selected_classes]
-colors = [colors[i] for i, c in enumerate(original_classes) if c in selected_classes]
-
-REFLECTANCE_MAX_BAND = 65535
-PADDING_EDGE = 100
-
-# folder s
-LAND_COVER_FILE = "./CA_forest_VLCE_2015/CA_forest_VLCE_2015.tif"
-TRAIN_DATASETS = 'train'
-TEST_DATASETS = 'test'
-
-SUPPORTED_BANDS = [2, 3, 4, 5, 6, 7]
diff --git a/3_class_best_weight.hdf5 b/data/3_class_best_weight.hdf5
similarity index 100%
rename from 3_class_best_weight.hdf5
rename to data/3_class_best_weight.hdf5
diff --git a/best_weight.hdf5 b/data/best_weight.hdf5
similarity index 100%
rename from best_weight.hdf5
rename to data/best_weight.hdf5
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 0000000..9787c3b
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,3 @@
+[build-system]
+requires = ["setuptools", "wheel"]
+build-backend = "setuptools.build_meta"
diff --git a/requirements.txt b/requirements.txt
index 2c833d6..c0c94d8 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,9 +1,12 @@
+landsatxplore
matplotlib
-numpy
+numpy~=1.19.2
opencv-python
Pillow
-tensorflow
-scikit-image
+pygeoapi
rasterio
requests
-scikit-learn
\ No newline at end of file
+scikit-image
+scikit-learn
+tensorflow~=2.6.0
+tinydb
diff --git a/setup.py b/setup.py
new file mode 100644
index 0000000..30a42e9
--- /dev/null
+++ b/setup.py
@@ -0,0 +1,49 @@
+# =================================================================
+# Copyright (C) 2021-2021 52°North Spatial Information Research GmbH
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# https://docs.python.org/3/distutils/setupscript.html
+#
+# =================================================================
+
+from setuptools import setup, find_packages
+
+
+def parse_requirements(filename):
+ """ load requirements from a pip requirements file """
+ lineiter = (line.strip() for line in open(filename))
+ return [line for line in lineiter if line and not line.startswith("#")]
+
+
+# loading requirements
+requirements = list(parse_requirements('requirements.txt'))
+
+setup(
+ name="landsatpredictor",
+ packages=find_packages(where='src'),
+ package_dir={'': 'src'},
+ version="0.1.0",
+ description="pygeoapi processor plugin for Landsat land cover classification",
+ long_description="landsat ML model for land cover classification",
+ long_description_content_type="text/markdown",
+ license="Apache License, Version 2.0",
+ url="https://github.com/52North/Landsat-classification",
+ keywords=["Landsat", "pygeoapi", "EO", "Landsat Level 2 Collection 2", "machine learning"],
+ install_requires=requirements,
+ test_suite="tests",
+ classifiers=[
+ 'Development Status :: 3 - Alpha',
+ 'License :: OSI Approved :: Apache License, Version 2.0',
+ 'Programming Language :: Python :: 3',
+ 'Programming Language :: Python :: 3.9',
+ ]
+)
diff --git a/src/landsatpredictor/__init__.py b/src/landsatpredictor/__init__.py
new file mode 100644
index 0000000..cc23264
--- /dev/null
+++ b/src/landsatpredictor/__init__.py
@@ -0,0 +1,15 @@
+# =================================================================
+# Copyright (C) 2021-2021 52°North Spatial Information Research GmbH
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# =================================================================
+from .pygeoapi_processor import LandcoverPredictionProcessor
diff --git a/src/landsatpredictor/config.py b/src/landsatpredictor/config.py
new file mode 100644
index 0000000..0ed31ac
--- /dev/null
+++ b/src/landsatpredictor/config.py
@@ -0,0 +1,86 @@
+# =================================================================
+# Copyright (C) 2021-2021 52°North Spatial Information Research GmbH
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# =================================================================
+from matplotlib import patches, pyplot as plt
+
+selected_classes = ['no_change', 'water', 'coniferous', 'herbs']
+
+original_classes = dict(no_change=0,
+ water=20,
+ snow_ice=31,
+ rock_rubble=32,
+ exposed_barren_land=33,
+ bryoids=40,
+ shrubland=50,
+ wetland=80,
+ wetlandtreed=81,
+ herbs=100,
+ coniferous=210,
+ broadleaf=220,
+ mixedwood=230)
+
+
+if len(selected_classes) == 0:
+ selected_classes = list(original_classes.keys())
+model_classes = {c: idx for idx, c in enumerate(original_classes) if c in selected_classes}
+
+colors = [(0, 0, 0)] + list(plt.cm.get_cmap('Paired').colors)
+colors_legend = [patches.Patch(color=colors[i], label=c) for i, c in enumerate(original_classes) if
+ c in selected_classes]
+colors = [colors[i] for i, c in enumerate(original_classes) if c in selected_classes]
+
+LANDSAT8_REFLECTANCE_BAND_MAX_VALUE = 65455
+"""
+Max value for Landsat 8 reflectance bands. See values for surface reflectance.
+
+See https://www.usgs.gov/core-science-systems/nli/landsat/landsat-collection-2-level-2-science-products
+"""
+
+PADDING_EDGE = 100
+
+# folder s
+LAND_COVER_FILE = "./CA_forest_VLCE_2015/CA_forest_VLCE_2015.tif"
+TRAIN_DATASETS = 'train'
+TEST_DATASETS = 'test'
+
+REQUIRED_LANDSAT8_BAND_INDICES = [1, 2, 3, 4, 5, 6]
+"""
+Landsat 8 Level 2 bands for the prediction:
+B2 -> blue
+B3 -> green
+B4 -> red
+B5 -> near infrared
+B6 -> Short Wave Infrared 1
+B7 -> Short Wave Infrared 2
+
+Definition
+See https://www.usgs.gov/faqs/what-are-band-designations-landsat-satellites
+
+Usage
+See https://www.usgs.gov/media/images/common-landsat-band-rgb-composites
+"""
+
+VISUAL_LIGHT_BANDS = [1, 2, 3]
+"""
+Indices of bands in visual light spectrum, e.g. Red, Green, Blue.
+
+For Landsat 8 Collection 2 Level 2: 2 -> blue, 3 -> green, 4 -> red
+
+For Coverages within TB17; 1 -> blue, 2 -> green, 3 -> red
+"""
+
+REQUIRED_BAND_COUNT = 6
+"""
+The prediction model requires 6 bands. More or less MUST cause an ValueError
+"""
\ No newline at end of file
diff --git a/src/landsatpredictor/downloader/__init__.py b/src/landsatpredictor/downloader/__init__.py
new file mode 100644
index 0000000..2f0488f
--- /dev/null
+++ b/src/landsatpredictor/downloader/__init__.py
@@ -0,0 +1,14 @@
+# =================================================================
+# Copyright (C) 2021-2021 52°North Spatial Information Research GmbH
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# =================================================================
diff --git a/downloader/download_datasets.py b/src/landsatpredictor/downloader/download_datasets.py
similarity index 64%
rename from downloader/download_datasets.py
rename to src/landsatpredictor/downloader/download_datasets.py
index 1ca6367..61e6fca 100644
--- a/downloader/download_datasets.py
+++ b/src/landsatpredictor/downloader/download_datasets.py
@@ -1,10 +1,24 @@
+# =================================================================
+# Copyright (C) 2021-2021 52°North Spatial Information Research GmbH
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# =================================================================
+import os
from pathlib import Path
+import requests
from landsatxplore.api import API
from landsatxplore.earthexplorer import EarthExplorer
-import os
from tqdm import tqdm
-import requests
# download land cover dataset
land_cover_url = 'https://opendata.nfis.org/downloads/forest_change/CA_forest_VLCE_2015.zip'
diff --git a/src/landsatpredictor/preprocessing/__init__.py b/src/landsatpredictor/preprocessing/__init__.py
new file mode 100644
index 0000000..2f0488f
--- /dev/null
+++ b/src/landsatpredictor/preprocessing/__init__.py
@@ -0,0 +1,14 @@
+# =================================================================
+# Copyright (C) 2021-2021 52°North Spatial Information Research GmbH
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# =================================================================
diff --git a/preprocessing/image_registration.py b/src/landsatpredictor/preprocessing/image_registration.py
similarity index 68%
rename from preprocessing/image_registration.py
rename to src/landsatpredictor/preprocessing/image_registration.py
index 4587c1f..0a506a9 100644
--- a/preprocessing/image_registration.py
+++ b/src/landsatpredictor/preprocessing/image_registration.py
@@ -1,16 +1,32 @@
+# =================================================================
+# Copyright (C) 2021-2021 52°North Spatial Information Research GmbH
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# =================================================================
+import re
+from os import walk
+from pathlib import Path
+
+import cv2 as cv
import matplotlib.pyplot as plt
-from rasterio.windows import from_bounds
import numpy as np
-import cv2 as cv
-from pathlib import Path
import rasterio
from rasterio.enums import Resampling
from rasterio.warp import calculate_default_transform, reproject
+from rasterio.windows import from_bounds
from skimage.exposure import equalize_hist
-from os import walk
-import re
-from config import LAND_COVER_FILE, SUPPORTED_BANDS, REFLECTANCE_MAX_BAND, PADDING_EDGE
+from ..config import LAND_COVER_FILE, REQUIRED_LANDSAT8_BAND_INDICES, LANDSAT8_REFLECTANCE_BAND_MAX_VALUE, \
+ PADDING_EDGE, VISUAL_LIGHT_BANDS, REQUIRED_BAND_COUNT
def merge_reprojected_bands(datasets_folder):
@@ -41,7 +57,7 @@ def merge_reprojected_bands(datasets_folder):
})
with rasterio.open(Path(datasets_folder, '%s.tif' % dataset), 'w', **kwargs) as dst:
print('Reprojecting bands of %s' % dataset)
- for i, b in enumerate(SUPPORTED_BANDS, start=1):
+ for i, b in enumerate(REQUIRED_LANDSAT8_BAND_INDICES, start=1):
with rasterio.open(Path(files + '%d' % b).with_suffix('.TIF')) as band:
reproject(
source=rasterio.band(band, 1),
@@ -60,11 +76,11 @@ def rotate_datasets(landsat_dataset_path, enhance_colors=False, show_preprocessi
bands = []
masks = []
# collect and normalize spectral bands
- for band_num in SUPPORTED_BANDS:
+ for band_num in REQUIRED_LANDSAT8_BAND_INDICES:
band = l_sat.read(band_num)
- if band_num in [2, 3, 4]:
+ if band_num in VISUAL_LIGHT_BANDS:
masks.append(band != 0)
- band = band / REFLECTANCE_MAX_BAND
+ band = band / LANDSAT8_REFLECTANCE_BAND_MAX_VALUE
bands.append(band)
# stacking Multi-spectral image containing -> (Blue, Green, Red, NIR, SWIR 1, SWIR 2)
@@ -155,25 +171,41 @@ def rotate_datasets(landsat_dataset_path, enhance_colors=False, show_preprocessi
return ls_cropped, lc_cropped
-def getMultiSpectral(landsat_dataset_path):
- with rasterio.open(landsat_dataset_path) as l_sat:
- bands = []
- masks = []
- metadata = l_sat.meta.copy()
- metadata.update({'count': 1})
- # collect and normalize spectral bands
- for band_num in SUPPORTED_BANDS:
- band = l_sat.read(band_num)
- if band_num in [2, 3, 4]:
- masks.append(band != 0)
- band = band / REFLECTANCE_MAX_BAND
- bands.append(band)
-
- # stacking Multi-spectral image containing -> (Blue, Green, Red, NIR, SWIR 1, SWIR 2)
- ls_original = np.array(bands).transpose([1, 2, 0])
-
- # extract mask from the bands
- mask = np.mean(np.array(masks).transpose([1, 2, 0]), axis=2)
- mask[mask > 0] = 1
- mask[mask <= 0] = 0
- return ls_original, mask, metadata
+def get_multi_spectral(dataset):
+
+ # ToDo: refactor into three separate functions for each return value?
+ if dataset.count != REQUIRED_BAND_COUNT:
+ raise ValueError('Number of bands != {}: {}'.format(REQUIRED_BAND_COUNT, dataset.count))
+ bands = []
+ masks = []
+ metadata = dataset.meta.copy()
+ # Why do we set the band count to 1?
+ # Because it is used for the final result that contains only one band -> should be moved to a better location
+ metadata.update({'count': 1})
+ # collect and normalize spectral bands
+ for band_num in REQUIRED_LANDSAT8_BAND_INDICES:
+ band = dataset.read(band_num)
+ # for visual light bands (landsat 8 bands: 2 -> blue, 3 -> green, 4 -> red
+ # for coverages result: 1 -> blue, 2 -> green, 3 -> red
+ # ToDo potentially skip this when using numpy masked arrays
+ if band_num in VISUAL_LIGHT_BANDS:
+ # add binary no data mask
+ masks.append(band != 0)
+ # normalize band values to 0..1
+ band = _normalize_landsat_band(band)
+ bands.append(band)
+
+ # stacking Multi-spectral image containing -> (Blue, Green, Red, NIR, SWIR 1, SWIR 2)
+ landsat_bands_normalized = np.array(bands).transpose([1, 2, 0])
+
+ # ToDo potentially skip this when using numpy masked arrays
+ # combine visual reflectance masks: one band with reflectance per pixel is enough for true
+ mask = np.mean(np.array(masks), axis=0)
+ mask[mask > 0] = 1
+ mask[mask <= 0] = 0
+
+ return landsat_bands_normalized, mask, metadata
+
+
+def _normalize_landsat_band(band):
+ return band / LANDSAT8_REFLECTANCE_BAND_MAX_VALUE
diff --git a/preprocessing/patches_generator.py b/src/landsatpredictor/preprocessing/patches_generator.py
similarity index 82%
rename from preprocessing/patches_generator.py
rename to src/landsatpredictor/preprocessing/patches_generator.py
index 7d6618f..4a2342d 100644
--- a/preprocessing/patches_generator.py
+++ b/src/landsatpredictor/preprocessing/patches_generator.py
@@ -1,7 +1,22 @@
-from pathlib import Path
-from PIL import Image
+# =================================================================
+# Copyright (C) 2021-2021 52°North Spatial Information Research GmbH
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# =================================================================
import os
+from pathlib import Path
+
import numpy as np
+from PIL import Image
from sklearn.model_selection import train_test_split
original_classes = dict(no_change=0,
diff --git a/preprocessing/run.py b/src/landsatpredictor/preprocessing/run.py
similarity index 53%
rename from preprocessing/run.py
rename to src/landsatpredictor/preprocessing/run.py
index 214c6e7..91a5dce 100644
--- a/preprocessing/run.py
+++ b/src/landsatpredictor/preprocessing/run.py
@@ -1,7 +1,22 @@
+# =================================================================
+# Copyright (C) 2021-2021 52°North Spatial Information Research GmbH
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# =================================================================
from pathlib import Path
-from config import selected_classes, TRAIN_DATASETS, TEST_DATASETS
-from patches_generator import generate_patches
+
from image_registration import merge_reprojected_bands, rotate_datasets
+from patches_generator import generate_patches
+from ..config import selected_classes, TRAIN_DATASETS, TEST_DATASETS
# reproject each dataset then obtain a list of paths
reprojected_train_datasets = merge_reprojected_bands(TRAIN_DATASETS)
diff --git a/src/landsatpredictor/preprocessing/stack_single_band_geotiff.py b/src/landsatpredictor/preprocessing/stack_single_band_geotiff.py
new file mode 100644
index 0000000..ed538fc
--- /dev/null
+++ b/src/landsatpredictor/preprocessing/stack_single_band_geotiff.py
@@ -0,0 +1,13 @@
+from pathlib import Path
+
+import rasterio
+
+path = "../../data/LC08_L2SP_035024_20150813_20200909_02_T1"
+multi_image = [rasterio.open(band_path) for band_path in sorted(list(Path(path).glob('*SR_B[2-7].TIF')))]
+
+meta = multi_image[0].meta.copy()
+meta.update(count=7)
+with rasterio.open(Path(path, 'LC08_L2SP_035024_20150813_20200909_02_T1_merged_1-7.tif'), 'w', **meta) as dst:
+ for i, band in enumerate(multi_image, start=2):
+ dst.write(band.read(1), i)
+ band.close()
diff --git a/src/landsatpredictor/pygeoapi_processor.py b/src/landsatpredictor/pygeoapi_processor.py
new file mode 100644
index 0000000..83a9749
--- /dev/null
+++ b/src/landsatpredictor/pygeoapi_processor.py
@@ -0,0 +1,333 @@
+# =================================================================
+# Copyright (C) 2021-2021 52°North Spatial Information Research GmbH
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# =================================================================
+from __future__ import annotations
+
+import json
+import logging
+import os
+
+import time
+from typing import Tuple, Any
+import rasterio
+from rasterio.io import MemoryFile
+from pathlib import Path
+from urllib.error import HTTPError
+
+import requests
+from .u_net import UNET
+from .preprocessing.image_registration import get_multi_spectral
+from pygeoapi.process.base import (BaseProcessor, ProcessorExecuteError)
+
+BASE_URL = "https://17.testbed.dev.52north.org/geodatacube/collections/{}/coverage?f=NetCDF&bbox={}"
+GEOTIFF_MIME_TYPES = ['application/geotiff', 'image/tiff;application=geotiff','image/geo+tiff']
+
+LOGGER = logging.getLogger(__name__)
+
+#
+# LINKS
+#
+# Process inputs
+# https://github.com/opengeospatial/ogcapi-processes/blob/master/core/examples/json/ProcessDescription.json#L14
+# http://docs.ogc.org/DRAFTS/18-062.html#sc_process_inputs
+# Bbox:
+# http://docs.ogc.org/DRAFTS/18-062.html#bbox-schema
+# https://github.com/opengeospatial/ogcapi-coverages#query-parameters-optional-conformance-classes
+#
+# Process outputs
+# https://github.com/opengeospatial/ogcapi-processes/blob/master/core/examples/json/ProcessDescription.json#L199
+# Image
+# https://github.com/opengeospatial/ogcapi-processes/blob/master/core/examples/json/ProcessDescription.json#L318-L325
+#
+# Implementation
+# Async processing pygeoapi:
+# https://docs.pygeoapi.io/en/latest/data-publishing/ogcapi-processes.html#asynchronous-support
+#
+PROCESS_METADATA = {
+ 'version': '0.1.0',
+ 'id': 'landcover-prediction',
+ 'title': 'Land cover prediction',
+ 'description': 'Land cover prediction with Landsat 8',
+ 'keywords': ['land cover prediction', 'landsat 8', 'tb-17'],
+ 'jobControlOptions': 'async-execute',
+ 'outputTransmission': ['value'],
+ 'links': [
+ {
+ 'type': 'text/html',
+ 'rel': 'canonical',
+ 'title': 'Processor Repository',
+ 'href': 'https://github.com/52North/Landsat-classification/blob/main/README.md',
+ 'hreflang': 'en-US'
+ },
+ {
+ 'type': 'text/html',
+ 'rel': 'canonical',
+ 'title': 'Landsat 8 Collection 2 Level 2',
+ 'href': 'https://www.usgs.gov/core-science-systems/nli/landsat/landsat-collection-2-level-2-science-products',
+ 'hreflang': 'en-US'
+ }
+ ],
+ 'inputs': {
+ 'collection': {
+ 'title': 'Coverage collection',
+ 'description': 'url of the OGC API Coverages collection providing the Landsat 8 Collection 2 '
+ 'Level 2 data (must start with http or https and include the following bands:'
+ ' blue, green, red, nir, swir1, swir2)',
+ 'schema': {
+ 'oneOf': [
+ {
+ 'type': 'string',
+ },
+ {
+ 'type': 'string',
+ 'contentEncoding': 'binary',
+ 'contentMediaType': 'image/tiff; application=geotiff'
+ }
+ ]
+ },
+ 'minOccurs': 1,
+ 'maxOccurs': 1,
+ # TODO how to use?
+ 'metadata': None,
+ 'keywords': ['landsat']
+ },
+ 'bbox': {
+ 'title': 'Spatial bounding box',
+ 'description': 'Spatial bounding box in WGS84',
+ 'schema': {
+ "allOf": [
+ {'format': 'ogc-bbox'},
+ {'$ref': 'https://raw.githubusercontent.com/opengeospatial/ogcapi-processes/master/core/openapi/schemas/bbox.yaml'}
+ ],
+ 'default': {'bbox': [-104.6, 51.8, -103.7, 52.6], 'crs': 'http://www.opengis.net/def/crs/OGC/1.3/CRS84'}
+ },
+ 'minOccurs': 0,
+ 'maxOccurs': 1,
+ 'metadata': None,
+ 'keywords': ['bbox']
+ },
+ 'bands': {
+ 'title': 'Bands',
+ 'description': 'Landsat 8 bands (comma-separated list, e.g. "blue, green, red, nir, swir1, swir2")',
+ 'schema': {
+ 'type': 'string'
+ },
+ 'minOccurs': 0,
+ 'maxOccurs': 1,
+ 'metadata': None,
+ 'keywords': ['bands']
+ },
+ },
+ 'outputs': {
+ 'prediction': {
+ 'title': 'Land cover prediction',
+ 'description':
+ 'Land cover prediction with Landsat 8 Collection 2 Level 2 for no change (=1), '
+ 'water (=2), coniferous (=3) and herbs (=4) (no data=0)',
+ 'schema': {
+ 'type': 'string',
+ 'format': 'byte',
+ 'contentMediaType': 'image/tiff; application=geotiff'
+ }
+ }
+ },
+ 'example': {
+ 'inputs': {
+ 'collection': {
+ 'collection': 'https://17.testbed.dev.52north.org/geodatacube/collections/landsat8_c2_l2'
+ },
+ 'bbox': {
+ 'bbox': [-104.6, 51.8, -103.7, 52.6],
+ 'crs': 'http://www.opengis.net/def/crs/OGC/1.3/CRS84'
+ }
+ },
+ # pygeoapi uses mode: async
+ 'jobControlOptions': ['async-execute'],
+ 'outputTransmission': ['value'],
+ 'response': 'raw'
+ }
+}
+
+
+class ModelCache:
+ """
+ Stores not changing trained model to be used by each instance of the LandcoverPredictionProcessor.
+ Implementation follows:
+
+ https://python-patterns.guide/gang-of-four/singleton/
+ """
+
+ _instance = None
+
+ def __init__(self):
+ raise RuntimeError('Call instance() instead')
+
+ @classmethod
+ def instance(cls) -> ModelCache:
+ LOGGER.debug("instance() called")
+ #
+ # Init model and its data as global pickled singleton
+ #
+ if cls._instance is None:
+ LOGGER.debug("Creating instance of class '{}'...".format(UNET))
+ cls._instance = UNET()
+ LOGGER.debug('...DONE.')
+ else:
+ LOGGER.debug("Instance of class '{}' already existing".format(UNET))
+ return cls._instance
+
+
+class LandcoverPredictionProcessor(BaseProcessor):
+ """Landcover Prediction Processor"""
+
+ def __init__(self, processor_def):
+ """
+ Initialize object
+
+ :param processor_def: provider definition
+
+ :returns: odcprovider.processes.LandcoverPredictionProcessor
+ """
+
+ super().__init__(processor_def, PROCESS_METADATA)
+ self.model = ModelCache.instance()
+
+ def execute(self, data: dict) -> Tuple[str, Any]:
+
+ bbox, collection, bands = self._parse_inputs(data)
+ input_landsat_bands_normalized, visual_light_reflectance_mask, metadata = self._process_collection(collection, bbox, bands)
+
+ LOGGER.debug('Requesting prediction for "{}"'.format(collection))
+ result_file_path = self.model.estimate_raw_landsat(input_landsat_bands_normalized, visual_light_reflectance_mask, metadata, trim=20)
+ LOGGER.debug('Prediction received. Result in "{}"'.format(result_file_path))
+
+ mimetype = 'image/tiff; application=geotiff'
+ with open(result_file_path, 'r+b') as file:
+ return mimetype, file.read()
+
+ def _parse_inputs(self, data):
+ LOGGER.debug("RAW Inputs:\n{}".format(json.dumps(data, indent=4)))
+ # ToDo: add support for base64-encoded geotiffs
+ collection_input = data.get('collection', None)
+ bbox_input = data.get('bbox', None)
+ bands = data.get('bands', None)
+ if collection_input is None:
+ raise ProcessorExecuteError('Cannot process without a collection')
+ else:
+ collection = collection_input.get('collection')
+ if bbox_input is None:
+ bbox = [-104.6, 51.8, -103.7, 52.6]
+ LOGGER.debug('No bbox input given. Using default bbox: {}'.format(bbox))
+ else:
+ bbox = bbox_input.get('bbox')
+
+ if len(bbox) != 4:
+ msg = "Received bbox '{}' is not an array containing four elements.".format(bbox)
+ LOGGER.error(msg)
+ raise ProcessorExecuteError(msg)
+
+ LOGGER.debug('Parsed Process inputs')
+ LOGGER.debug('collection : {}'.format(collection))
+ LOGGER.debug('bbox : {}'.format(bbox))
+ if bands:
+ LOGGER.debug('bands : {}'.format(bands))
+
+ return bbox, collection, bands
+
+ def _process_collection(self, collection, bbox, bands):
+
+ if collection.startswith('http'):
+
+ if collection.endswith('/'):
+ collection = collection[:-1]
+
+ # Get format string for geotiff defined by the server from the links
+ collection_url = collection + '?f=json'
+ try:
+ with requests.get(collection_url) as request:
+ request.raise_for_status()
+ collection_json = request.json()
+ collection_links = collection_json.get('links', None)
+ if collection_links:
+ format_geotiff = None
+ for link in collection_links:
+ if link['type'].replace(" ", "") in GEOTIFF_MIME_TYPES:
+ format_geotiff = link['href'].split('f=')[-1]
+ if format_geotiff is None:
+ msg = 'No link found for collection {} to get coverage data as geotiff.'.format(collection)
+ LOGGER.error(msg)
+ raise ProcessorExecuteError(msg)
+ else:
+ raise ProcessorExecuteError('The collection {} has no links.'.format(collection))
+ except HTTPError as err:
+ msg = 'Requesting collection metadata failed: {}'.format(collection_url)
+ LOGGER.error(msg)
+ raise ProcessorExecuteError(msg)
+
+ # Check if bands are in rangetype
+ if bands:
+ band_names = [band.strip() for band in bands.split(",")]
+ collection_rangetype_url = collection + '/coverage/rangetype?f=json'
+ try:
+ with requests.get(collection_rangetype_url) as request:
+ collection_rangetype_json = request.json()
+ fields = []
+ for field in collection_rangetype_json['field']:
+ fields.append(field['name'])
+ for band in band_names:
+ if band not in fields:
+ msg = 'Band {} it not provided by the collection.'.format(band)
+ LOGGER.error(msg)
+ raise ProcessorExecuteError(msg)
+ except HTTPError as err:
+ msg = 'Requesting collection rangetype failed: {}'.format(collection_rangetype_json)
+ LOGGER.error(msg)
+ raise ProcessorExecuteError(msg)
+
+ # Request coverage data
+ if bands:
+ coverage_download_url = collection + '/coverage?f={}&bbox={}&range-subset={}'.format(format_geotiff, ','.join(map(str, bbox)), bands)
+ else:
+ coverage_download_url = collection + '/coverage?f={}&bbox={}'.format(format_geotiff, ','.join(map(str, bbox)))
+
+ LOGGER.debug("Requesting coverage from '{}'".format(coverage_download_url))
+ try:
+ with requests.get(coverage_download_url, verify=False, stream=True) as request:
+ request.raise_for_status()
+
+ with MemoryFile(request.content) as memfile:
+ with memfile.open() as dataset:
+ return get_multi_spectral(dataset)
+
+ # ToDo use correct temp file and use tmp file name as input for unet.estimate_raw
+ # with open('/tmp/temp.geotiff', 'wb') as file:
+ # for chunk in request.iter_content(chunk_size=8192):
+ # file.write(chunk)
+ except HTTPError as err:
+ msg = 'Requesting input data failed: {}'.format(coverage_download_url)
+ LOGGER.error(msg)
+ raise ProcessorExecuteError(msg)
+ # write response to temporary file used as input for prediction/estimation function
+ # ToDo: add logger output, e.g. error/warning if request wasn't successful
+
+ elif collection.startswith('file'):
+ landsat_file_path = str(Path(collection).resolve())
+
+ with rasterio.open(landsat_file_path) as dataset:
+ return get_multi_spectral(dataset)
+ else:
+ raise(ProcessorExecuteError("Invalid collection input received: '{}'.".format(collection)))
+
+ def __repr__(self):
+ return ' {}'.format(self.name)
diff --git a/src/landsatpredictor/train.py b/src/landsatpredictor/train.py
new file mode 100644
index 0000000..7d9f30f
--- /dev/null
+++ b/src/landsatpredictor/train.py
@@ -0,0 +1,20 @@
+# =================================================================
+# Copyright (C) 2021-2021 52°North Spatial Information Research GmbH
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# =================================================================
+import sys
+import pickle
+from u_net import UNET
+
+model = UNET(batch_size=16, epochs=300)
+model.train()
diff --git a/u_net.py b/src/landsatpredictor/u_net.py
similarity index 78%
rename from u_net.py
rename to src/landsatpredictor/u_net.py
index 93f55a6..a790dbd 100644
--- a/u_net.py
+++ b/src/landsatpredictor/u_net.py
@@ -1,22 +1,36 @@
+# =================================================================
+# Copyright (C) 2021-2021 52°North Spatial Information Research GmbH
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# =================================================================
import os
import pickle
+import tempfile
from pathlib import Path
+
+import numpy as np
import rasterio
from PIL import Image
-from matplotlib import pyplot as plt, patches
-import numpy as np
-from tensorflow.keras.models import Model, load_model
-from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D
+from matplotlib import pyplot as plt
+from tensorflow.python.keras import backend as K
from tensorflow.python.keras.backend import concatenate
from tensorflow.python.keras.callbacks import ModelCheckpoint, EarlyStopping
from tensorflow.python.keras.layers import Conv2DTranspose, Dropout
+from tensorflow.python.keras.layers import Input, Conv2D, MaxPooling2D
+from tensorflow.python.keras.models import Model, load_model
from tensorflow.python.keras.optimizer_v2.adam import Adam
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator
-from config import selected_classes, colors, colors_legend
-from preprocessing.image_registration import rotate_datasets, getMultiSpectral
-from tensorflow.keras import backend as K
-
+from .config import selected_classes, colors, colors_legend
def dice_coef(y_true, y_pred, smooth=1):
@@ -28,10 +42,10 @@ def dice_coef_loss(y_true, y_pred):
return 1 - dice_coef(y_true, y_pred)
-def getTeilsGenerator(w, h, window_size, trim, in_image):
- stepSize = window_size - trim * 2
- for y in range(0, h, stepSize):
- for x in range(0, w, stepSize):
+def get_tiles_generator(w, h, window_size, trim, in_image):
+ step_size = window_size - trim * 2
+ for y in range(0, h, step_size):
+ for x in range(0, w, step_size):
x_overflow = x + window_size
y_overflow = y + window_size
if x_overflow > w and y_overflow > h:
@@ -44,19 +58,19 @@ def getTeilsGenerator(w, h, window_size, trim, in_image):
yield in_image[:, x:x_overflow, y:y_overflow, :], x, y, x_overflow, y_overflow
-
class UNET:
- def __init__(self, batch_size=64, epochs=30, window_size=256):
+ def __init__(self, weight_file: str = str(Path('data/3_class_best_weight.hdf5')), batch_size: int = 64,
+ epochs: int = 30, window_size: int = 256):
self.bands = 6
self.batch_size = batch_size
self.window_size = window_size
self.epochs = epochs
- self.weight_file = str(Path('3_class_best_weight.hdf5'))
+ self.weight_file = weight_file
self.model = self.init_network((window_size, window_size, self.bands))
self.model.compile(loss=dice_coef_loss, optimizer=Adam(learning_rate=0.001), # Adam(learning_rate=0.001),
metrics=['accuracy'])
self.model = load_model(self.weight_file, custom_objects={'dice_coef_loss': dice_coef_loss})
- # self.model.load_weights(self.weight_file)
+ self.model.load_weights(self.weight_file)
def init_network(self, input_size):
"""
@@ -205,43 +219,41 @@ def test(self):
plt.legend(handles=colors_legend, borderaxespad=-15, fontsize='x-small')
plt.show()
- def estimate_raw_landsat(self, path: Path, trim=20):
+ def estimate_raw_landsat(self, input_landsat_bands_normalized, visual_light_reflectance_mask, metadata, trim=20):
"""
Estimates the full map image by sliding a window over and
trimming off sides from each side of 256*256 patch
- :param path:
- folder path of landsat scene
+ :param metadata:
+ :param input_landsat_bands_normalized:
+ :param visual_light_reflectance_mask:
:param trim: int
the number of pixels trimmed of each side of the predicted window
e.g. 100 -> adds only the middle 56*56 square of the 256*256 patch to the result.
The trimming is used to avoid creases and artifacts since patch-wise prediction
has no knowledge of nearby structures from the next patch.
"""
- multi_image = [rasterio.open(band_path) for band_path in list(Path(path).glob('*SR_B[2-7].TIF'))]
- profile = multi_image[0].meta.copy()
- profile.update(count=7)
- with rasterio.open(Path(path, '%s.tif' % 'merged'), 'w',
- **profile) as dst:
- for i, band in enumerate(multi_image, start=2):
- dst.write(band.read(1), i)
- band.close()
- input_map, mask, metadata = getMultiSpectral(Path(path, 'merged.tif'))
- self.model.load_weights(self.weight_file)
- w, h, _ = input_map.shape
- in_image = np.reshape(input_map, (1, input_map.shape[0], input_map.shape[1], input_map.shape[2]))
- res = np.zeros((input_map.shape[0], input_map.shape[1]))
- for window_data, x, y, x_overflow, y_overflow in getTeilsGenerator(w, h, self.window_size, trim, in_image):
+
+ input_width, input_height, input_band_count = input_landsat_bands_normalized.shape
+ in_image = np.reshape(input_landsat_bands_normalized, (1, input_width, input_height, input_band_count))
+ result = np.zeros((input_width, input_height))
+ for window_data, x, y, x_overflow, y_overflow in get_tiles_generator(input_width, input_height, self.window_size, trim, in_image):
window = np.zeros((1, self.window_size, self.window_size, self.bands))
window[:, :window_data.shape[1], :window_data.shape[2], :] = window_data
output = self.model.predict(window, verbose=0)[:, :window_data.shape[1], :window_data.shape[2], :]
- res[x + trim:x_overflow - trim,
- y + trim:y_overflow - trim] = np.argmax(output.squeeze()[
+ result[x + trim:x_overflow - trim,
+ y + trim:y_overflow - trim] = np.argmax(output.squeeze()[
trim:window_data.shape[1] - trim,
trim:window_data.shape[2] - trim],
axis=2)
- assert res.shape[0] == w and res.shape[1] == h
- print(res.shape[0], res.shape[1])
- res *= mask
- with rasterio.open(Path(path, 'classified_landcover.tif'), 'w', **metadata) as dst:
- dst.write(res.astype(rasterio.uint8), 1)
-
+ assert result.shape[0] == input_width and result.shape[1] == input_height
+ # ToDo change to log statement
+ print(result.shape[0], result.shape[1])
+ # skip all pixels without visual light reflectance in landsat scene
+ # shift all classes +1 in the result, hence 0:= no data and not no_change
+ result += 1
+ # ToDo potentially skip this when using numpy masked arrays
+ result *= visual_light_reflectance_mask
+ temp_result_file = tempfile.NamedTemporaryFile(delete=False, suffix='.tif', prefix='landcover_prediction_')
+ with rasterio.open(temp_result_file.name, 'w', **metadata) as destination:
+ destination.write(result.astype(rasterio.uint8), 1)
+ return temp_result_file.name
diff --git a/test.py b/test.py
deleted file mode 100644
index 3507a22..0000000
--- a/test.py
+++ /dev/null
@@ -1,6 +0,0 @@
-from pathlib import Path
-from u_net import UNET
-
-
-model = UNET(batch_size=24, epochs=50)
-model.estimate_raw_landsat(path=Path('test', 'LC08_L2SP_035024'), trim=5)
diff --git a/tests/config.yml b/tests/config.yml
new file mode 100644
index 0000000..ff52d3e
--- /dev/null
+++ b/tests/config.yml
@@ -0,0 +1,66 @@
+# Copyright (C) 2021-2021 52°North Spatial Information Research GmbH
+#
+# This program is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 as published
+# by the Free Software Foundation.
+#
+# If the program is linked with libraries which are licensed under one of
+# the following licenses, the combination of the program with the linked
+# library is not considered a "derivative work" of the program:
+#
+# - Apache License, version 2.0
+# - Apache Software License, version 1.0
+# - GNU Lesser General Public License, version 3
+# - Mozilla Public License, versions 1.0, 1.1 and 2.0
+# - Common Development and Distribution License (CDDL), version 1.0
+#
+# Therefore the distribution of the program linked with libraries licensed
+# under the aforementioned licenses, is permitted by the copyright holders
+# if the distribution is compliant with both the GNU General Public
+# License version 2 and the aforementioned licenses.
+#
+# This program is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
+# Public License for more details.
+#
+server:
+ bind:
+ host: 0.0.0.0
+ port: 5000
+ cors: True
+ encoding: utf-8
+ language: en-US
+ limit: 10
+ manager:
+ name: TinyDB
+ connection: /tmp/pygeoapi-process-manager.db
+ output_dir: /tmp/pygeoapi-process-outputs/
+ map:
+ attribution: '© OpenStreetMap contributors'
+ url: https://tile.openstreetmap.org/{z}/{x}/{y}.png
+ mimetype: application/json; charset=UTF-8
+ pretty_print: True
+ url: http://localhost:5000/
+
+logging:
+ level: DEBUG
+
+metadata:
+ identification:
+ title: '[TEST] OGC API Processes for Landsat Prediction'
+ description: '[TEST] instance'
+ contact:
+ name: Doe, John
+ license:
+ name: CC-BY 4.0 license
+ url: https://creativecommons.org/licenses/by/4.0/
+ provider:
+ name: ACME
+ url: https://example.org/
+
+resources:
+ landcover-prediction:
+ type: process
+ processor:
+ name: landsatpredictor.LandcoverPredictionProcessor
diff --git a/tests/data/LC08_L2SP_035024_20150813_20200909_02_T1_merged_1-6_cropped.tif b/tests/data/LC08_L2SP_035024_20150813_20200909_02_T1_merged_1-6_cropped.tif
new file mode 100644
index 0000000..c3c6f3a
Binary files /dev/null and b/tests/data/LC08_L2SP_035024_20150813_20200909_02_T1_merged_1-6_cropped.tif differ
diff --git a/tests/manual/test.py b/tests/manual/test.py
new file mode 100644
index 0000000..c846733
--- /dev/null
+++ b/tests/manual/test.py
@@ -0,0 +1,28 @@
+# =================================================================
+# Copyright (C) 2021-2021 52°North Spatial Information Research GmbH
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# =================================================================
+from pathlib import Path
+import rasterio
+from landsatpredictor.u_net import UNET
+from landsatpredictor.preprocessing.image_registration import get_multi_spectral
+
+model = UNET(weight_file= '../../data/3_class_best_weight.hdf5', batch_size=24, epochs=50)
+
+landsat_file_path = Path('..', 'data', 'LC08_L2SP_035024_20150813_20200909_02_T1_merged_1-6_cropped.tif')
+with rasterio.open(landsat_file_path) as dataset:
+ input_landsat_bands_normalized, visual_light_reflectance_mask, metadata = get_multi_spectral(dataset)
+
+result_file = model.estimate_raw_landsat(input_landsat_bands_normalized, visual_light_reflectance_mask, metadata, trim=5)
+
+print('Estimation result can be found in file "{}"'.format(Path(result_file).resolve()))
diff --git a/train.py b/train.py
deleted file mode 100644
index 4fd4833..0000000
--- a/train.py
+++ /dev/null
@@ -1,6 +0,0 @@
-import sys
-import pickle
-from u_net import UNET
-
-model = UNET(batch_size=16, epochs=300)
-model.train()