Code Monkey home page Code Monkey logo

remotior_sensus's Introduction

https://img.shields.io/badge/Website-darkgreen https://img.shields.io/badge/Documentation-blue https://img.shields.io/badge/Bug%20reports-red https://img.shields.io/pypi/v/remotior-sensus?label=PyPI%20version https://img.shields.io/pypi/dm/remotior-sensus?label=PyPI%20downloads https://img.shields.io/conda/v/conda-forge/remotior-sensus?label=Conda%20version https://img.shields.io/conda/d/conda-forge/remotior-sensus?label=Conda%20downloads https://img.shields.io/conda/l/conda-forge/remotior-sensus

Introduction

Remotior Sensus (which is Latin for "a more remote sense") is a Python package that allows for the processing of remote sensing images and GIS data.

Remotior Sensus is developed by Luca Congedo.

The main objective is to simplify the processing of remote sensing data through practical and integrated APIs that span from the download and preprocessing of satellite images to the postprocessing of classifications and GIS data. Basic dependencies are NumPy, SciPy for calculations, and GDAL for managing spatial data. Optionally, Matplotlib is used to display spectral signature plots.

The main features are:

  • Search and Download of remote sensing data such as Landsat and Sentinel-2.
  • Preprocessing of several products such as Landsat and Sentinel-2 images.
  • Processing and postprocessing tools to perform image classification through machine learning, manage GIS data and perform spatial analyses.
  • Parallel processing available for most processing tools.

WARNING: Remotior Sensus is still in early development; new tools are going to be added, tools and APIs may change, and one may encounter issues and bugs using Remotior Sensus.

Management of Raster Bands

Most tools accept raster bands as input, defined through the file path.

In addition, raster bands can be managed through a catalog of BandSets, where each BandSet is an object that includes information about single bands (from the file path to the spatial and spectral characteristics). Bands in a BandSet can be referenced by the properties thereof, such as order number or center wavelength.

Multimple BandSets can be defined and identified by their reference number. Therefore, BandSets can be used as input for operations on multiple bands such as Principal Components Analysis, classification, mosaic, or band calculation.

In band calculations, alias name of bands based on center wavelength (e.g. blue, red) can be used to simplify the structure of calculation expression.

Performance

Most tools are designed to run in parallel processes, through a simple and effective parallelization approach based on dividing the raster input in sections that are distributed to available threads, maximizing the use of available RAM. This allows even complex algorithms to run in parallel. Optionally, the output file can be a virtual raster collecting the output rasters (corresponding to the sections) written independently by parallel processes; this avoids the time required to produce a unique raster output. Most tools allow for on the fly reprojection of input data.

Machine Learning

Remotior Sensus optional dependencies are PyTorch and scikit-learn, which are integrated in the classification tool. to allow for land cover classification through machine learning. The aim is to simplify the training process and development of the model.

Installation

Remotior Sensus requires GDAL, NumPy and SciPy for most functionalities. Also, scikit-learn and PyTorch are optional but required for machine learning. Optionally, Matplotlib is used to display spectral signature plots.

It is recommended to install Remotior Sensus using a Conda environment.

$ conda install -c conda-forge remotior-sensus scikit-learn pytorch

License of Remotior Sensus

Remotior Sensus 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. Remotior Sensus 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 Remotior Sensus. If not, see https://www.gnu.org/licenses/.

Official site

For more information and tutorials visit the official site

From GIS to Remote Sensing

remotior_sensus's People

Contributors

semiautomaticgit avatar ivanbarsukov avatar

Stargazers

Victor Pedroso Curtarelli avatar Rivelle Rivétria avatar  avatar ruoli_develop avatar Curtis Yung avatar 橘子味的鱼 avatar Brian Dunnette avatar Christian Ledermann avatar Cláudio Ângelo avatar fener95 avatar Liao Spacefan avatar  avatar  avatar Andres Calderon avatar Paulo van Breugel avatar Gökhan Çalınak avatar Peter Jackson avatar SAI RAM KASANAGOTTU avatar  avatar Vinea avatar Christian J. Tai Udovicic avatar Jacob A Rose avatar Dmitry Sorokin avatar  avatar Yi Dong avatar Antony Barja  avatar Bakhtiyar Babashli avatar

Watchers

Dmitry Sorokin avatar  avatar Kostas Georgiou avatar  avatar

remotior_sensus's Issues

Library tests failing

Hello,

