diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..8b83274
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,8 @@
+*.pyc
+*.mat
+*.tif
+*.png
+*.mp4
+*.gif
+*.jpg
+*.pkl
\ No newline at end of file
diff --git a/.ipynb_checkpoints/shoreline_extraction-checkpoint.ipynb b/.ipynb_checkpoints/shoreline_extraction-checkpoint.ipynb
new file mode 100644
index 0000000..8d99b85
--- /dev/null
+++ b/.ipynb_checkpoints/shoreline_extraction-checkpoint.ipynb
@@ -0,0 +1,199 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Shoreline extraction from satellite images"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This notebook shows how to download satellite images (Landsat 5,7,8 and Sentinel-2) from Google Earth Engine and apply the shoreline detection algorithm described in *Vos K., Harley M.D., Splinter K.D., Simmons J.A., Turner I.L. (in review). Capturing intra-annual to multi-decadal shoreline variability from publicly available satellite imagery, Coastal Engineering*. "
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Initial settings"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The Python packages required to run this notebook can be installed by running the following anaconda command:\n",
+ "*\"conda env create -f environment.yml\"*. This will create a new enviroment with all the relevant packages installed. You will also need to sign up for Google Earth Engine (https://earthengine.google.com and go to signup) and authenticate on the computer so that python can access via your login."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "import pickle\n",
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "import warnings\n",
+ "warnings.filterwarnings(\"ignore\")\n",
+ "# load modules from directory\n",
+ "import SDS_download, SDS_preprocess, SDS_tools, SDS_shoreline"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Download images"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Define the region of interest, the dates and the satellite missions from which you want to download images. The image will be cropped on the Google Earth Engine server and only the region of interest will be downloaded resulting in low memory allocation (~ 1 megabyte/image for 5 km of beach)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# define the area of interest (longitude, latitude)\n",
+ "polygon = [[[151.301454, -33.700754],\n",
+ " [151.311453, -33.702075], \n",
+ " [151.307237, -33.739761],\n",
+ " [151.294220, -33.736329],\n",
+ " [151.301454, -33.700754]]]\n",
+ " \n",
+ "# define dates of interest\n",
+ "dates = ['2017-12-01','2018-01-01']\n",
+ "\n",
+ "# define satellite missions ('L5' --> landsat 5 , 'S2' --> Sentinel-2)\n",
+ "sat_list = ['L5', 'L7', 'L8', 'S2']\n",
+ "\n",
+ "# give a name to the site\n",
+ "sitename = 'NARRA'\n",
+ "\n",
+ "# download satellite images. The cropped images are saved in a '/data' subfolder. The image information is stored\n",
+ "# into 'metadata.pkl'.\n",
+ "# SDS_download.get_images(sitename, polygon, dates, sat_list)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Shoreline extraction"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Performs a sub-pixel resolution shoreline detection method integrating a supervised classification component that allows to map the boundary between water and sand."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# parameters and settings\n",
+ "%matplotlib qt\n",
+ "settings = { \n",
+ " 'sitename': sitename,\n",
+ " \n",
+ " # general parameters:\n",
+ " 'cloud_thresh': 0.5, # threshold on maximum cloud cover\n",
+ " 'output_epsg': 28356, # epsg code of the desired output spatial reference system\n",
+ " \n",
+ " # shoreline detection parameters:\n",
+ " 'min_beach_size': 20, # minimum number of connected pixels for a beach\n",
+ " 'buffer_size': 7, # radius (in pixels) of disk for buffer around sandy pixels\n",
+ " 'min_length_sl': 200, # minimum length of shoreline perimeter to be kept \n",
+ " 'max_dist_ref': 100 , # max distance (in meters) allowed from a reference shoreline\n",
+ " \n",
+ " # quality control:\n",
+ " 'check_detection': True # if True, shows each shoreline detection and lets the user \n",
+ " # decide which shorleines are correct and which ones are false due to\n",
+ " # the presence of clouds and other artefacts. \n",
+ " # If set to False, shorelines are extracted from all images.\n",
+ " }\n",
+ "\n",
+ "# load metadata structure (contains information on the downloaded satellite images and is created\n",
+ "# after all images have been successfully downloaded)\n",
+ "filepath = os.path.join(os.getcwd(), 'data', settings['sitename'])\n",
+ "with open(os.path.join(filepath, settings['sitename'] + '_metadata' + '.pkl'), 'rb') as f:\n",
+ " metadata = pickle.load(f)\n",
+ " \n",
+ "# [OPTIONAL] saves .jpg files of the preprocessed images (cloud mask and pansharpening/down-sampling) \n",
+ "#SDS_preprocess.preprocess_all_images(metadata, settings)\n",
+ "\n",
+ "# [OPTIONAL] to avoid false detections and identify obvious outliers there is the option to\n",
+ "# create a reference shoreline position (manually clicking on a satellite image)\n",
+ "settings['refsl'] = SDS_preprocess.get_reference_sl(metadata, settings)\n",
+ "\n",
+ "# extract shorelines from all images. Saves out.pkl which contains the shoreline coordinates for each date in the spatial\n",
+ "# reference system specified in settings['output_epsg']. Save the output in a file called 'out.pkl'.\n",
+ "out = SDS_shoreline.extract_shorelines(metadata, settings)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Plot the shorelines"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "plt.figure()\n",
+ "plt.axis('equal')\n",
+ "plt.xlabel('Eastings [m]')\n",
+ "plt.ylabel('Northings [m]')\n",
+ "plt.title('Shorelines')\n",
+ "for satname in out.keys():\n",
+ " if satname == 'meta':\n",
+ " continue\n",
+ " for i in range(len(out[satname]['shoreline'])):\n",
+ " sl = out[satname]['shoreline'][i]\n",
+ " date = out[satname]['timestamp'][i]\n",
+ " plt.plot(sl[:,0], sl[:,1], '-', label=date.strftime('%d-%m-%Y'))\n",
+ "plt.legend()"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.4"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ 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.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..c15b548
--- /dev/null
+++ b/README.md
@@ -0,0 +1,33 @@
+# coastsat
+
+Python code to download publicly available satellite imagery with Google Earth Engine API and extract shorelines using a robust sub-pixel resolution shoreline detection algorithm described in *Vos K., Harley M.D., Splinter K.D., Simmons J.A., Turner I.L. (in review). Capturing intra-annual to multi-decadal shoreline variability from publicly available satellite imagery, Coastal Engineering*.
+
+Written by *Kilian Vos*.
+
+## Description
+
+Satellite remote sensing can provide low-cost long-term shoreline data capable of resolving the temporal scales of interest to coastal scientists and engineers at sites where no in-situ measurements are available. Satellite imagery spannig the last 30 years with constant revisit periods is publicly available and suitable to extract repeated measurements of the shoreline positon.
+*coastsat* is an open-source Python module that allows to extract shorelines from Landsat 5, Landsat 7, Landsat 8 and Sentinel-2 images.
+The shoreline detection algorithm proposed here combines a sub-pixel border segmentation and an image classification component, which refines the segmentation into four distinct categories such that the shoreline detection is specific to the sand/water interface.
+
+## Use
+
+A demonstration of the use of *coastsat* is provided in the Jupyter Notebook *shoreline_extraction.ipynb*. The code can also be run in Spyder with *main_spyder.py*.
+
+The Python packages required to run this notebook can be installed by running the following anaconda command: *conda env create -f environment.yml*. This will create a new enviroment with all the relevant packages installed. You will also need to sign up for Google Earth Engine (https://earthengine.google.com and go to signup) and authenticate on the computer so that python can access via your login.
+
+The first step is to retrieve the satellite images of the region of interest from Google Earth Engine servers by calling *SDS_download.get_images(sitename, polygon, dates, sat_list)*:
+- *sitename* is a string which will define the name of the folder where the files will be stored
+- *polygon* contains the coordinates of the region of interest (longitude/latitude pairs)
+- *dates* defines the dates over which the images will be retrieved (e.g., *dates = ['2017-12-01', '2018-01-01']*)
+- *sat_list* indicates which satellite missions to consider (e.g., *sat_list = ['L5', 'L7', 'L8', 'S2']* will download images from Landsat 5, 7, 8 and Sentinel-2 collections).
+
+The images are cropped on the Google Earth Engine servers and only the region of interest is downloaded resulting in low memory allocation (~ 1 megabyte/image for a 5km-long beach). The relevant image metadata (time of acquisition, geometric accuracy...etc) is stored in a file named *sitename_metadata.pkl*.
+
+Once the images have been downloaded, the shorelines are extracted from the multispectral images using the sub-pixel resolution technique described in *Vos K., Harley M.D., Splinter K.D., Simmons J.A., Turner I.L. (in review). Capturing intra-annual to multi-decadal shoreline variability from publicly available satellite imagery, Coastal Engineering*.
+The shoreline extraction is performed by the function SDS_shoreline.extract_shorelines(metadata, settings). The user must define the settings in a Python dictionary. To ensure maximum robustness of the algorithm the user can optionally digitize a reference shoreline (byc calling *SDS_preprocess.get_reference_sl(metadata, settings)*) that will then be used to identify obvious outliers and minimize false detections. Since the cloud mask is not perfect (especially in Sentinel-2 images) the user has the option to manually validate each detection by setting the *'check_detection'* parameter to *True*.
+The shoreline coordinates (in the coordinate system defined by the user in *'output_epsg'* are stored in a file named *sitename_out.pkl*.
+
+## Issues and Contributions
+
+Looking to contribute to the code? Please see the [Issues page](https://github.com/kvos/coastsat/issues).
diff --git a/SDS_download.py b/SDS_download.py
new file mode 100644
index 0000000..138a865
--- /dev/null
+++ b/SDS_download.py
@@ -0,0 +1,432 @@
+"""This module contains all the functions needed to download the satellite images from GEE
+
+ Author: Kilian Vos, Water Research Laboratory, University of New South Wales
+"""
+
+# Initial settings
+import os
+import numpy as np
+import matplotlib.pyplot as plt
+import pdb
+import ee
+from urllib.request import urlretrieve
+from datetime import datetime
+import pytz
+import pickle
+import zipfile
+
+# initialise connection with GEE server
+ee.Initialize()
+
+# Functions
+
+def download_tif(image, polygon, bandsId, filepath):
+ """
+ Downloads a .TIF image from the ee server and stores it in a temp file
+
+ Arguments:
+ -----------
+ image: ee.Image
+ Image object to be downloaded
+ polygon: list
+ polygon containing the lon/lat coordinates to be extracted
+ longitudes in the first column and latitudes in the second column
+ bandsId: list of dict
+ list of bands to be downloaded
+ filepath: location where the temporary file should be saved
+
+ """
+
+ url = ee.data.makeDownloadUrl(ee.data.getDownloadId({
+ 'image': image.serialize(),
+ 'region': polygon,
+ 'bands': bandsId,
+ 'filePerBand': 'false',
+ 'name': 'data',
+ }))
+ local_zip, headers = urlretrieve(url)
+ with zipfile.ZipFile(local_zip) as local_zipfile:
+ return local_zipfile.extract('data.tif', filepath)
+
+
+def get_images(sitename,polygon,dates,sat):
+ """
+ Downloads all images from Landsat 5, Landsat 7, Landsat 8 and Sentinel-2 covering the given
+ polygon and acquired during the given dates. The images are organised in subfolders and divided
+ by satellite mission and pixel resolution.
+
+ KV WRL 2018
+
+ Arguments:
+ -----------
+ sitename: str
+ String containig the name of the site
+ polygon: list
+ polygon containing the lon/lat coordinates to be extracted
+ longitudes in the first column and latitudes in the second column
+ dates: list of str
+ list that contains 2 strings with the initial and final dates in format 'yyyy-mm-dd'
+ e.g. ['1987-01-01', '2018-01-01']
+ sat: list of str
+ list that contains the names of the satellite missions to include
+ e.g. ['L5', 'L7', 'L8', 'S2']
+
+ """
+
+ # format in which the images are downloaded
+ suffix = '.tif'
+
+ # initialise metadata dictionnary (stores timestamps and georefencing accuracy of each image)
+ metadata = dict([])
+
+ # create directories
+ try:
+ os.makedirs(os.path.join(os.getcwd(), 'data',sitename))
+ except:
+ print('')
+
+ #=============================================================================================#
+ # download L5 images
+ #=============================================================================================#
+
+ if 'L5' in sat or 'Landsat5' in sat:
+
+ satname = 'L5'
+ # create a subfolder to store L5 images
+ filepath = os.path.join(os.getcwd(), 'data', sitename, satname, '30m')
+ try:
+ os.makedirs(filepath)
+ except:
+ print('')
+
+ # Landsat 5 collection
+ input_col = ee.ImageCollection('LANDSAT/LT05/C01/T1_TOA')
+ # filter by location and dates
+ flt_col = input_col.filterBounds(ee.Geometry.Polygon(polygon)).filterDate(dates[0],dates[1])
+ # get all images in the filtered collection
+ im_all = flt_col.getInfo().get('features')
+ # print how many images there are for the user
+ n_img = flt_col.size().getInfo()
+ print('Number of ' + satname + ' images covering ' + sitename + ':', n_img)
+
+ # loop trough images
+ timestamps = []
+ acc_georef = []
+ all_names = []
+ im_epsg = []
+ for i in range(n_img):
+
+ # find each image in ee database
+ im = ee.Image(im_all[i].get('id'))
+ # read metadata
+ im_dic = im.getInfo()
+ # get bands
+ im_bands = im_dic.get('bands')
+ # get time of acquisition (UNIX time)
+ t = im_dic['properties']['system:time_start']
+ # convert to datetime
+ im_timestamp = datetime.fromtimestamp(t/1000, tz=pytz.utc)
+ timestamps.append(im_timestamp)
+ im_date = im_timestamp.strftime('%Y-%m-%d-%H-%M-%S')
+ # get EPSG code of reference system
+ im_epsg.append(int(im_dic['bands'][0]['crs'][5:]))
+ # get geometric accuracy
+ try:
+ acc_georef.append(im_dic['properties']['GEOMETRIC_RMSE_MODEL'])
+ except:
+ # default value of accuracy (RMSE = 12m)
+ acc_georef.append(12)
+ print('No geometric rmse model property')
+ # delete dimensions key from dictionnary, otherwise the entire image is extracted
+ for j in range(len(im_bands)): del im_bands[j]['dimensions']
+ # bands for L5
+ ms_bands = [im_bands[0], im_bands[1], im_bands[2], im_bands[3], im_bands[4], im_bands[7]]
+ # filenames for the images
+ filename = im_date + '_' + satname + '_' + sitename + suffix
+ # if two images taken at the same date add 'dup' in the name
+ if any(filename in _ for _ in all_names):
+ filename = im_date + '_' + satname + '_' + sitename + '_dup' + suffix
+ all_names.append(filename)
+ # download .TIF image
+ local_data = download_tif(im, polygon, ms_bands, filepath)
+ # update filename
+ os.rename(local_data, os.path.join(filepath, filename))
+ print(i, end='..')
+
+ # sort timestamps and georef accuracy (dowloaded images are sorted by date in directory)
+ timestamps_sorted = sorted(timestamps)
+ idx_sorted = sorted(range(len(timestamps)), key=timestamps.__getitem__)
+ acc_georef_sorted = [acc_georef[j] for j in idx_sorted]
+ im_epsg_sorted = [im_epsg[j] for j in idx_sorted]
+ # save into dict
+ metadata[satname] = {'dates':timestamps_sorted, 'acc_georef':acc_georef_sorted,
+ 'epsg':im_epsg_sorted}
+ print('Finished with ' + satname)
+
+
+
+ #=============================================================================================#
+ # download L7 images
+ #=============================================================================================#
+
+ if 'L7' in sat or 'Landsat7' in sat:
+
+ satname = 'L7'
+ # create subfolders (one for 30m multispectral bands and one for 15m pan bands)
+ filepath = os.path.join(os.getcwd(), 'data', sitename, 'L7')
+ filepath_pan = os.path.join(filepath, 'pan')
+ filepath_ms = os.path.join(filepath, 'ms')
+ try:
+ os.makedirs(filepath_pan)
+ os.makedirs(filepath_ms)
+ except:
+ print('')
+
+ # landsat 7 collection
+ input_col = ee.ImageCollection('LANDSAT/LE07/C01/T1_RT_TOA')
+ # filter by location and dates
+ flt_col = input_col.filterBounds(ee.Geometry.Polygon(polygon)).filterDate(dates[0],dates[1])
+ # get all images in the filtered collection
+ im_all = flt_col.getInfo().get('features')
+ # print how many images there are for the user
+ n_img = flt_col.size().getInfo()
+ print('Number of ' + satname + ' images covering ' + sitename + ':', n_img)
+
+ # loop trough images
+ timestamps = []
+ acc_georef = []
+ all_names = []
+ im_epsg = []
+ for i in range(n_img):
+
+ # find each image in ee database
+ im = ee.Image(im_all[i].get('id'))
+ # read metadata
+ im_dic = im.getInfo()
+ # get bands
+ im_bands = im_dic.get('bands')
+ # get time of acquisition (UNIX time)
+ t = im_dic['properties']['system:time_start']
+ # convert to datetime
+ im_timestamp = datetime.fromtimestamp(t/1000, tz=pytz.utc)
+ timestamps.append(im_timestamp)
+ im_date = im_timestamp.strftime('%Y-%m-%d-%H-%M-%S')
+ # get EPSG code of reference system
+ im_epsg.append(int(im_dic['bands'][0]['crs'][5:]))
+ # get geometric accuracy
+ try:
+ acc_georef.append(im_dic['properties']['GEOMETRIC_RMSE_MODEL'])
+ except:
+ # default value of accuracy (RMSE = 12m)
+ acc_georef.append(12)
+ print('No geometric rmse model property')
+ # delete dimensions key from dictionnary, otherwise the entire image is extracted
+ for j in range(len(im_bands)): del im_bands[j]['dimensions']
+ # bands for L7
+ pan_band = [im_bands[8]]
+ ms_bands = [im_bands[0], im_bands[1], im_bands[2], im_bands[3], im_bands[4], im_bands[9]]
+ # filenames for the images
+ filename_pan = im_date + '_' + satname + '_' + sitename + '_pan' + suffix
+ filename_ms = im_date + '_' + satname + '_' + sitename + '_ms' + suffix
+ # if two images taken at the same date add 'dup' in the name
+ if any(filename_pan in _ for _ in all_names):
+ filename_pan = im_date + '_' + satname + '_' + sitename + '_pan' + '_dup' + suffix
+ filename_ms = im_date + '_' + satname + '_' + sitename + '_ms' + '_dup' + suffix
+ all_names.append(filename_pan)
+ # download .TIF image
+ local_data_pan = download_tif(im, polygon, pan_band, filepath_pan)
+ local_data_ms = download_tif(im, polygon, ms_bands, filepath_ms)
+ # update filename
+ os.rename(local_data_pan, os.path.join(filepath_pan, filename_pan))
+ os.rename(local_data_ms, os.path.join(filepath_ms, filename_ms))
+ print(i, end='..')
+
+ # sort timestamps and georef accuracy (dowloaded images are sorted by date in directory)
+ timestamps_sorted = sorted(timestamps)
+ idx_sorted = sorted(range(len(timestamps)), key=timestamps.__getitem__)
+ acc_georef_sorted = [acc_georef[j] for j in idx_sorted]
+ im_epsg_sorted = [im_epsg[j] for j in idx_sorted]
+ # save into dict
+ metadata[satname] = {'dates':timestamps_sorted, 'acc_georef':acc_georef_sorted,
+ 'epsg':im_epsg_sorted}
+ print('Finished with ' + satname)
+
+
+ #=============================================================================================#
+ # download L8 images
+ #=============================================================================================#
+
+ if 'L8' in sat or 'Landsat8' in sat:
+
+ satname = 'L8'
+ # create subfolders (one for 30m multispectral bands and one for 15m pan bands)
+ filepath = os.path.join(os.getcwd(), 'data', sitename, 'L8')
+ filepath_pan = os.path.join(filepath, 'pan')
+ filepath_ms = os.path.join(filepath, 'ms')
+ try:
+ os.makedirs(filepath_pan)
+ os.makedirs(filepath_ms)
+ except:
+ print('')
+
+ # landsat 8 collection
+ input_col = ee.ImageCollection('LANDSAT/LC08/C01/T1_RT_TOA')
+ # filter by location and dates
+ flt_col = input_col.filterBounds(ee.Geometry.Polygon(polygon)).filterDate(dates[0],dates[1])
+ # get all images in the filtered collection
+ im_all = flt_col.getInfo().get('features')
+ # print how many images there are for the user
+ n_img = flt_col.size().getInfo()
+ print('Number of ' + satname + ' images covering ' + sitename + ':', n_img)
+
+ # loop trough images
+ timestamps = []
+ acc_georef = []
+ all_names = []
+ im_epsg = []
+ for i in range(n_img):
+
+ # find each image in ee database
+ im = ee.Image(im_all[i].get('id'))
+ # read metadata
+ im_dic = im.getInfo()
+ # get bands
+ im_bands = im_dic.get('bands')
+ # get time of acquisition (UNIX time)
+ t = im_dic['properties']['system:time_start']
+ # convert to datetime
+ im_timestamp = datetime.fromtimestamp(t/1000, tz=pytz.utc)
+ timestamps.append(im_timestamp)
+ im_date = im_timestamp.strftime('%Y-%m-%d-%H-%M-%S')
+ # get EPSG code of reference system
+ im_epsg.append(int(im_dic['bands'][0]['crs'][5:]))
+ # get geometric accuracy
+ try:
+ acc_georef.append(im_dic['properties']['GEOMETRIC_RMSE_MODEL'])
+ except:
+ # default value of accuracy (RMSE = 12m)
+ acc_georef.append(12)
+ print('No geometric rmse model property')
+ # delete dimensions key from dictionnary, otherwise the entire image is extracted
+ for j in range(len(im_bands)): del im_bands[j]['dimensions']
+ # bands for L8
+ pan_band = [im_bands[7]]
+ ms_bands = [im_bands[1], im_bands[2], im_bands[3], im_bands[4], im_bands[5], im_bands[11]]
+ # filenames for the images
+ filename_pan = im_date + '_' + satname + '_' + sitename + '_pan' + suffix
+ filename_ms = im_date + '_' + satname + '_' + sitename + '_ms' + suffix
+ # if two images taken at the same date add 'dup' in the name
+ if any(filename_pan in _ for _ in all_names):
+ filename_pan = im_date + '_' + satname + '_' + sitename + '_pan' + '_dup' + suffix
+ filename_ms = im_date + '_' + satname + '_' + sitename + '_ms' + '_dup' + suffix
+ all_names.append(filename_pan)
+ # download .TIF image
+ local_data_pan = download_tif(im, polygon, pan_band, filepath_pan)
+ local_data_ms = download_tif(im, polygon, ms_bands, filepath_ms)
+ # update filename
+ os.rename(local_data_pan, os.path.join(filepath_pan, filename_pan))
+ os.rename(local_data_ms, os.path.join(filepath_ms, filename_ms))
+ print(i, end='..')
+
+ # sort timestamps and georef accuracy (dowloaded images are sorted by date in directory)
+ timestamps_sorted = sorted(timestamps)
+ idx_sorted = sorted(range(len(timestamps)), key=timestamps.__getitem__)
+ acc_georef_sorted = [acc_georef[j] for j in idx_sorted]
+ im_epsg_sorted = [im_epsg[j] for j in idx_sorted]
+
+ metadata[satname] = {'dates':timestamps_sorted, 'acc_georef':acc_georef_sorted,
+ 'epsg':im_epsg_sorted}
+ print('Finished with ' + satname)
+
+ #=============================================================================================#
+ # download S2 images
+ #=============================================================================================#
+
+ if 'S2' in sat or 'Sentinel2' in sat:
+
+ satname = 'S2'
+ # create subfolders for the 10m, 20m and 60m multipectral bands
+ filepath = os.path.join(os.getcwd(), 'data', sitename, 'S2')
+ try:
+ os.makedirs(os.path.join(filepath, '10m'))
+ os.makedirs(os.path.join(filepath, '20m'))
+ os.makedirs(os.path.join(filepath, '60m'))
+ except:
+ print('')
+
+ # Sentinel2 collection
+ input_col = ee.ImageCollection('COPERNICUS/S2')
+ # filter by location and dates
+ flt_col = input_col.filterBounds(ee.Geometry.Polygon(polygon)).filterDate(dates[0],dates[1])
+ # get all images in the filtered collection
+ im_all = flt_col.getInfo().get('features')
+ # print how many images there are
+ n_img = flt_col.size().getInfo()
+ print('Number of ' + satname + ' images covering ' + sitename + ':', n_img)
+
+ # loop trough images
+ timestamps = []
+ acc_georef = []
+ all_names = []
+ im_epsg = []
+ for i in range(n_img):
+
+ # find each image in ee database
+ im = ee.Image(im_all[i].get('id'))
+ # read metadata
+ im_dic = im.getInfo()
+ # get bands
+ im_bands = im_dic.get('bands')
+ # get time of acquisition (UNIX time)
+ t = im_dic['properties']['system:time_start']
+ # convert to datetime
+ im_timestamp = datetime.fromtimestamp(t/1000, tz=pytz.utc)
+ im_date = im_timestamp.strftime('%Y-%m-%d-%H-%M-%S')
+ # delete dimensions key from dictionnary, otherwise the entire image is extracted
+ for j in range(len(im_bands)): del im_bands[j]['dimensions']
+ # bands for S2
+ bands10 = [im_bands[1], im_bands[2], im_bands[3], im_bands[7]]
+ bands20 = [im_bands[11]]
+ bands60 = [im_bands[15]]
+ # filenames for images
+ filename10 = im_date + '_' + satname + '_' + sitename + '_' + '10m' + suffix
+ filename20 = im_date + '_' + satname + '_' + sitename + '_' + '20m' + suffix
+ filename60 = im_date + '_' + satname + '_' + sitename + '_' + '60m' + suffix
+ # if two images taken at the same date skip the second image (they are the same)
+ if any(filename10 in _ for _ in all_names):
+ continue
+ all_names.append(filename10)
+ # download .TIF image and update filename
+ local_data = download_tif(im, polygon, bands10, os.path.join(filepath, '10m'))
+ os.rename(local_data, os.path.join(filepath, '10m', filename10))
+ local_data = download_tif(im, polygon, bands20, os.path.join(filepath, '20m'))
+ os.rename(local_data, os.path.join(filepath, '20m', filename20))
+ local_data = download_tif(im, polygon, bands60, os.path.join(filepath, '60m'))
+ os.rename(local_data, os.path.join(filepath, '60m', filename60))
+
+ # save timestamp, epsg code and georeferencing accuracy (1 if passed 0 if not passed)
+ timestamps.append(im_timestamp)
+ im_epsg.append(int(im_dic['bands'][0]['crs'][5:]))
+ try:
+ if im_dic['properties']['GEOMETRIC_QUALITY_FLAG'] == 'PASSED':
+ acc_georef.append(1)
+ else:
+ acc_georef.append(0)
+ except:
+ acc_georef.append(0)
+ print(i, end='..')
+
+ # sort timestamps and georef accuracy (dowloaded images are sorted by date in directory)
+ timestamps_sorted = sorted(timestamps)
+ idx_sorted = sorted(range(len(timestamps)), key=timestamps.__getitem__)
+ acc_georef_sorted = [acc_georef[j] for j in idx_sorted]
+ im_epsg_sorted = [im_epsg[j] for j in idx_sorted]
+
+ metadata[satname] = {'dates':timestamps_sorted, 'acc_georef':acc_georef_sorted,
+ 'epsg':im_epsg_sorted}
+ print('Finished with ' + satname)
+
+ # save metadata dict
+ filepath = os.path.join(os.getcwd(), 'data', sitename)
+ with open(os.path.join(filepath, sitename + '_metadata' + '.pkl'), 'wb') as f:
+ pickle.dump(metadata, f)
\ No newline at end of file
diff --git a/SDS_preprocess.py b/SDS_preprocess.py
new file mode 100644
index 0000000..c98c501
--- /dev/null
+++ b/SDS_preprocess.py
@@ -0,0 +1,667 @@
+"""This module contains all the functions needed to preprocess the satellite images: creating a
+cloud mask and pansharpening/downsampling the images.
+
+ Author: Kilian Vos, Water Research Laboratory, University of New South Wales
+"""
+
+# Initial settings
+import os
+import numpy as np
+import matplotlib.pyplot as plt
+from osgeo import gdal, ogr, osr
+import skimage.transform as transform
+import skimage.morphology as morphology
+import sklearn.decomposition as decomposition
+import skimage.exposure as exposure
+from pylab import ginput
+import pickle
+import pdb
+import SDS_tools
+
+# Functions
+
+def create_cloud_mask(im_qa, satname):
+ """
+ Creates a cloud mask from the image containing the QA band information.
+
+ KV WRL 2018
+
+ Arguments:
+ -----------
+ im_qa: np.array
+ Image containing the QA band
+ satname: string
+ short name for the satellite (L8, L7, S2)
+
+ Returns:
+ -----------
+ cloud_mask : np.ndarray of booleans
+ A boolean array with True where the cloud are present
+ """
+
+ # convert QA bits depending on the satellite mission
+ if satname == 'L8':
+ cloud_values = [2800, 2804, 2808, 2812, 6896, 6900, 6904, 6908]
+ elif satname == 'L7' or satname == 'L5' or satname == 'L4':
+ cloud_values = [752, 756, 760, 764]
+ elif satname == 'S2':
+ cloud_values = [1024, 2048] # 1024 = dense cloud, 2048 = cirrus clouds
+
+ # find which pixels have bits corresponding to cloud values
+ cloud_mask = np.isin(im_qa, cloud_values)
+
+ # remove isolated cloud pixels (there are some in the swash zone and they can cause problems)
+ if sum(sum(cloud_mask)) > 0 and sum(sum(~cloud_mask)) > 0:
+ morphology.remove_small_objects(cloud_mask, min_size=10, connectivity=1, in_place=True)
+
+ return cloud_mask
+
+def hist_match(source, template):
+ """
+ Adjust the pixel values of a grayscale image such that its histogram matches that of a
+ target image.
+
+ Arguments:
+ -----------
+ source: np.array
+ Image to transform; the histogram is computed over the flattened
+ array
+ template: np.array
+ Template image; can have different dimensions to source
+ Returns:
+ -----------
+ matched: np.array
+ The transformed output image
+ """
+
+ oldshape = source.shape
+ source = source.ravel()
+ template = template.ravel()
+
+ # get the set of unique pixel values and their corresponding indices and
+ # counts
+ s_values, bin_idx, s_counts = np.unique(source, return_inverse=True,
+ return_counts=True)
+ t_values, t_counts = np.unique(template, return_counts=True)
+
+ # take the cumsum of the counts and normalize by the number of pixels to
+ # get the empirical cumulative distribution functions for the source and
+ # template images (maps pixel value --> quantile)
+ s_quantiles = np.cumsum(s_counts).astype(np.float64)
+ s_quantiles /= s_quantiles[-1]
+ t_quantiles = np.cumsum(t_counts).astype(np.float64)
+ t_quantiles /= t_quantiles[-1]
+
+ # interpolate linearly to find the pixel values in the template image
+ # that correspond most closely to the quantiles in the source image
+ interp_t_values = np.interp(s_quantiles, t_quantiles, t_values)
+
+ return interp_t_values[bin_idx].reshape(oldshape)
+
+def pansharpen(im_ms, im_pan, cloud_mask):
+ """
+ Pansharpens a multispectral image (3D), using the panchromatic band (2D) and a cloud mask.
+ A PCA is applied to the image, then the 1st PC is replaced with the panchromatic band.
+
+ KV WRL 2018
+
+ Arguments:
+ -----------
+ im_ms: np.array
+ Multispectral image to pansharpen (3D)
+ im_pan: np.array
+ Panchromatic band (2D)
+ cloud_mask: np.array
+ 2D cloud mask with True where cloud pixels are
+
+ Returns:
+ -----------
+ im_ms_ps: np.ndarray
+ Pansharpened multisoectral image (3D)
+ """
+
+ # reshape image into vector and apply cloud mask
+ vec = im_ms.reshape(im_ms.shape[0] * im_ms.shape[1], im_ms.shape[2])
+ vec_mask = cloud_mask.reshape(im_ms.shape[0] * im_ms.shape[1])
+ vec = vec[~vec_mask, :]
+ # apply PCA to RGB bands
+ pca = decomposition.PCA()
+ vec_pcs = pca.fit_transform(vec)
+
+ # replace 1st PC with pan band (after matching histograms)
+ vec_pan = im_pan.reshape(im_pan.shape[0] * im_pan.shape[1])
+ vec_pan = vec_pan[~vec_mask]
+ vec_pcs[:,0] = hist_match(vec_pan, vec_pcs[:,0])
+ vec_ms_ps = pca.inverse_transform(vec_pcs)
+
+ # reshape vector into image
+ vec_ms_ps_full = np.ones((len(vec_mask), im_ms.shape[2])) * np.nan
+ vec_ms_ps_full[~vec_mask,:] = vec_ms_ps
+ im_ms_ps = vec_ms_ps_full.reshape(im_ms.shape[0], im_ms.shape[1], im_ms.shape[2])
+
+ return im_ms_ps
+
+
+def rescale_image_intensity(im, cloud_mask, prob_high):
+ """
+ Rescales the intensity of an image (multispectral or single band) by applying
+ a cloud mask and clipping the prob_high upper percentile. This functions allows
+ to stretch the contrast of an image for visualisation purposes.
+
+ KV WRL 2018
+
+ Arguments:
+ -----------
+ im: np.array
+ Image to rescale, can be 3D (multispectral) or 2D (single band)
+ cloud_mask: np.array
+ 2D cloud mask with True where cloud pixels are
+ prob_high: float
+ probability of exceedence used to calculate the upper percentile
+
+ Returns:
+ -----------
+ im_adj: np.array
+ The rescaled image
+ """
+
+ # lower percentile is set to 0
+ prc_low = 0
+
+ # reshape the 2D cloud mask into a 1D vector
+ vec_mask = cloud_mask.reshape(im.shape[0] * im.shape[1])
+
+ # if image contains several bands, stretch the contrast for each band
+ if len(im.shape) > 2:
+ # reshape into a vector
+ vec = im.reshape(im.shape[0] * im.shape[1], im.shape[2])
+ # initiliase with NaN values
+ vec_adj = np.ones((len(vec_mask), im.shape[2])) * np.nan
+ # loop through the bands
+ for i in range(im.shape[2]):
+ # find the higher percentile (based on prob)
+ prc_high = np.percentile(vec[~vec_mask, i], prob_high)
+ # clip the image around the 2 percentiles and rescale the contrast
+ vec_rescaled = exposure.rescale_intensity(vec[~vec_mask, i],
+ in_range=(prc_low, prc_high))
+ vec_adj[~vec_mask,i] = vec_rescaled
+ # reshape into image
+ im_adj = vec_adj.reshape(im.shape[0], im.shape[1], im.shape[2])
+
+ # if image only has 1 bands (grayscale image)
+ else:
+ vec = im.reshape(im.shape[0] * im.shape[1])
+ vec_adj = np.ones(len(vec_mask)) * np.nan
+ prc_high = np.percentile(vec[~vec_mask], prob_high)
+ vec_rescaled = exposure.rescale_intensity(vec[~vec_mask], in_range=(prc_low, prc_high))
+ vec_adj[~vec_mask] = vec_rescaled
+ im_adj = vec_adj.reshape(im.shape[0], im.shape[1])
+
+ return im_adj
+
+def preprocess_single(fn, satname):
+ """
+ Creates a cloud mask using the QA band and performs pansharpening/down-sampling of the image.
+
+ KV WRL 2018
+
+ Arguments:
+ -----------
+ fn: str or list of str
+ filename of the .TIF file containing the image
+ for L7, L8 and S2 there is a filename for the bands at different resolutions
+ satname: str
+ name of the satellite mission (e.g., 'L5')
+
+ Returns:
+ -----------
+ im_ms: np.array
+ 3D array containing the pansharpened/down-sampled bands (B,G,R,NIR,SWIR1)
+ georef: np.array
+ vector of 6 elements [Xtr, Xscale, Xshear, Ytr, Yshear, Yscale] defining the
+ coordinates of the top-left pixel of the image
+ cloud_mask: np.array
+ 2D cloud mask with True where cloud pixels are
+
+ """
+
+ #=============================================================================================#
+ # L5 images
+ #=============================================================================================#
+ if satname == 'L5':
+
+ # read all bands
+ data = gdal.Open(fn, gdal.GA_ReadOnly)
+ georef = np.array(data.GetGeoTransform())
+ bands = [data.GetRasterBand(k + 1).ReadAsArray() for k in range(data.RasterCount)]
+ im_ms = np.stack(bands, 2)
+
+ # down-sample to 15 m (half of the original pixel size)
+ nrows = im_ms.shape[0]*2
+ ncols = im_ms.shape[1]*2
+
+ # create cloud mask
+ im_qa = im_ms[:,:,5]
+ im_ms = im_ms[:,:,:-1]
+ cloud_mask = create_cloud_mask(im_qa, satname)
+
+ # resize the image using bilinear interpolation (order 1)
+ im_ms = transform.resize(im_ms,(nrows, ncols), order=1, preserve_range=True,
+ mode='constant')
+ # resize the image using nearest neighbour interpolation (order 0)
+ cloud_mask = transform.resize(cloud_mask, (nrows, ncols), order=0, preserve_range=True,
+ mode='constant').astype('bool_')
+
+ # adjust georeferencing vector to the new image size
+ # scale becomes 15m and the origin is adjusted to the center of new top left pixel
+ georef[1] = 15
+ georef[5] = -15
+ georef[0] = georef[0] + 7.5
+ georef[3] = georef[3] - 7.5
+
+ # check if -inf or nan values on any band and add to cloud mask
+ for k in range(im_ms.shape[2]):
+ im_inf = np.isin(im_ms[:,:,k], -np.inf)
+ im_nan = np.isnan(im_ms[:,:,k])
+ cloud_mask = np.logical_or(np.logical_or(cloud_mask, im_inf), im_nan)
+
+ # calculate cloud cover
+ cloud_cover = sum(sum(cloud_mask.astype(int)))/(cloud_mask.shape[0]*cloud_mask.shape[1])
+
+ #=============================================================================================#
+ # L7 images
+ #=============================================================================================#
+ elif satname == 'L7':
+
+ # read pan image
+ fn_pan = fn[0]
+ data = gdal.Open(fn_pan, gdal.GA_ReadOnly)
+ georef = np.array(data.GetGeoTransform())
+ bands = [data.GetRasterBand(k + 1).ReadAsArray() for k in range(data.RasterCount)]
+ im_pan = np.stack(bands, 2)[:,:,0]
+
+ # size of pan image
+ nrows = im_pan.shape[0]
+ ncols = im_pan.shape[1]
+
+ # read ms image
+ fn_ms = fn[1]
+ data = gdal.Open(fn_ms, gdal.GA_ReadOnly)
+ bands = [data.GetRasterBand(k + 1).ReadAsArray() for k in range(data.RasterCount)]
+ im_ms = np.stack(bands, 2)
+
+ # create cloud mask
+ im_qa = im_ms[:,:,5]
+ cloud_mask = create_cloud_mask(im_qa, satname)
+
+ # resize the image using bilinear interpolation (order 1)
+ im_ms = im_ms[:,:,:5]
+ im_ms = transform.resize(im_ms,(nrows, ncols), order=1, preserve_range=True,
+ mode='constant')
+ # resize the image using nearest neighbour interpolation (order 0)
+ cloud_mask = transform.resize(cloud_mask, (nrows, ncols), order=0, preserve_range=True,
+ mode='constant').astype('bool_')
+ # check if -inf or nan values on any band and eventually add those pixels to cloud mask
+ for k in range(im_ms.shape[2]+1):
+ if k == 5:
+ im_inf = np.isin(im_pan, -np.inf)
+ im_nan = np.isnan(im_pan)
+ else:
+ im_inf = np.isin(im_ms[:,:,k], -np.inf)
+ im_nan = np.isnan(im_ms[:,:,k])
+ cloud_mask = np.logical_or(np.logical_or(cloud_mask, im_inf), im_nan)
+
+ # calculate cloud cover
+ cloud_cover = sum(sum(cloud_mask.astype(int)))/(cloud_mask.shape[0]*cloud_mask.shape[1])
+
+ # pansharpen Green, Red, NIR (where there is overlapping with pan band in L7)
+ try:
+ im_ms_ps = pansharpen(im_ms[:,:,[1,2,3]], im_pan, cloud_mask)
+ except: # if pansharpening fails, keep downsampled bands (for long runs)
+ im_ms_ps = im_ms[:,:,[1,2,3]]
+ # add downsampled Blue and SWIR1 bands
+ im_ms_ps = np.append(im_ms[:,:,[0]], im_ms_ps, axis=2)
+ im_ms_ps = np.append(im_ms_ps, im_ms[:,:,[4]], axis=2)
+
+ im_ms = im_ms_ps.copy()
+
+ #=============================================================================================#
+ # L8 images
+ #=============================================================================================#
+ elif satname == 'L8':
+
+ # read pan image
+ fn_pan = fn[0]
+ data = gdal.Open(fn_pan, gdal.GA_ReadOnly)
+ georef = np.array(data.GetGeoTransform())
+ bands = [data.GetRasterBand(k + 1).ReadAsArray() for k in range(data.RasterCount)]
+ im_pan = np.stack(bands, 2)[:,:,0]
+
+ # size of pan image
+ nrows = im_pan.shape[0]
+ ncols = im_pan.shape[1]
+
+ # read ms image
+ fn_ms = fn[1]
+ data = gdal.Open(fn_ms, gdal.GA_ReadOnly)
+ bands = [data.GetRasterBand(k + 1).ReadAsArray() for k in range(data.RasterCount)]
+ im_ms = np.stack(bands, 2)
+
+ # create cloud mask
+ im_qa = im_ms[:,:,5]
+ cloud_mask = create_cloud_mask(im_qa, satname)
+
+ # resize the image using bilinear interpolation (order 1)
+ im_ms = im_ms[:,:,:5]
+ im_ms = transform.resize(im_ms,(nrows, ncols), order=1, preserve_range=True,
+ mode='constant')
+ # resize the image using nearest neighbour interpolation (order 0)
+ cloud_mask = transform.resize(cloud_mask, (nrows, ncols), order=0, preserve_range=True,
+ mode='constant').astype('bool_')
+ # check if -inf or nan values on any band and eventually add those pixels to cloud mask
+ for k in range(im_ms.shape[2]+1):
+ if k == 5:
+ im_inf = np.isin(im_pan, -np.inf)
+ im_nan = np.isnan(im_pan)
+ else:
+ im_inf = np.isin(im_ms[:,:,k], -np.inf)
+ im_nan = np.isnan(im_ms[:,:,k])
+ cloud_mask = np.logical_or(np.logical_or(cloud_mask, im_inf), im_nan)
+
+ # calculate cloud cover
+ cloud_cover = sum(sum(cloud_mask.astype(int)))/(cloud_mask.shape[0]*cloud_mask.shape[1])
+
+ # pansharpen Blue, Green, Red (where there is overlapping with pan band in L8)
+ try:
+ im_ms_ps = pansharpen(im_ms[:,:,[0,1,2]], im_pan, cloud_mask)
+ except: # if pansharpening fails, keep downsampled bands (for long runs)
+ im_ms_ps = im_ms[:,:,[0,1,2]]
+ # add downsampled NIR and SWIR1 bands
+ im_ms_ps = np.append(im_ms_ps, im_ms[:,:,[3,4]], axis=2)
+
+ im_ms = im_ms_ps.copy()
+
+ #=============================================================================================#
+ # S2 images
+ #=============================================================================================#
+ if satname == 'S2':
+
+ # read 10m bands (R,G,B,NIR)
+ fn10 = fn[0]
+ data = gdal.Open(fn10, gdal.GA_ReadOnly)
+ georef = np.array(data.GetGeoTransform())
+ bands = [data.GetRasterBand(k + 1).ReadAsArray() for k in range(data.RasterCount)]
+ im10 = np.stack(bands, 2)
+ im10 = im10/10000 # TOA scaled to 10000
+
+ # if image contains only zeros (can happen with S2), skip the image
+ if sum(sum(sum(im10))) < 1:
+ im_ms = []
+ georef = []
+ # skip the image by giving it a full cloud_mask
+ cloud_mask = np.ones((im10.shape[0],im10.shape[1])).astype('bool')
+ return im_ms, georef, cloud_mask
+
+ # size of 10m bands
+ nrows = im10.shape[0]
+ ncols = im10.shape[1]
+
+ # read 20m band (SWIR1)
+ fn20 = fn[1]
+ data = gdal.Open(fn20, gdal.GA_ReadOnly)
+ bands = [data.GetRasterBand(k + 1).ReadAsArray() for k in range(data.RasterCount)]
+ im20 = np.stack(bands, 2)
+ im20 = im20[:,:,0]
+ im20 = im20/10000 # TOA scaled to 10000
+
+ # resize the image using bilinear interpolation (order 1)
+ im_swir = transform.resize(im20, (nrows, ncols), order=1, preserve_range=True,
+ mode='constant')
+ im_swir = np.expand_dims(im_swir, axis=2)
+
+ # append down-sampled SWIR1 band to the other 10m bands
+ im_ms = np.append(im10, im_swir, axis=2)
+
+ # create cloud mask using 60m QA band (not as good as Landsat cloud cover)
+ fn60 = fn[2]
+ data = gdal.Open(fn60, gdal.GA_ReadOnly)
+ bands = [data.GetRasterBand(k + 1).ReadAsArray() for k in range(data.RasterCount)]
+ im60 = np.stack(bands, 2)
+ im_qa = im60[:,:,0]
+ cloud_mask = create_cloud_mask(im_qa, satname)
+ # resize the cloud mask using nearest neighbour interpolation (order 0)
+ cloud_mask = transform.resize(cloud_mask,(nrows, ncols), order=0, preserve_range=True,
+ mode='constant')
+ # check if -inf or nan values on any band and add to cloud mask
+ for k in range(im_ms.shape[2]):
+ im_inf = np.isin(im_ms[:,:,k], -np.inf)
+ im_nan = np.isnan(im_ms[:,:,k])
+ cloud_mask = np.logical_or(np.logical_or(cloud_mask, im_inf), im_nan)
+
+ # calculate cloud cover
+ cloud_cover = sum(sum(cloud_mask.astype(int)))/(cloud_mask.shape[0]*cloud_mask.shape[1])
+
+ return im_ms, georef, cloud_mask
+
+
+def create_jpg(im_ms, cloud_mask, date, satname, filepath):
+ """
+ Saves a .jpg file with the RGB image as well as the NIR and SWIR1 grayscale images.
+
+ KV WRL 2018
+
+ Arguments:
+ -----------
+ im_ms: np.array
+ 3D array containing the pansharpened/down-sampled bands (B,G,R,NIR,SWIR1)
+ cloud_mask: np.array
+ 2D cloud mask with True where cloud pixels are
+ date: str
+ String containing the date at which the image was acquired
+ satname: str
+ name of the satellite mission (e.g., 'L5')
+
+ Returns:
+ -----------
+ Saves a .jpg image corresponding to the preprocessed satellite image
+
+ """
+
+ # rescale image intensity for display purposes
+ im_RGB = rescale_image_intensity(im_ms[:,:,[2,1,0]], cloud_mask, 99.9)
+ im_NIR = rescale_image_intensity(im_ms[:,:,3], cloud_mask, 99.9)
+ im_SWIR = rescale_image_intensity(im_ms[:,:,4], cloud_mask, 99.9)
+
+ # make figure
+ fig = plt.figure()
+ fig.set_size_inches([18,9])
+ fig.set_tight_layout(True)
+ # RGB
+ plt.subplot(131)
+ plt.axis('off')
+ plt.imshow(im_RGB)
+ plt.title(date + ' ' + satname, fontsize=16)
+ # NIR
+ plt.subplot(132)
+ plt.axis('off')
+ plt.imshow(im_NIR, cmap='seismic')
+ plt.title('Near Infrared', fontsize=16)
+ # SWIR
+ plt.subplot(133)
+ plt.axis('off')
+ plt.imshow(im_SWIR, cmap='seismic')
+ plt.title('Short-wave Infrared', fontsize=16)
+ # save figure
+ plt.rcParams['savefig.jpeg_quality'] = 100
+ fig.savefig(os.path.join(filepath,
+ date + '_' + satname + '.jpg'), dpi=150)
+ plt.close()
+
+
+def preprocess_all_images(metadata, settings):
+ """
+ Saves a .jpg image for all the file contained in metadata.
+
+ KV WRL 2018
+
+ Arguments:
+ -----------
+ sitename: str
+ name of the site (and corresponding folder)
+ metadata: dict
+ contains all the information about the satellite images that were downloaded
+ cloud_thresh: float
+ maximum fraction of cloud cover allowed in the images
+
+ Returns:
+ -----------
+ Generates .jpg files for all the satellite images avaialble
+
+ """
+
+ sitename = settings['sitename']
+ cloud_thresh = settings['cloud_thresh']
+
+ # create subfolder to store the jpg files
+ filepath_jpg = os.path.join(os.getcwd(), 'data', sitename, 'jpg_files', 'preprocessed')
+ try:
+ os.makedirs(filepath_jpg)
+ except:
+ print('')
+
+ # loop through satellite list
+ for satname in metadata.keys():
+ # access the images
+ if satname == 'L5':
+ # access downloaded Landsat 5 images
+ filepath = os.path.join(os.getcwd(), 'data', sitename, satname, '30m')
+ filenames = os.listdir(filepath)
+ elif satname == 'L7':
+ # access downloaded Landsat 7 images
+ filepath_pan = os.path.join(os.getcwd(), 'data', sitename, 'L7', 'pan')
+ filepath_ms = os.path.join(os.getcwd(), 'data', sitename, 'L7', 'ms')
+ filenames_pan = os.listdir(filepath_pan)
+ filenames_ms = os.listdir(filepath_ms)
+ if (not len(filenames_pan) == len(filenames_ms)):
+ raise 'error: not the same amount of files for pan and ms'
+ filepath = [filepath_pan, filepath_ms]
+ filenames = filenames_pan
+ elif satname == 'L8':
+ # access downloaded Landsat 7 images
+ filepath_pan = os.path.join(os.getcwd(), 'data', sitename, 'L8', 'pan')
+ filepath_ms = os.path.join(os.getcwd(), 'data', sitename, 'L8', 'ms')
+ filenames_pan = os.listdir(filepath_pan)
+ filenames_ms = os.listdir(filepath_ms)
+ if (not len(filenames_pan) == len(filenames_ms)):
+ raise 'error: not the same amount of files for pan and ms'
+ filepath = [filepath_pan, filepath_ms]
+ filenames = filenames_pan
+ elif satname == 'S2':
+ # access downloaded Sentinel 2 images
+ filepath10 = os.path.join(os.getcwd(), 'data', sitename, satname, '10m')
+ filenames10 = os.listdir(filepath10)
+ filepath20 = os.path.join(os.getcwd(), 'data', sitename, satname, '20m')
+ filenames20 = os.listdir(filepath20)
+ filepath60 = os.path.join(os.getcwd(), 'data', sitename, satname, '60m')
+ filenames60 = os.listdir(filepath60)
+ if (not len(filenames10) == len(filenames20)) or (not len(filenames20) == len(filenames60)):
+ raise 'error: not the same amount of files for 10, 20 and 60 m'
+ filepath = [filepath10, filepath20, filepath60]
+ filenames = filenames10
+
+ # loop through images
+ for i in range(len(filenames)):
+ # image filename
+ fn = SDS_tools.get_filenames(filenames[i],filepath, satname)
+ # preprocess image (cloud mask + pansharpening/downsampling)
+ im_ms, georef, cloud_mask = preprocess_single(fn, satname)
+ # calculate cloud cover
+ cloud_cover = np.divide(sum(sum(cloud_mask.astype(int))),
+ (cloud_mask.shape[0]*cloud_mask.shape[1]))
+ # skip image if cloud cover is above threshold
+ if cloud_cover > cloud_thresh:
+ continue
+ # save .jpg with date and satellite in the title
+ date = filenames[i][:10]
+ create_jpg(im_ms, cloud_mask, date, satname, filepath_jpg)
+
+def get_reference_sl(metadata, settings):
+
+ sitename = settings['sitename']
+
+ # check if reference shoreline already exists
+ filepath = os.path.join(os.getcwd(), 'data', sitename)
+ filename = sitename + '_ref_sl.pkl'
+ if filename in os.listdir(filepath):
+ print('Reference shoreline already exists and was loaded')
+ with open(os.path.join(filepath, sitename + '_ref_sl.pkl'), 'rb') as f:
+ refsl = pickle.load(f)
+ return refsl
+
+ else:
+ satname = 'S2'
+ # access downloaded Sentinel 2 images
+ filepath10 = os.path.join(os.getcwd(), 'data', sitename, satname, '10m')
+ filenames10 = os.listdir(filepath10)
+ filepath20 = os.path.join(os.getcwd(), 'data', sitename, satname, '20m')
+ filenames20 = os.listdir(filepath20)
+ filepath60 = os.path.join(os.getcwd(), 'data', sitename, satname, '60m')
+ filenames60 = os.listdir(filepath60)
+ if (not len(filenames10) == len(filenames20)) or (not len(filenames20) == len(filenames60)):
+ raise 'error: not the same amount of files for 10, 20 and 60 m'
+ for i in range(len(filenames10)):
+ # image filename
+ fn = [os.path.join(filepath10, filenames10[i]),
+ os.path.join(filepath20, filenames20[i]),
+ os.path.join(filepath60, filenames60[i])]
+ # preprocess image (cloud mask + pansharpening/downsampling)
+ im_ms, georef, cloud_mask = preprocess_single(fn, satname)
+ # calculate cloud cover
+ cloud_cover = np.divide(sum(sum(cloud_mask.astype(int))),
+ (cloud_mask.shape[0]*cloud_mask.shape[1]))
+ # skip image if cloud cover is above threshold
+ if cloud_cover > settings['cloud_thresh']:
+ continue
+ # rescale image intensity for display purposes
+ im_RGB = rescale_image_intensity(im_ms[:,:,[2,1,0]], cloud_mask, 99.9)
+ # make figure
+ fig = plt.figure()
+ fig.set_size_inches([18,9])
+ fig.set_tight_layout(True)
+ # RGB
+ plt.axis('off')
+ plt.imshow(im_RGB)
+ plt.title('click if image is not clear enough to digitize the shoreline.\n' +
+ 'Otherwise click on and start digitizing the shoreline.\n' +
+ 'When finished digitizing the shoreline click on the scroll wheel ' +
+ '(middle click).', fontsize=14)
+ plt.text(0, 0.9, 'keep', size=16, ha="left", va="top",
+ transform=plt.gca().transAxes,
+ bbox=dict(boxstyle="square", ec='k',fc='w'))
+ plt.text(1, 0.9, 'skip', size=16, ha="right", va="top",
+ transform=plt.gca().transAxes,
+ bbox=dict(boxstyle="square", ec='k',fc='w'))
+ mng = plt.get_current_fig_manager()
+ mng.window.showMaximized()
+ # let user click on the image once
+ pt_keep = ginput(n=1, timeout=100, show_clicks=True)
+ pt_keep = np.array(pt_keep)
+ # if clicks next to , show another image
+ if pt_keep[0][0] > im_ms.shape[1]/2:
+ plt.close()
+ continue
+ else:
+ # let user click on the shoreline
+ pts = ginput(n=5000, timeout=100000, show_clicks=True)
+ pts_pix = np.array(pts)
+ plt.close()
+ # convert image coordinates to world coordinates
+ pts_world = SDS_tools.convert_pix2world(pts_pix[:,[1,0]], georef)
+ image_epsg = metadata[satname]['epsg'][i]
+ pts_coords = SDS_tools.convert_epsg(pts_world, image_epsg, settings['output_epsg'])
+ with open(os.path.join(filepath, sitename + '_ref_sl.pkl'), 'wb') as f:
+ pickle.dump(pts_coords, f)
+ print('Reference shoreline has been saved')
+ break
+
+ return pts_coords
\ No newline at end of file
diff --git a/SDS_shoreline.py b/SDS_shoreline.py
new file mode 100644
index 0000000..b583aab
--- /dev/null
+++ b/SDS_shoreline.py
@@ -0,0 +1,604 @@
+"""This module contains all the functions needed for extracting satellite-derived shorelines (SDS)
+
+ Author: Kilian Vos, Water Research Laboratory, University of New South Wales
+"""
+
+# Initial settings
+import os
+import numpy as np
+import matplotlib.pyplot as plt
+import pdb
+
+# other modules
+from osgeo import gdal, ogr, osr
+import scipy.interpolate as interpolate
+from datetime import datetime, timedelta
+import matplotlib.patches as mpatches
+import matplotlib.lines as mlines
+import matplotlib.cm as cm
+from matplotlib import gridspec
+from pylab import ginput
+import pickle
+
+# image processing modules
+import skimage.filters as filters
+import skimage.exposure as exposure
+import skimage.transform as transform
+import sklearn.decomposition as decomposition
+import skimage.measure as measure
+import skimage.morphology as morphology
+
+# machine learning modules
+from sklearn.externals import joblib
+from shapely.geometry import LineString
+
+import SDS_tools, SDS_preprocess
+np.seterr(all='ignore') # raise/ignore divisions by 0 and nans
+
+
+def nd_index(im1, im2, cloud_mask):
+ """
+ Computes normalised difference index on 2 images (2D), given a cloud mask (2D).
+
+ KV WRL 2018
+
+ Arguments:
+ -----------
+ im1, im2: np.array
+ Images (2D) with which to calculate the ND index
+ cloud_mask: np.array
+ 2D cloud mask with True where cloud pixels are
+
+ Returns: -----------
+ im_nd: np.array
+ Image (2D) containing the ND index
+ """
+
+ # reshape the cloud mask
+ vec_mask = cloud_mask.reshape(im1.shape[0] * im1.shape[1])
+ # initialise with NaNs
+ vec_nd = np.ones(len(vec_mask)) * np.nan
+ # reshape the two images
+ vec1 = im1.reshape(im1.shape[0] * im1.shape[1])
+ vec2 = im2.reshape(im2.shape[0] * im2.shape[1])
+ # compute the normalised difference index
+ temp = np.divide(vec1[~vec_mask] - vec2[~vec_mask],
+ vec1[~vec_mask] + vec2[~vec_mask])
+ vec_nd[~vec_mask] = temp
+ # reshape into image
+ im_nd = vec_nd.reshape(im1.shape[0], im1.shape[1])
+
+ return im_nd
+
+def classify_image_NN(im_ms_ps, im_pan, cloud_mask, min_beach_size):
+ """
+ Classifies every pixel in the image in one of 4 classes:
+ - sand --> label = 1
+ - whitewater (breaking waves and swash) --> label = 2
+ - water --> label = 3
+ - other (vegetation, buildings, rocks...) --> label = 0
+
+ The classifier is a Neural Network, trained with 7000 pixels for the class SAND and 1500
+ pixels for each of the other classes. This is because the class of interest for my application
+ is SAND and I wanted to minimize the classification error for that class.
+
+ KV WRL 2018
+
+ Arguments:
+ -----------
+ im_ms_ps: np.array
+ Pansharpened RGB + downsampled NIR and SWIR
+ im_pan:
+ Panchromatic band
+ cloud_mask: np.array
+ 2D cloud mask with True where cloud pixels are
+ plot_bool: boolean
+ True if plot is wanted
+
+ Returns: -----------
+ im_classif: np.array
+ 2D image containing labels
+ im_labels: np.array of booleans
+ 3D image containing a boolean image for each class (im_classif == label)
+
+ """
+
+ # load classifier
+ clf = joblib.load('.\\classifiers\\NN_4classes_withpan.pkl')
+
+ # calculate features
+ n_features = 10
+ im_features = np.zeros((im_ms_ps.shape[0], im_ms_ps.shape[1], n_features))
+ im_features[:,:,[0,1,2,3,4]] = im_ms_ps
+ im_features[:,:,5] = im_pan
+ im_features[:,:,6] = nd_index(im_ms_ps[:,:,3], im_ms_ps[:,:,1], cloud_mask, False) # (NIR-G)
+ im_features[:,:,7] = nd_index(im_ms_ps[:,:,3], im_ms_ps[:,:,2], cloud_mask, False) # ND(NIR-R)
+ im_features[:,:,8] = nd_index(im_ms_ps[:,:,0], im_ms_ps[:,:,2], cloud_mask, False) # ND(B-R)
+ im_features[:,:,9] = nd_index(im_ms_ps[:,:,4], im_ms_ps[:,:,1], cloud_mask, False) # ND(SWIR-G)
+ # remove NaNs and clouds
+ vec_features = im_features.reshape((im_ms_ps.shape[0] * im_ms_ps.shape[1], n_features))
+ vec_cloud = cloud_mask.reshape(cloud_mask.shape[0]*cloud_mask.shape[1])
+ vec_nan = np.any(np.isnan(vec_features), axis=1)
+ vec_mask = np.logical_or(vec_cloud, vec_nan)
+ vec_features = vec_features[~vec_mask, :]
+ # predict with NN classifier
+ labels = clf.predict(vec_features)
+ # recompose image
+ vec_classif = np.zeros((cloud_mask.shape[0]*cloud_mask.shape[1]))
+ vec_classif[~vec_mask] = labels
+ im_classif = vec_classif.reshape((im_ms_ps.shape[0], im_ms_ps.shape[1]))
+
+ # labels
+ im_sand = im_classif == 1
+ # remove small patches of sand
+ im_sand = morphology.remove_small_objects(im_sand, min_size=min_beach_size, connectivity=2)
+ im_swash = im_classif == 2
+ im_water = im_classif == 3
+ im_labels = np.stack((im_sand,im_swash,im_water), axis=-1)
+
+ return im_classif, im_labels
+
+
+def classify_image_NN_nopan(im_ms_ps, cloud_mask, min_beach_size):
+ """
+ To be used for multispectral images that do not have a panchromatic band (L5 and S2).
+ Classifies every pixel in the image in one of 4 classes:
+ - sand --> label = 1
+ - whitewater (breaking waves and swash) --> label = 2
+ - water --> label = 3
+ - other (vegetation, buildings, rocks...) --> label = 0
+
+ The classifier is a Neural Network, trained with 7000 pixels for the class SAND and 1500
+ pixels for each of the other classes. This is because the class of interest for my application
+ is SAND and I wanted to minimize the classification error for that class.
+
+ KV WRL 2018
+
+ Arguments:
+ -----------
+ im_ms_ps: np.array
+ Pansharpened RGB + downsampled NIR and SWIR
+ im_pan:
+ Panchromatic band
+ cloud_mask: np.array
+ 2D cloud mask with True where cloud pixels are
+
+ Returns: -----------
+ im_classif: np.ndarray
+ 2D image containing labels
+ im_labels: np.ndarray of booleans
+ 3D image containing a boolean image for each class (im_classif == label)
+
+ """
+
+ # load classifier
+ clf = joblib.load('.\\classifiers\\NN_4classes_nopan.pkl')
+
+ # calculate features
+ n_features = 9
+ im_features = np.zeros((im_ms_ps.shape[0], im_ms_ps.shape[1], n_features))
+ im_features[:,:,[0,1,2,3,4]] = im_ms_ps
+ im_features[:,:,5] = nd_index(im_ms_ps[:,:,3], im_ms_ps[:,:,1], cloud_mask) # (NIR-G)
+ im_features[:,:,6] = nd_index(im_ms_ps[:,:,3], im_ms_ps[:,:,2], cloud_mask) # ND(NIR-R)
+ im_features[:,:,7] = nd_index(im_ms_ps[:,:,0], im_ms_ps[:,:,2], cloud_mask) # ND(B-R)
+ im_features[:,:,8] = nd_index(im_ms_ps[:,:,4], im_ms_ps[:,:,1], cloud_mask) # ND(SWIR-G)
+ # remove NaNs and clouds
+ vec_features = im_features.reshape((im_ms_ps.shape[0] * im_ms_ps.shape[1], n_features))
+ vec_cloud = cloud_mask.reshape(cloud_mask.shape[0]*cloud_mask.shape[1])
+ vec_nan = np.any(np.isnan(vec_features), axis=1)
+ vec_mask = np.logical_or(vec_cloud, vec_nan)
+ vec_features = vec_features[~vec_mask, :]
+ # predict with NN classifier
+ labels = clf.predict(vec_features)
+
+ # recompose image
+ vec_classif = np.zeros((cloud_mask.shape[0]*cloud_mask.shape[1]))
+ vec_classif[~vec_mask] = labels
+ im_classif = vec_classif.reshape((im_ms_ps.shape[0], im_ms_ps.shape[1]))
+
+ # labels
+ im_sand = im_classif == 1
+ # remove small patches of sand
+ im_sand = morphology.remove_small_objects(im_sand, min_size=min_beach_size, connectivity=2)
+ im_swash = im_classif == 2
+ im_water = im_classif == 3
+ im_labels = np.stack((im_sand,im_swash,im_water), axis=-1)
+
+ return im_classif, im_labels
+
+def find_wl_contours1(im_ndwi, cloud_mask):
+ """
+ Traditional method for shorelien detection.
+ Finds the water line by thresholding the Normalized Difference Water Index and applying
+ the Marching Squares Algorithm to contour the iso-value corresponding to the threshold.
+
+ KV WRL 2018
+
+ Arguments:
+ -----------
+ im_ndwi: np.ndarray
+ Image (2D) with the NDWI (water index)
+ cloud_mask: np.ndarray
+ 2D cloud mask with True where cloud pixels are
+
+ Returns: -----------
+ contours_wl: list of np.arrays
+ contains the (row,column) coordinates of the contour lines
+
+ """
+
+ # reshape image to vector
+ vec_ndwi = im_ndwi.reshape(im_ndwi.shape[0] * im_ndwi.shape[1])
+ vec_mask = cloud_mask.reshape(cloud_mask.shape[0] * cloud_mask.shape[1])
+ vec = vec_ndwi[~vec_mask]
+ # apply otsu's threshold
+ vec = vec[~np.isnan(vec)]
+ t_otsu = filters.threshold_otsu(vec)
+ # use Marching Squares algorithm to detect contours on ndwi image
+ contours = measure.find_contours(im_ndwi, t_otsu)
+
+ # remove contours that have nans (due to cloud pixels in the contour)
+ contours_nonans = []
+ for k in range(len(contours)):
+ if np.any(np.isnan(contours[k])):
+ index_nan = np.where(np.isnan(contours[k]))[0]
+ contours_temp = np.delete(contours[k], index_nan, axis=0)
+ if len(contours_temp) > 1:
+ contours_nonans.append(contours_temp)
+ else:
+ contours_nonans.append(contours[k])
+ contours = contours_nonans
+
+ return contours
+
+def find_wl_contours2(im_ms_ps, im_labels, cloud_mask, buffer_size):
+ """
+ New robust method for extracting shorelines. Incorporates the classification component to
+ refube the treshold and make it specific to the sand/water interface.
+
+ KV WRL 2018
+
+ Arguments:
+ -----------
+ im_ms_ps: np.array
+ Pansharpened RGB + downsampled NIR and SWIR
+ im_labels: np.array
+ 3D image containing a boolean image for each class in the order (sand, swash, water)
+ cloud_mask: np.array
+ 2D cloud mask with True where cloud pixels are
+ buffer_size: int
+ size of the buffer around the sandy beach
+
+ Returns: -----------
+ contours_wi: list of np.arrays
+ contains the (row,column) coordinates of the contour lines extracted with the
+ NDWI (Normalized Difference Water Index)
+ contours_mwi: list of np.arrays
+ contains the (row,column) coordinates of the contour lines extracted with the
+ MNDWI (Modified Normalized Difference Water Index)
+
+ """
+
+ nrows = cloud_mask.shape[0]
+ ncols = cloud_mask.shape[1]
+
+ # calculate Normalized Difference Modified Water Index (SWIR - G)
+ im_mwi = nd_index(im_ms_ps[:,:,4], im_ms_ps[:,:,1], cloud_mask)
+ # calculate Normalized Difference Modified Water Index (NIR - G)
+ im_wi = nd_index(im_ms_ps[:,:,3], im_ms_ps[:,:,1], cloud_mask)
+ # stack indices together
+ im_ind = np.stack((im_wi, im_mwi), axis=-1)
+ vec_ind = im_ind.reshape(nrows*ncols,2)
+
+ # reshape labels into vectors
+ vec_sand = im_labels[:,:,0].reshape(ncols*nrows)
+ vec_water = im_labels[:,:,2].reshape(ncols*nrows)
+
+ # create a buffer around the sandy beach
+ se = morphology.disk(buffer_size)
+ im_buffer = morphology.binary_dilation(im_labels[:,:,0], se)
+ vec_buffer = im_buffer.reshape(nrows*ncols)
+
+ # select water/sand/swash pixels that are within the buffer
+ int_water = vec_ind[np.logical_and(vec_buffer,vec_water),:]
+ int_sand = vec_ind[np.logical_and(vec_buffer,vec_sand),:]
+
+ # make sure both classes have the same number of pixels before thresholding
+ if len(int_water) > 0 and len(int_sand) > 0:
+ if np.argmin([int_sand.shape[0],int_water.shape[0]]) == 1:
+ if (int_sand.shape[0] - int_water.shape[0])/int_water.shape[0] > 0.5:
+ int_sand = int_sand[np.random.randint(0,int_sand.shape[0],int_water.shape[0]),:]
+ else:
+ if (int_water.shape[0] - int_sand.shape[0])/int_sand.shape[0] > 0.5:
+ int_water = int_water[np.random.randint(0,int_water.shape[0],int_sand.shape[0]),:]
+
+ # threshold the sand/water intensities
+ int_all = np.append(int_water,int_sand, axis=0)
+ t_mwi = filters.threshold_otsu(int_all[:,0])
+ t_wi = filters.threshold_otsu(int_all[:,1])
+
+ # find contour with MS algorithm
+ im_wi_buffer = np.copy(im_wi)
+ im_wi_buffer[~im_buffer] = np.nan
+ im_mwi_buffer = np.copy(im_mwi)
+ im_mwi_buffer[~im_buffer] = np.nan
+ contours_wi = measure.find_contours(im_wi_buffer, t_wi)
+ contours_mwi = measure.find_contours(im_mwi, t_mwi)
+
+ # remove contour points that are nans (around clouds)
+ contours = contours_wi
+ contours_nonans = []
+ for k in range(len(contours)):
+ if np.any(np.isnan(contours[k])):
+ index_nan = np.where(np.isnan(contours[k]))[0]
+ contours_temp = np.delete(contours[k], index_nan, axis=0)
+ if len(contours_temp) > 1:
+ contours_nonans.append(contours_temp)
+ else:
+ contours_nonans.append(contours[k])
+ contours_wi = contours_nonans
+
+ contours = contours_mwi
+ contours_nonans = []
+ for k in range(len(contours)):
+ if np.any(np.isnan(contours[k])):
+ index_nan = np.where(np.isnan(contours[k]))[0]
+ contours_temp = np.delete(contours[k], index_nan, axis=0)
+ if len(contours_temp) > 1:
+ contours_nonans.append(contours_temp)
+ else:
+ contours_nonans.append(contours[k])
+ contours_mwi = contours_nonans
+
+ return contours_wi, contours_mwi
+
+def process_shoreline(contours, georef, image_epsg, settings):
+
+ # convert pixel coordinates to world coordinates
+ contours_world = SDS_tools.convert_pix2world(contours, georef)
+ # convert world coordinates to desired spatial reference system
+ contours_epsg = SDS_tools.convert_epsg(contours_world, image_epsg, settings['output_epsg'])
+ # remove contours that have a perimeter < min_length_wl (provided in settings dict)
+ # this enable to remove the very small contours that do not correspond to the shoreline
+ contours_long = []
+ for l, wl in enumerate(contours_epsg):
+ coords = [(wl[k,0], wl[k,1]) for k in range(len(wl))]
+ a = LineString(coords) # shapely LineString structure
+ if a.length >= settings['min_length_sl']:
+ contours_long.append(wl)
+ # format points into np.array
+ x_points = np.array([])
+ y_points = np.array([])
+ for k in range(len(contours_long)):
+ x_points = np.append(x_points,contours_long[k][:,0])
+ y_points = np.append(y_points,contours_long[k][:,1])
+ contours_array = np.transpose(np.array([x_points,y_points]))
+
+ # if reference shoreline has been manually digitised
+ if 'refsl' in settings.keys():
+ # only keep the points that are at a certain distance (define in settings) from the
+ # reference shoreline, enables to avoid false detections and remove obvious outliers
+ temp = np.zeros((len(contours_array))).astype(bool)
+ for k in range(len(settings['refsl'])):
+ temp = np.logical_or(np.linalg.norm(contours_array - settings['refsl'][k,[0,1]],
+ axis=1) < settings['max_dist_ref'], temp)
+ shoreline = contours_array[temp]
+ else:
+ shoreline = contours_array
+
+ return shoreline
+
+def show_detection(im_ms, cloud_mask, im_labels, shoreline,image_epsg, georef,
+ settings, date, satname):
+
+ # subfolder to store the .jpg files
+ filepath = os.path.join(os.getcwd(), 'data', settings['sitename'], 'jpg_files', 'detection')
+
+ # display RGB image
+ im_RGB = SDS_preprocess.rescale_image_intensity(im_ms[:,:,[2,1,0]], cloud_mask, 99.9)
+ # display classified image
+ im_class = np.copy(im_RGB)
+ cmap = cm.get_cmap('tab20c')
+ colorpalette = cmap(np.arange(0,13,1))
+ colours = np.zeros((3,4))
+ colours[0,:] = colorpalette[5]
+ colours[1,:] = np.array([204/255,1,1,1])
+ colours[2,:] = np.array([0,91/255,1,1])
+ for k in range(0,im_labels.shape[2]):
+ im_class[im_labels[:,:,k],0] = colours[k,0]
+ im_class[im_labels[:,:,k],1] = colours[k,1]
+ im_class[im_labels[:,:,k],2] = colours[k,2]
+ # display MNDWI grayscale image
+ im_mwi = nd_index(im_ms[:,:,4], im_ms[:,:,1], cloud_mask)
+ # transform world coordinates of shoreline into pixel coordinates
+ sl_pix = SDS_tools.convert_world2pix(SDS_tools.convert_epsg(shoreline, settings['output_epsg'],
+ image_epsg)[:,[0,1]], georef)
+ # make figure
+ fig = plt.figure()
+ gs = gridspec.GridSpec(1, 3)
+ gs.update(bottom=0.05, top=0.95)
+ ax1 = fig.add_subplot(gs[0,0])
+ plt.imshow(im_RGB)
+ plt.plot(sl_pix[:,0], sl_pix[:,1], 'k--')
+ plt.axis('off')
+ ax1.set_anchor('W')
+ btn_keep = plt.text(0, 0.9, 'keep', size=16, ha="left", va="top",
+ transform=ax1.transAxes,
+ bbox=dict(boxstyle="square", ec='k',fc='w'))
+ btn_skip = plt.text(1, 0.9, 'skip', size=16, ha="right", va="top",
+ transform=ax1.transAxes,
+ bbox=dict(boxstyle="square", ec='k',fc='w'))
+ plt.title('Click on if shoreline detection is correct. Click on if false detection')
+ ax2 = fig.add_subplot(gs[0,1])
+ plt.imshow(im_class)
+ plt.plot(sl_pix[:,0], sl_pix[:,1], 'k--')
+ plt.axis('off')
+ ax2.set_anchor('W')
+ orange_patch = mpatches.Patch(color=colours[0,:], label='sand')
+ white_patch = mpatches.Patch(color=colours[1,:], label='whitewater')
+ blue_patch = mpatches.Patch(color=colours[2,:], label='water')
+ black_line = mlines.Line2D([],[],color='k',linestyle='--', label='shoreline')
+ plt.legend(handles=[orange_patch,white_patch,blue_patch, black_line], bbox_to_anchor=(1, 0.5), fontsize=9)
+ ax3 = fig.add_subplot(gs[0,2])
+ plt.imshow(im_mwi, cmap='bwr')
+ plt.plot(sl_pix[:,0], sl_pix[:,1], 'k--')
+ plt.axis('off')
+ cb = plt.colorbar()
+ cb.ax.tick_params(labelsize=10)
+ cb.set_label('MNDWI values')
+ ax3.set_anchor('W')
+ fig.set_size_inches([12.53, 9.3])
+ fig.set_tight_layout(True)
+ mng = plt.get_current_fig_manager()
+ mng.window.showMaximized()
+
+ # wait for user's selection ( or )
+ pt = ginput(n=1, timeout=100, show_clicks=True)
+ pt = np.array(pt)
+ # if clicks next to , return skip_image = True
+ if pt[0][0] > im_ms.shape[1]/2:
+ skip_image = True
+ plt.close()
+ else:
+ skip_image = False
+ ax1.set_title(date + ' ' + satname)
+ btn_skip.set_visible(False)
+ btn_keep.set_visible(False)
+ fig.savefig(os.path.join(filepath, date + '_' + satname + '.jpg'), dpi=150)
+ plt.close()
+
+ return skip_image
+
+
+def extract_shorelines(metadata, settings):
+
+ sitename = settings['sitename']
+
+ # initialise output structure
+ out = dict([])
+ # create a subfolder to store the .jpg images showing the detection
+ filepath_jpg = os.path.join(os.getcwd(), 'data', sitename, 'jpg_files', 'detection')
+ try:
+ os.makedirs(filepath_jpg)
+ except:
+ print('')
+
+ # loop through satellite list
+ for satname in metadata.keys():
+
+ # access the images
+ if satname == 'L5':
+ # access downloaded Landsat 5 images
+ filepath = os.path.join(os.getcwd(), 'data', sitename, satname, '30m')
+ filenames = os.listdir(filepath)
+ elif satname == 'L7':
+ # access downloaded Landsat 7 images
+ filepath_pan = os.path.join(os.getcwd(), 'data', sitename, 'L7', 'pan')
+ filepath_ms = os.path.join(os.getcwd(), 'data', sitename, 'L7', 'ms')
+ filenames_pan = os.listdir(filepath_pan)
+ filenames_ms = os.listdir(filepath_ms)
+ if (not len(filenames_pan) == len(filenames_ms)):
+ raise 'error: not the same amount of files for pan and ms'
+ filepath = [filepath_pan, filepath_ms]
+ filenames = filenames_pan
+ elif satname == 'L8':
+ # access downloaded Landsat 7 images
+ filepath_pan = os.path.join(os.getcwd(), 'data', sitename, 'L8', 'pan')
+ filepath_ms = os.path.join(os.getcwd(), 'data', sitename, 'L8', 'ms')
+ filenames_pan = os.listdir(filepath_pan)
+ filenames_ms = os.listdir(filepath_ms)
+ if (not len(filenames_pan) == len(filenames_ms)):
+ raise 'error: not the same amount of files for pan and ms'
+ filepath = [filepath_pan, filepath_ms]
+ filenames = filenames_pan
+ elif satname == 'S2':
+ # access downloaded Sentinel 2 images
+ filepath10 = os.path.join(os.getcwd(), 'data', sitename, satname, '10m')
+ filenames10 = os.listdir(filepath10)
+ filepath20 = os.path.join(os.getcwd(), 'data', sitename, satname, '20m')
+ filenames20 = os.listdir(filepath20)
+ filepath60 = os.path.join(os.getcwd(), 'data', sitename, satname, '60m')
+ filenames60 = os.listdir(filepath60)
+ if (not len(filenames10) == len(filenames20)) or (not len(filenames20) == len(filenames60)):
+ raise 'error: not the same amount of files for 10, 20 and 60 m'
+ filepath = [filepath10, filepath20, filepath60]
+ filenames = filenames10
+
+ # initialise some variables
+ out_timestamp = [] # datetime at which the image was acquired (UTC time)
+ out_shoreline = [] # vector of shoreline points
+ out_filename = [] # filename of the images from which the shorelines where derived
+ out_cloudcover = [] # cloud cover of the images
+ out_geoaccuracy = []# georeferencing accuracy of the images
+ out_idxkeep = [] # index that were kept during the analysis (cloudy images are skipped)
+
+ # loop through the images
+ for i in range(len(filenames)):
+ # get image filename
+ fn = SDS_tools.get_filenames(filenames[i],filepath, satname)
+ # preprocess image (cloud mask + pansharpening/downsampling)
+ im_ms, georef, cloud_mask = SDS_preprocess.preprocess_single(fn, satname)
+ # get image spatial reference system (epsg code) from metadata dict
+ image_epsg = metadata[satname]['epsg'][i]
+ # calculate cloud cover
+ cloud_cover = np.divide(sum(sum(cloud_mask.astype(int))),
+ (cloud_mask.shape[0]*cloud_mask.shape[1]))
+ # skip image if cloud cover is above threshold
+ if cloud_cover > settings['cloud_thresh']:
+ continue
+ # classify image in 4 classes (sand, whitewater, water, other) with NN classifier
+ im_classif, im_labels = classify_image_NN_nopan(im_ms, cloud_mask,
+ settings['min_beach_size'])
+ # extract water line contours
+ # if there aren't any sandy pixels, use find_wl_contours1 (traditional method),
+ # otherwise use find_wl_contours2 (enhanced method with classification)
+ if sum(sum(im_labels[:,:,0])) == 0 :
+ # compute MNDWI (SWIR-Green normalized index) grayscale image
+ im_mndwi = nd_index(im_ms[:,:,4], im_ms[:,:,1], cloud_mask)
+ # find water contourson MNDWI grayscale image
+ contours_mwi = find_wl_contours1(im_mndwi, cloud_mask)
+ else:
+ # use classification to refine threshold and extract sand/water interface
+ contours_wi, contours_mwi = find_wl_contours2(im_ms, im_labels,
+ cloud_mask, settings['buffer_size'])
+ # extract clean shoreline from water contours
+ shoreline = process_shoreline(contours_mwi, georef, image_epsg, settings)
+
+ if settings['check_detection']:
+ date = filenames[i][:10]
+ skip_image = show_detection(im_ms, cloud_mask, im_labels, shoreline,
+ image_epsg, georef, settings, date, satname)
+ if skip_image:
+ continue
+
+ # fill and save output structure
+ out_timestamp.append(metadata[satname]['dates'][i])
+ out_shoreline.append(shoreline)
+ out_filename.append(filenames[i])
+ out_cloudcover.append(cloud_cover)
+ out_geoaccuracy.append(metadata[satname]['acc_georef'][i])
+ out_idxkeep.append(i)
+
+ out[satname] = {
+ 'timestamp': out_timestamp,
+ 'shoreline': out_shoreline,
+ 'filename': out_filename,
+ 'cloudcover': out_cloudcover,
+ 'geoaccuracy': out_geoaccuracy,
+ 'idxkeep': out_idxkeep
+ }
+
+ # add some metadata
+ out['meta'] = {
+ 'timestamp': 'UTC time',
+ 'shoreline': 'coordinate system epsg : ' + str(settings['output_epsg']),
+ 'cloudcover': 'calculated on the cropped image',
+ 'geoaccuracy': 'RMSE error based on GCPs',
+ 'idxkeep': 'indices of the images that were kept to extract a shoreline'
+ }
+ # save output structure as out.pkl
+ filepath = os.path.join(os.getcwd(), 'data', sitename)
+ with open(os.path.join(filepath, sitename + '_out.pkl'), 'wb') as f:
+ pickle.dump(out, f)
+
+ return out
\ No newline at end of file
diff --git a/SDS_tools.py b/SDS_tools.py
new file mode 100644
index 0000000..4b743e9
--- /dev/null
+++ b/SDS_tools.py
@@ -0,0 +1,187 @@
+"""This module contains utilities to work with satellite images'
+
+ Author: Kilian Vos, Water Research Laboratory, University of New South Wales
+"""
+
+# Initial settings
+import os
+import numpy as np
+from osgeo import gdal, ogr, osr
+import skimage.transform as transform
+import simplekml
+import pdb
+
+# Functions
+
+def convert_pix2world(points, georef):
+ """
+ Converts pixel coordinates (row,columns) to world projected coordinates
+ performing an affine transformation.
+
+ KV WRL 2018
+
+ Arguments:
+ -----------
+ points: np.array or list of np.array
+ array with 2 columns (rows first and columns second)
+ georef: np.array
+ vector of 6 elements [Xtr, Xscale, Xshear, Ytr, Yshear, Yscale]
+
+ Returns: -----------
+ points_converted: np.array or list of np.array
+ converted coordinates, first columns with X and second column with Y
+
+ """
+
+ # make affine transformation matrix
+ aff_mat = np.array([[georef[1], georef[2], georef[0]],
+ [georef[4], georef[5], georef[3]],
+ [0, 0, 1]])
+ # create affine transformation
+ tform = transform.AffineTransform(aff_mat)
+
+ if type(points) is list:
+ points_converted = []
+ # iterate over the list
+ for i, arr in enumerate(points):
+ tmp = arr[:,[1,0]]
+ points_converted.append(tform(tmp))
+
+ elif type(points) is np.ndarray:
+ tmp = points[:,[1,0]]
+ points_converted = tform(tmp)
+
+ else:
+ print('invalid input type')
+ raise
+
+ return points_converted
+
+def convert_world2pix(points, georef):
+ """
+ Converts world projected coordinates (X,Y) to image coordinates (row,column)
+ performing an affine transformation.
+
+ KV WRL 2018
+
+ Arguments:
+ -----------
+ points: np.array or list of np.array
+ array with 2 columns (rows first and columns second)
+ georef: np.array
+ vector of 6 elements [Xtr, Xscale, Xshear, Ytr, Yshear, Yscale]
+
+ Returns: -----------
+ points_converted: np.array or list of np.array
+ converted coordinates, first columns with row and second column with column
+
+ """
+
+ # make affine transformation matrix
+ aff_mat = np.array([[georef[1], georef[2], georef[0]],
+ [georef[4], georef[5], georef[3]],
+ [0, 0, 1]])
+ # create affine transformation
+ tform = transform.AffineTransform(aff_mat)
+
+ if type(points) is list:
+ points_converted = []
+ # iterate over the list
+ for i, arr in enumerate(points):
+ points_converted.append(tform.inverse(points))
+
+ elif type(points) is np.ndarray:
+ points_converted = tform.inverse(points)
+
+ else:
+ print('invalid input type')
+ raise
+
+ return points_converted
+
+
+def convert_epsg(points, epsg_in, epsg_out):
+ """
+ Converts from one spatial reference to another using the epsg codes.
+
+ KV WRL 2018
+
+ Arguments:
+ -----------
+ points: np.array or list of np.ndarray
+ array with 2 columns (rows first and columns second)
+ epsg_in: int
+ epsg code of the spatial reference in which the input is
+ epsg_out: int
+ epsg code of the spatial reference in which the output will be
+
+ Returns: -----------
+ points_converted: np.array or list of np.array
+ converted coordinates
+
+ """
+
+ # define input and output spatial references
+ inSpatialRef = osr.SpatialReference()
+ inSpatialRef.ImportFromEPSG(epsg_in)
+ outSpatialRef = osr.SpatialReference()
+ outSpatialRef.ImportFromEPSG(epsg_out)
+ # create a coordinates transform
+ coordTransform = osr.CoordinateTransformation(inSpatialRef, outSpatialRef)
+ # transform points
+ if type(points) is list:
+ points_converted = []
+ # iterate over the list
+ for i, arr in enumerate(points):
+ points_converted.append(np.array(coordTransform.TransformPoints(arr)))
+ elif type(points) is np.ndarray:
+ points_converted = np.array(coordTransform.TransformPoints(points))
+ else:
+ print('invalid input type')
+ raise
+
+ return points_converted
+
+def coords_from_kml(fn):
+
+ # read .kml file
+ with open(fn) as kmlFile:
+ doc = kmlFile.read()
+ # parse to find coordinates field
+ str1 = ''
+ str2 = ''
+ subdoc = doc[doc.find(str1)+len(str1):doc.find(str2)]
+ coordlist = subdoc.split('\n')
+ polygon = []
+ for i in range(1,len(coordlist)-1):
+ polygon.append([float(coordlist[i].split(',')[0]), float(coordlist[i].split(',')[1])])
+
+ return [polygon]
+
+def save_kml(coords, epsg):
+
+ kml = simplekml.Kml()
+ coords_wgs84 = convert_epsg(coords, epsg, 4326)
+ kml.newlinestring(name='coords', coords=coords_wgs84)
+ kml.save('coords.kml')
+
+def get_filenames(filename, filepath, satname):
+
+ if satname == 'L5':
+ fn = os.path.join(filepath, filename)
+ if satname == 'L7' or satname == 'L8':
+ idx = filename.find('.tif')
+ filename_ms = filename[:idx-3] + 'ms.tif'
+ fn = [os.path.join(filepath[0], filename),
+ os.path.join(filepath[1], filename_ms)]
+ if satname == 'S2':
+ idx = filename.find('.tif')
+ filename20 = filename[:idx-3] + '20m.tif'
+ filename60 = filename[:idx-3] + '60m.tif'
+ fn = [os.path.join(filepath[0], filename),
+ os.path.join(filepath[1], filename20),
+ os.path.join(filepath[2], filename60)]
+ return fn
+
+
+
\ No newline at end of file
diff --git a/main_spyder.py b/main_spyder.py
new file mode 100644
index 0000000..61920fc
--- /dev/null
+++ b/main_spyder.py
@@ -0,0 +1,80 @@
+#==========================================================#
+# Shoreline extraction from satellite images
+#==========================================================#
+
+# load modules
+import os
+import pickle
+import warnings
+warnings.filterwarnings("ignore")
+import matplotlib.pyplot as plt
+import SDS_download, SDS_preprocess, SDS_shoreline
+
+
+# define the area of interest (longitude, latitude)
+polygon = [[[151.301454, -33.700754],
+ [151.311453, -33.702075],
+ [151.307237, -33.739761],
+ [151.294220, -33.736329],
+ [151.301454, -33.700754]]]
+
+# define dates of interest
+dates = ['2017-12-01', '2018-01-01']
+
+# define satellite missions
+sat_list = ['L5', 'L7', 'L8', 'S2']
+
+# give a name to the site
+sitename = 'NARRA'
+
+# download satellite images (also saves metadata.pkl)
+#SDS_download.get_images(sitename, polygon, dates, sat_list)
+
+# load metadata structure (contains information on the downloaded satellite images and is created
+# after all images have been successfully downloaded)
+filepath = os.path.join(os.getcwd(), 'data', sitename)
+with open(os.path.join(filepath, sitename + '_metadata' + '.pkl'), 'rb') as f:
+ metadata = pickle.load(f)
+
+# parameters and settings
+settings = {
+ 'sitename': sitename,
+
+ # general parameters:
+ 'cloud_thresh': 0.5, # threshold on maximum cloud cover
+ 'output_epsg': 28356, # epsg code of the desired output spatial reference system
+
+ # shoreline detection parameters:
+ 'min_beach_size': 20, # minimum number of connected pixels for a beach
+ 'buffer_size': 7, # radius (in pixels) of disk for buffer around sandy pixels
+ 'min_length_sl': 200, # minimum length of shoreline perimeter to be kept
+ 'max_dist_ref': 100, # max distance (in meters) allowed from a reference shoreline
+
+ # quality control:
+ 'check_detection': True # if True, shows each shoreline detection and lets the user
+ # decide which ones are correct and which ones are false due to
+ # the presence of clouds
+}
+
+# preprocess images (cloud masking, pansharpening/down-sampling)
+SDS_preprocess.preprocess_all_images(metadata, settings)
+
+# create a reference shoreline (used to identify outliers and false detections)
+settings['refsl'] = SDS_preprocess.get_reference_sl(metadata, settings)
+
+# extract shorelines from all images (also saves output.pkl)
+out = SDS_shoreline.extract_shorelines(metadata, settings)
+
+# plot shorelines
+plt.figure()
+plt.axis('equal')
+plt.xlabel('Eastings [m]')
+plt.ylabel('Northings [m]')
+for satname in out.keys():
+ if satname == 'meta':
+ continue
+ for i in range(len(out[satname]['shoreline'])):
+ sl = out[satname]['shoreline'][i]
+ date = out[satname]['timestamp'][i]
+ plt.plot(sl[:, 0], sl[:, 1], '-', label=date.strftime('%d-%m-%Y'))
+plt.legend()
diff --git a/shoreline_extraction.ipynb b/shoreline_extraction.ipynb
new file mode 100644
index 0000000..8d99b85
--- /dev/null
+++ b/shoreline_extraction.ipynb
@@ -0,0 +1,199 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Shoreline extraction from satellite images"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This notebook shows how to download satellite images (Landsat 5,7,8 and Sentinel-2) from Google Earth Engine and apply the shoreline detection algorithm described in *Vos K., Harley M.D., Splinter K.D., Simmons J.A., Turner I.L. (in review). Capturing intra-annual to multi-decadal shoreline variability from publicly available satellite imagery, Coastal Engineering*. "
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Initial settings"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The Python packages required to run this notebook can be installed by running the following anaconda command:\n",
+ "*\"conda env create -f environment.yml\"*. This will create a new enviroment with all the relevant packages installed. You will also need to sign up for Google Earth Engine (https://earthengine.google.com and go to signup) and authenticate on the computer so that python can access via your login."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "import pickle\n",
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "import warnings\n",
+ "warnings.filterwarnings(\"ignore\")\n",
+ "# load modules from directory\n",
+ "import SDS_download, SDS_preprocess, SDS_tools, SDS_shoreline"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Download images"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Define the region of interest, the dates and the satellite missions from which you want to download images. The image will be cropped on the Google Earth Engine server and only the region of interest will be downloaded resulting in low memory allocation (~ 1 megabyte/image for 5 km of beach)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# define the area of interest (longitude, latitude)\n",
+ "polygon = [[[151.301454, -33.700754],\n",
+ " [151.311453, -33.702075], \n",
+ " [151.307237, -33.739761],\n",
+ " [151.294220, -33.736329],\n",
+ " [151.301454, -33.700754]]]\n",
+ " \n",
+ "# define dates of interest\n",
+ "dates = ['2017-12-01','2018-01-01']\n",
+ "\n",
+ "# define satellite missions ('L5' --> landsat 5 , 'S2' --> Sentinel-2)\n",
+ "sat_list = ['L5', 'L7', 'L8', 'S2']\n",
+ "\n",
+ "# give a name to the site\n",
+ "sitename = 'NARRA'\n",
+ "\n",
+ "# download satellite images. The cropped images are saved in a '/data' subfolder. The image information is stored\n",
+ "# into 'metadata.pkl'.\n",
+ "# SDS_download.get_images(sitename, polygon, dates, sat_list)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Shoreline extraction"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Performs a sub-pixel resolution shoreline detection method integrating a supervised classification component that allows to map the boundary between water and sand."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# parameters and settings\n",
+ "%matplotlib qt\n",
+ "settings = { \n",
+ " 'sitename': sitename,\n",
+ " \n",
+ " # general parameters:\n",
+ " 'cloud_thresh': 0.5, # threshold on maximum cloud cover\n",
+ " 'output_epsg': 28356, # epsg code of the desired output spatial reference system\n",
+ " \n",
+ " # shoreline detection parameters:\n",
+ " 'min_beach_size': 20, # minimum number of connected pixels for a beach\n",
+ " 'buffer_size': 7, # radius (in pixels) of disk for buffer around sandy pixels\n",
+ " 'min_length_sl': 200, # minimum length of shoreline perimeter to be kept \n",
+ " 'max_dist_ref': 100 , # max distance (in meters) allowed from a reference shoreline\n",
+ " \n",
+ " # quality control:\n",
+ " 'check_detection': True # if True, shows each shoreline detection and lets the user \n",
+ " # decide which shorleines are correct and which ones are false due to\n",
+ " # the presence of clouds and other artefacts. \n",
+ " # If set to False, shorelines are extracted from all images.\n",
+ " }\n",
+ "\n",
+ "# load metadata structure (contains information on the downloaded satellite images and is created\n",
+ "# after all images have been successfully downloaded)\n",
+ "filepath = os.path.join(os.getcwd(), 'data', settings['sitename'])\n",
+ "with open(os.path.join(filepath, settings['sitename'] + '_metadata' + '.pkl'), 'rb') as f:\n",
+ " metadata = pickle.load(f)\n",
+ " \n",
+ "# [OPTIONAL] saves .jpg files of the preprocessed images (cloud mask and pansharpening/down-sampling) \n",
+ "#SDS_preprocess.preprocess_all_images(metadata, settings)\n",
+ "\n",
+ "# [OPTIONAL] to avoid false detections and identify obvious outliers there is the option to\n",
+ "# create a reference shoreline position (manually clicking on a satellite image)\n",
+ "settings['refsl'] = SDS_preprocess.get_reference_sl(metadata, settings)\n",
+ "\n",
+ "# extract shorelines from all images. Saves out.pkl which contains the shoreline coordinates for each date in the spatial\n",
+ "# reference system specified in settings['output_epsg']. Save the output in a file called 'out.pkl'.\n",
+ "out = SDS_shoreline.extract_shorelines(metadata, settings)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Plot the shorelines"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "plt.figure()\n",
+ "plt.axis('equal')\n",
+ "plt.xlabel('Eastings [m]')\n",
+ "plt.ylabel('Northings [m]')\n",
+ "plt.title('Shorelines')\n",
+ "for satname in out.keys():\n",
+ " if satname == 'meta':\n",
+ " continue\n",
+ " for i in range(len(out[satname]['shoreline'])):\n",
+ " sl = out[satname]['shoreline'][i]\n",
+ " date = out[satname]['timestamp'][i]\n",
+ " plt.plot(sl[:,0], sl[:,1], '-', label=date.strftime('%d-%m-%Y'))\n",
+ "plt.legend()"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.4"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}