Example #1
0
    def get_mask(self, geometry, shape):

        # create an ogr datasource
        driver = ogr.GetDriverByName(str('Memory'))
        source = driver.CreateDataSource(str(''))
        sr = osr.SpatialReference(self.projection)
        layer = source.CreateLayer(str(''), sr)
        defn = layer.GetLayerDefn()
        feature = ogr.Feature(defn)
        feature.SetGeometry(geometry)
        layer.CreateFeature(feature)

        # burn where data should be
        mask = np.zeros(shape, dtype='u1')
        geo_transform = self.geo_transform.shifted(geometry)
        kwargs = {
            'geo_transform': geo_transform,
            'projection': self.projection
        }
        with datasets.Dataset(mask, **kwargs) as dataset:
            gdal.RasterizeLayer(dataset, (1, ), layer, burn_values=(1, ))

        return mask.astype('b1').repeat(3, axis=0)
Example #2
0
    gdalsrsinfo epsg:28992 -o wkt > myshape.prj
"""

from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division

import argparse
import os

from raster_tools import gdal
from raster_tools import ogr
from raster_tools import postgis

DRIVER_OGR_MEMORY = ogr.GetDriverByName(str('Memory'))
DRIVER_OGR_SHAPE = ogr.GetDriverByName(str('ESRI Shapefile'))

COMPATIBLE = {1: (1, 4),
              2: (2, 5),
              3: (3, 6),
              4: (1, 4),
              5: (2, 5),
              6: (3, 6)}


gdal.PushErrorHandler(b'CPLQuietErrorHandler')


class Selector(object):
    def __init__(self, target_path, table, attribute, clip, **kwargs):
Example #3
0
import argparse
import os
import shlex
import subprocess

import numpy as np

from raster_tools import datasets
from raster_tools import gdal
from raster_tools import ogr
from raster_tools import osr
from raster_tools import vectors

PROJECTION = osr.GetUserInputAsWKT(str('epsg:28992'))
MEM_DRIVER = ogr.GetDriverByName(str('Memory'))
NO_DATA_VALUE = np.finfo('f4').min.item()
SR = osr.SpatialReference(PROJECTION)


def clip(kwargs, geometry):
    """ Clip kwargs in place. """
    # do not touch original kwargs
    kwargs = kwargs.copy()
    array = kwargs.pop('array')
    mask = np.ones_like(array, 'u1')

    # create an ogr datasource
    source = MEM_DRIVER.CreateDataSource('')
    layer = source.CreateLayer(str(''), SR)
    defn = layer.GetLayerDefn()
Example #4
0
from __future__ import absolute_import
from __future__ import division

import argparse
import os

import numpy as np

from raster_tools import groups
from raster_tools import datasources

from raster_tools import gdal
from raster_tools import ogr
from raster_tools import osr

SHAPE = ogr.GetDriverByName(str('esri shapefile'))
COURSES = np.array([(64, 128, 1), (32, 0, 2), (16, 8, 4)], 'u1')

INDICES = COURSES.nonzero()
NUMBERS = COURSES[INDICES][np.newaxis, ...]
OFFSETS = np.array(INDICES).transpose() - 1

CLASSES = ((2.0, 3.0), (3.0, 4.0), (4.0, 4.7), (4.7, 9.9))


def get_traveled(courses):
    """ Return indices when travelling along courses. """
    # turn indices into points array
    height, width = courses.shape
    indices = (np.arange(height).repeat(width),
               np.tile(np.arange(width), height))
Example #5
0
import getpass
import os

from raster_tools import gdal
from raster_tools import ogr

import numpy as np

from raster_tools import datasets
from raster_tools import datasources
from raster_tools import groups
from raster_tools import postgis

DRIVER_GDAL_GTIFF = gdal.GetDriverByName('gtiff')
DRIVER_GDAL_MEM = gdal.GetDriverByName('mem')
DRIVER_OGR_MEM = ogr.GetDriverByName('memory')

NO_DATA_VALUE = -3.4028234663852886e+38
FLOOR_ATTRIBUTE = 'floor'
CELLSIZE = 0.5


class Rasterizer:
    def __init__(self, table, raster_path, output_path, floor, **kwargs):
        # postgis
        self.postgis_source = postgis.PostgisSource(**kwargs)
        self.table = table

        # raster
        if isdir(raster_path):
            raster_datasets = [gdal.Open(join(raster_path, path))
def command(gardens_path, aerial_image_path, target_path, min_green, max_green,
            check_rast, part, pk):
    # open input shapefile
    shape_gardens = ogr.Open(gardens_path)
    layer_gardens = shape_gardens[0]

    # check projection of input shapefile
    sr = layer_gardens.GetSpatialRef()
    check_sr = get_projection(sr)
    if check_sr is None:
        print('[!] ERROR : EPSG projection code missing from shape.')
        hint = '[*] INFO  : Use this command: gdalsrsinfo -o wkt EPSG:28992 > '
        print(hint, gardens_path.replace('.shp', '.prj'))
        return 1

    # check spaces in aerial_image_path
    if ' ' in aerial_image_path:
        hint = '[!] ERROR : There is a space in the aerial image path: '
        print(hint, aerial_image_path)
        return 1

    # check if raster exists
    if not os.path.isfile(aerial_image_path):
        hint = '[!] ERROR : The specified file could not be found: '
        print(hint, aerial_image_path)
        return 1

    # get raster info and check rasterformat
    rasterfmt = os.path.splitext(aerial_image_path)[1]
    if (rasterfmt == '.ecw' or rasterfmt == '.tif' or rasterfmt == '.vrt'):
        pixelsize, envelope_aerial_image = gdalinfo(aerial_image_path)
    else:
        hint = '[!] ERROR : No supported raster format selected: '
        print(hint, rasterfmt, ' (use .tif, .vrt or .ecw)')
        return 1

    # delete any existing target
    driver = ogr.GetDriverByName(str('ESRI Shapefile'))
    try:
        driver.DeleteDataSource(str(target_path))
    except RuntimeError:
        pass

    # prepare target dataset
    target_shape = driver.CreateDataSource(str(target_path))
    target_layer_name = os.path.basename(target_path)
    target_layer = target_shape.CreateLayer(target_layer_name, sr)
    wkt = osr.GetUserInputAsWKT(str('EPSG:28992'))
    open(target_path.replace('.shp', '.prj'), 'w').write(wkt)
    target_layer_defn = layer_gardens.GetLayerDefn()
    for i in range(target_layer_defn.GetFieldCount()):
        target_field_defn = target_layer_defn.GetFieldDefn(i)
        target_layer.CreateField(target_field_defn)
    target_field_defn = ogr.FieldDefn(str('green_perc'), ogr.OFTReal)
    target_field_defn.SetWidth(5)
    target_field_defn.SetPrecision(3)
    target_layer.CreateField(target_field_defn)
    target_field_defn = ogr.FieldDefn(str('green_area'), ogr.OFTReal)
    target_field_defn.SetWidth(10)
    target_field_defn.SetPrecision(2)
    target_layer.CreateField(target_field_defn)

    # create tmp_dir for files
    tmp_dirname = os.path.join(os.path.dirname(target_path), 'tmp_greenfactor')
    if not os.path.exists(tmp_dirname):
        os.makedirs(tmp_dirname)

    # initialise progress bar
    total = layer_gardens.GetFeatureCount()
    ogr.TermProgress_nocb(0)

    index = datasources.PartialDataSource(gardens_path)
    if part is not None:
        index = index.select(part)

    # main loop
    for count, feature_garden in enumerate(index):
        # get envelope and convert it to the projwin for ecw_gdal_translate
        geometry_garden = feature_garden.geometry()
        garden_name = feature_garden.GetFieldAsString(str(pk))
        envelope_garden = geometry_garden.GetEnvelope()
        skip_large_size = check_envelopes_input(garden_name, envelope_garden,
                                                envelope_aerial_image)
        if not skip_large_size == 1:
            x1, x2, y1, y2 = envelope_garden
            x1, y1 = np.floor(np.divide((x1, y1), pixelsize)) * pixelsize
            x2, y2 = np.ceil(np.divide((x2, y2), pixelsize)) * pixelsize
            envelope_garden_round = (x1, x2, y1, y2)
            projwin_garden = '%s %s %s %s' % (x1, y2, x2, y1)

            # create filename clipped aerial image geotiff
            tmp_aerial_tif = os.path.join(tmp_dirname, garden_name + '.tif')
            tmp_mask_tif = os.path.join(tmp_dirname, garden_name + '_mask.tif')
            tmp_green_tif = os.path.join(tmp_dirname,
                                         garden_name + '_green.tif')

            # prepare rgbt-array for green factor calculation
            rgbt, rasterdata = prepare_aerial_array(tmp_aerial_tif,
                                                    aerial_image_path,
                                                    projwin_garden, sr)

            # prepare mask-array for green factor calculation
            z = rgbt[:1, :, :] * 0
            rasterdata['fillvalue'] = 1
            array = create_filled_rasterarray(z,
                                              geometry_garden,
                                              tmp_mask_tif,
                                              rasterdata,
                                              print_rast=0)
            m = array[0].astype('b1')

            # Call function to determine the green factor
            result = determine_green_factor(rgbt, m, min_green, max_green)
            greenfactor, greengarden_percentage, greengarden_pixels = result
            greengarden_area = greengarden_pixels * pixelsize**2

            # Create raster to check green factor
            if check_rast == 1:
                rasterdata['fillvalue'] = rasterdata['no_data_value'] = -9999
                polygon_envelope_garden = get_envelope_polygon(
                    envelope_garden_round,
                    rasterdata['sr'],
                )
                outside = polygon_envelope_garden.Difference(geometry_garden)
                create_filled_rasterarray(greenfactor[np.newaxis],
                                          outside,
                                          tmp_green_tif,
                                          rasterdata,
                                          print_rast=1)

            # Create a new feature in shapefile
            attributes_garden = feature_garden.items()
            feature = ogr.Feature(target_layer.GetLayerDefn())
            feature.SetGeometry(geometry_garden)
            for key, value in attributes_garden.items():
                feature[str(key)] = value
            feature[str('green_perc')] = greengarden_percentage
            feature[str('green_area')] = greengarden_area
            target_layer.CreateFeature(feature)

            # remove raster
            os.remove(tmp_aerial_tif)

            # progress bar
            ogr.TermProgress_nocb((count + 1) / total)
    return 0
import argparse
import subprocess
import os
import re

import numpy as np

from raster_tools import gdal
from raster_tools import ogr
from raster_tools import osr

from raster_tools import datasets
from raster_tools import datasources

DRIVER_OGR_MEMORY = ogr.GetDriverByName(str('Memory'))
DRIVER_GDAL_MEM = gdal.GetDriverByName(str('mem'))
DRIVER_GDAL_GTIFF = gdal.GetDriverByName(str('gtiff'))

WKT_RD = osr.GetUserInputAsWKT(str('epsg:28992'))
PROJ4_RD = osr.SpatialReference(WKT_RD).ExportToProj4().strip()


def command(gardens_path, aerial_image_path, target_path, min_green, max_green,
            check_rast, part, pk):
    # open input shapefile
    shape_gardens = ogr.Open(gardens_path)
    layer_gardens = shape_gardens[0]

    # check projection of input shapefile
    sr = layer_gardens.GetSpatialRef()
Example #8
0
from scipy import ndimage
import numpy as np

from raster_tools import datasources
from raster_tools import gdal
from raster_tools import groups
from raster_tools import ogr
from raster_tools import utils
from raster_tools import vectors

logger = logging.getLogger(__name__)

LAYOUT_POINT = 'point'
LAYOUT_LINE = 'line'

DRIVER = ogr.GetDriverByName(str('ESRI Shapefile'))
LINESTRINGS = ogr.wkbLineString, ogr.wkbLineString25D
MULTILINESTRINGS = ogr.wkbMultiLineString, ogr.wkbMultiLineString25D


def get_carpet(parameterized_line, distance, step):
    """
    Return M x N x 2 numpy array.

    It contains the centers of the ParameterizedLine, but perpendicularly
    repeated by step along the normals to the segments of the
    ParameterizedLine, until distance is reached.
    """
    # length must be uneven, and no less than 2 * distance / step + 1
    steps = math.ceil(distance / step)
    offsets_1d = step * np.arange(-steps, steps + 1)