I recently attempted to build remotior_sensus and run the tests and found that a majority of them failed. Specifically, only 7 out of 32 tests passed. This is concerning as it suggests potential issues with the library's functionality and reliability.

Could you please confirm if these tests are expected to be operational at this stage? If so, I would appreciate any guidance on possible causes for these failures.

Here's a brief overview of my environment:

  • Operating System: Archlinux
  • Python Version: 3.11.6
  • Library Version: 0.2.01

Any insights or assistance you can provide in resolving these test failures would be greatly appreciated.

Thank you.

ResourceWarning: unclosed file in Log class of version 0.4.2

Description
When using version 0.4.2 of the remotior_sensus library, a ResourceWarning: unclosed file occurs due to unclosed file handlers in the Log class. This issue was not present in version 0.3.5.

Steps to Reproduce
Initialize a session with remotior_sensus.Session.
Observe the warning message about unclosed files in the logs.

Proposed Solution
In the log.py file, add a method to properly close all handlers to ensure that file handlers are correctly closed. Below is the modified code for the Log class:

Modified Code Snippet
Add the following method to ensure that all file handlers are properly closed:

def close_handlers(self, logger):
    if logger.hasHandlers():
        for handler in logger.handlers:
            try:
                handler.close()
            except Exception as err:
                print(f"Error closing handler: {err}")
        logger.handlers.clear()

And update the init method to call close_handlers:

if not multiprocess:
    # create file handler
    fh = logging.FileHandler(file_path)
    fh.setLevel(level)
    fhf = logging.Formatter(
        '%(levelname)s|%(asctime)s.%(msecs)03d|%(module)s|%(funcName)s'
        '|%(lineno)s|%(message)s', '%Y-%m-%dT%H:%M:%S'
    )
    fh.setFormatter(fhf)
    self.close_handlers(logger)  # Ensure handlers are closed before adding new ones
    logger.addHandler(fh)
    # create console handler
    if stream_handler:
        ch = logging.StreamHandler()
        ch.setLevel(level)
        if time:
            chf = logging.Formatter(
                '%(levelname)s[%(asctime)s.%(msecs)03d] '
                '%(module)s.%(funcName)s[%(lineno)s] %(message)s',
                '%Y-%m-%dT%H:%M:%S'
            )
        else:
            chf = logging.Formatter(
                '%(levelname)s %(module)s.%(funcName)s[%(lineno)s] '
                '%(message)s'
            )
        ch.setFormatter(chf)
        logger.addHandler(ch)
    logger.propagate = False
    self.log = logger
    self.file_path = file_path
    self.stream = None
    self.level = level
else:
    # create stream handler
    stream = io.StringIO()
    ch = logging.StreamHandler(stream)
    ch.setLevel(level)
    if time:
        chf = logging.Formatter(
            '%(levelname)s_p{}|%(asctime)s.%(msecs)03d|%(module)s'
            '|%(funcName)s|%(lineno)s|%(message)s'.format(
                multiprocess
            ), '%Y-%m-%dT%H:%M:%S'
        )
    else:
        chf = logging.Formatter(
            '%(levelname)s_p{}|%(module)s|%(funcName)s|%(lineno)s'
            '|%(message)s'.format(multiprocess)
        )
    ch.setFormatter(chf)
    self.close_handlers(logger)  # Ensure handlers are closed before adding new ones
    logger.addHandler(ch)
    logger.propagate = False
    self.log = logger
    self.stream = stream
    self.file_path = None
    self.level = level

Additional Notes
The added close_handlers method ensures that all file handlers are properly closed, preventing the ResourceWarning: unclosed file issue.

remotior_sensus latest version on OSGEO4W

Hello! Would it be possible to provide remotior_sensus newest version on OSGeo4W? The latest version available on it is the 0.2.1-1. I use it to manage the QGIS installations in my lab. It would be nice to update it directly from OSGeo4W.

dimension error in _collect_x_y_matrices function from rs.band_classification function

Hi Luca, this is a great effort from your part. I am trying to use the rs.band_classification function, I have this workflow so far.


if __name__ == '__main__':
    import remotior_sensus
    
    rs = remotior_sensus.Session(n_processes=16, available_ram=256* 16)
    cfg = rs.configurations
    
    # create BandSet
    catalog = rs.bandset_catalog()
    file_list = ['T17MQS_20230824T153621_B02.tif', 'T17MQS_20230824T153621_B03.tif', 'T17MQS_20230824T153621_B04.tif', 'T17MQS_20230824T153621_B05.tif', 'T17MQS_20230824T153621_B06.tif', 'T17MQS_20230824T153621_B08.tif', 'T17MQS_20230824T153621_B11.tif', 'T17MQS_20230824T153621_B12.tif', 'T17MQS_20230824T153621_B8A.tif']
    
    root_directory = 'data/'
    
    catalog.create_bandset(file_list, wavelengths=['Sentinel-2'], root_directory=root_directory)
    # set BandSet in SpectralCatalog
    signature_catalog_2 = rs.spectral_signatures_catalog(bandset=catalog.get(1))
    # import vector
    signature_catalog_2.import_vector(
        file_path=r'C:\Users\chelo\OneDrive\00_RACAR_FABIAN\land_use.gpkg',
        macroclass_field='macroclass', class_field='LandUseType',
        macroclass_name_field='macroclass', class_name_field='LandUseType',
        calculate_signature=True
    )
    temp = cfg.temp.temporary_file_path(
        name='class', name_suffix=cfg.tif_suffix
    )
    rs.band_classification(
        input_bands=catalog.get(1), output_path=temp,
        spectral_signatures=signature_catalog_2,
        signature_raster=False
    )

First I had a error, due to the fact that in the ogr could not read a band.tif file, this is the only situation that this does not work, because gdal and rasterio have no problem whit it. So I modify the function as follows, it worked after that.

# get CRS of a raster or vector
def get_crs(path):
    # try vector
    try:
        l_p = ogr.Open(path)
    except:
        l_p =  None
    # if raster
    if l_p is None:
        l_p = gdal.Open(path, gdal.GA_ReadOnly)
        if l_p is None:
            crs = None
        else:
            try:
                # check projections
                crs = l_p.GetProjection()
                crs = crs.replace(' ', '')
                if len(crs) == 0:
                    crs = None
            except Exception as err:
                crs = None
                cfg.logger.log.error(str(err))
    # if vector
    else:
        layer = l_p.GetLayer()
        # get projection
        crs = get_layer_crs(layer)
    cfg.logger.log.debug('path: %s; crs: %s' % (path, crs))
    return crs

After this part I have this error, in this function 'Gets x y arrays from rois' wich give me this error.

File "C:\Users\chelo\OneDrive\ALCANTARILLADO_PyQt5\00_MODULOS\pypiper\borrar.py", line 2873, in
rs.band_classification(
File "C:\Users\chelo\miniconda3\Lib\site-packages\remotior_sensus\tools\band_classification.py", line 1280, in band_classification
x_y_matrices = _collect_x_y_matrices(
^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\chelo\miniconda3\Lib\site-packages\remotior_sensus\tools\band_classification.py", line 1522, in _collect_x_y_matrices
x_y_arrays = _get_x_y_arrays_from_rois(
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\chelo\miniconda3\Lib\site-packages\remotior_sensus\tools\band_classification.py", line 1439, in _get_x_y_arrays_from_rois
matrix = np.stack(array_dictionary[s])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<array_function internals>", line 200, in stack
File "C:\Users\chelo\miniconda3\Lib\site-packages\numpy\core\shape_base.py", line 464, in stack
raise ValueError('all input arrays must have the same shape')
ValueError: all input arrays must have the same shape
forrtl: error (200): program aborting due to control-C event
Image PC Routine Line Source
libifcoremd.dll 00007FFA8673DF54 Unknown Unknown Unknown
KERNELBASE.dll 00007FFB048829E3 Unknown Unknown Unknown
KERNEL32.DLL 00007FFB05707344 Unknown Unknown Unknown
ntdll.dll 00007FFB071026B1 Unknown Unknown Unknown

Process finished with exit code 0

I have several warnings as this, but I think that is because of my type of features in the gpkg gile.

band classification [ 1%] [elapsed 1min23sec]:starting the classifier ⚙Warning 1: A geometry of type POLYGON is inserted into layer t20231010_201907039038_8290 of geometry type MULTIPOLYGON, which is not normally allowed by the GeoPackage specification, but the driver will however do it. To create a conformant GeoPackage, if using ogr2ogr, the -nlt option can be used to override the layer geometry type. This warning will no longer be emitted for this combination of layer and feature geometry type.

Glad to see this out, I used the plugin before so this is very useful for me as it let me do whole pipelines adding land use classification

Greetings,
Marcelo.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.