Changeset d0a651d for src


Ignore:
Timestamp:
Apr 4, 2020, 12:39:38 PM (7 years ago)
Author:
Joachim Langenbach <joachim.langenbach@…>
Branches:
debian/bullseye, master
Children:
c5ca247
Parents:
b72d9c4
Message:
Location:
src/common
Files:
6 added
4 edited

Legend:

Unmodified
Added
Removed
  • src/common/bin/gnuboat-log-analyser

    rb72d9c4 rd0a651d  
    9090        statistics = False
    9191        tile_sizes = [256]
     92        skip_empty = True
    9293       
    9394        gdal.UseExceptions()
    … …  
    9899        parser.add_argument('output_directory', metavar='output_directory', type=str,
    99100                                                help='Write the Digital Terrain Model into this directory (output)')
    100         parser.add_argument('-v', '--statistics', dest='statistics', action='store_true',
     101        parser.add_argument('-v', '--verbose', dest='statistics', action='store_true',
    101102                                                help='Print some statistics of the input and result datasets')
    102103        parser.add_argument('-p', '--points-min', dest='points_min', type=int, default=density_min,
    … …  
    108109        parser.add_argument('-m', '--raster_file_max', dest='raster_file_size_max', default=1024, type=int,
    109110                                                help='Maximum size of temporary raster Tifs for tile generation in MB')
     111        parser.add_argument('-k', '--keep-empty', dest='skip_empty', action='store_false',
     112                                                help='Do not skip empty tiles (=move only one empty tile into place), when moving tiles into target directory')
    110113        arguments = parser.parse_args(argv)
    111114
    … …  
    134137                zoom_range = arguments.zoom_range
    135138       
    136         if arguments.high_res is not None:
     139        if arguments.high_res is not None and arguments.high_res:
    137140                tile_sizes.append(512)
    138141               
    139142        if arguments.raster_file_size_max is not None:
    140143                raster_file_size_max = arguments.raster_file_size_max
     144               
     145        if arguments.skip_empty is not None and not arguments.skip_empty:
     146                skip_empty = arguments.skip_empty
    141147               
    142148        # create temporary directory
    … …  
    194200        print ('  Processed {} points'.format(csv_callback.count()))
    195201
    196         print("Generating tiles")
    197202        # create ogr file info
    198         source_xml_file = os.path.join(temp_directory, "tmp_ogr_input_file.vrt")
     203        source_xml_file = os.path.join(temp_directory, '{}.vrt'.format(source_data_layer))
    199204        try:
    200205                output_file = open(source_xml_file, 'wb')
    … …  
    204209        xml_data_source = ET.Element("OGRVRTDataSource")
    205210        xml_layer = ET.SubElement(xml_data_source, "OGRVRTLayer", {"name": source_data_layer})
    206         xml_source = ET.SubElement(xml_layer, "SrcDataSource")
     211        xml_source = ET.SubElement(xml_layer, "SrcDataSource", {'relativeToVRT': "1"})
    207212        xml_source.text = corrected_joined_point_cloud_file_path
    208213        xml_geometry_type = ET.SubElement(xml_layer, "GeometryType")
    … …  
    215220        output_file.close()
    216221       
     222        # create csvt file
     223        try:
     224                output_file_csvt = open(os.path.join(temp_directory, '{}.csvt'.format(source_data_layer)), 'w')
     225        except IOError as error:
     226                print('ERROR: Could not open the output file for the ogr data source description: {}'.format(error))
     227                sys.exit(6)
     228        output_file_csvt.write('"Real","Real","Real"')
     229        output_file_csvt.close()
     230               
    217231        # preparing output_directory
    218232        if os.path.exists(output_directory):
    … …  
    248262                        result_paths = tilegen.run(source_xml_file, temp_directory, tile_slice)
    249263                        for path in result_paths:
    250                                 tilegen.move_tiles_in_place(path.path, os.path.join(output_directory, path.prefixes['density'], path.prefixes['tile_size']))
     264                                tilegen.move_tiles_in_place(path.path, os.path.join(output_directory, path.prefixes['density'], path.prefixes['tile_size']), skip_empty = skip_empty)
    251265                        bar.update(i)
    252266                        i += 1
  • src/common/gnuboat_common/spatial/tilegenerator.py

    rb72d9c4 rd0a651d  
    2727import math
    2828import copy
     29from pathlib import Path
     30from PIL import Image
    2931
    3032try:
    … …  
    8486
    8587class LngLatBbox(dict):
    86         def __init__(self, east, south, west, north):
    87                 super(LngLatBbox, self).__init__({'east': east, 'south': south, 'west': west, 'north': north})
    88                
     88        def __init__(self, west, south, east, north):
     89                super(LngLatBbox, self).__init__({'west': west, 'south': south, 'east': east, 'north': north})
     90               
     91        def west(self):
     92                return self['west']
     93       
     94        def south(self):
     95                return self['south']
     96       
    8997        def east(self):
    9098                return self['east']
    9199       
    92         def south(self):
    93                 return self['south']
    94        
    95         def west(self):
    96                 return self['west']
    97        
    98100        def north(self):
    99101                return self['north']
    … …  
    103105       
    104106        def from_mercantile_bbox(mercantile_bbox):
    105                 return LngLatBbox(mercantile_bbox.east, mercantile_bbox.south, mercantile_bbox.west, mercantile_bbox.north)
     107                return LngLatBbox(mercantile_bbox.west, mercantile_bbox.south, mercantile_bbox.east, mercantile_bbox.north)
    106108       
    107109        def from_dict(dictionary):
    108                 return LngLatBbox(dictionary['east'], dictionary['south'], dictionary['west'], dictionary['north'])
     110                return LngLatBbox(dictionary['west'], dictionary['south'], dictionary['east'], dictionary['north'])
    109111
    110112class RasterSlice(dict):
    … …  
    121123                super(RasterSlice, self).__init__({'lng_lat_box': lng_lat_box, 'zoom_range': zoom_range, 'tile_size': tile_size, 'grid_width': grid_width, 'grid_height': grid_height})
    122124               
    123         def lng_lat_box(self):
     125        def lng_lat_bbox(self):
    124126                return self['lng_lat_box']
    125127       
    … …  
    170172                        lng_lat_box is of Type LngLatBbox
    171173                """
    172                 tile_bounding = mercantile.bounding_tile(lng_lat_box.west, lng_lat_box.south, lng_lat_box.east, lng_lat_box.north)
     174                tile_bounding = mercantile.bounding_tile(lng_lat_box.west(), lng_lat_box.south(), lng_lat_box.east(), lng_lat_box.north())
    173175                if tile_bounding.z > zoom_range.minimum():
    174176                        return LngLatBbox.from_mercantile_bbox(mercantile.bounds(mercantile.parent(tile_bounding, zoom=zoom_range.minimum())))
    … …  
    193195                for tile_size in tile_sizes:
    194196                        # fitting to tile borders
    195                         lng_lat_box = self.fit_extent_to_tiles(mercantile.LngLatBbox(west, south, east, north), zoom_range)
    196                         tiles_zoom_min = mercantile.tiles(lng_lat_box.west(), lng_lat_box.south(), lng_lat_box.east(), lng_lat_box.north(), zoom_range.minimum())
     197                        lng_lat_box = self.fit_extent_to_tiles(LngLatBbox(west, south, east, north), zoom_range)
     198                        # The lng_lat_box is exactly on the border between tiles. Since there are rounding errors,
     199                        # we move the corner edges a very little bit (about a few mm) into the tile. This makes sure,
     200                        # that we only get those tiles returned, which are really in the lng_lat_box.
     201                        tiles_zoom_min = mercantile.tiles(lng_lat_box.west() + 1*10**-7, lng_lat_box.south() + 1*10**-7, lng_lat_box.east() - 1*10**-7, lng_lat_box.north() - 1*10**-7, zoom_range.minimum())
    197202                                       
    198                         # calculating size of raster file for GDT_Float32 = 24bits (at least the tif'S seen at my pc)
    199                         tile_count_max =  math.floor(raster_file_size_max / (tile_size**2 * 24))
    200                         delta_zoom = math.floor(math.log(tile_count_max) / math.log(4))
     203                        # calculating size of raster file for GDT_Float32 = 32bits
     204                        delta_zoom = math.floor(math.log(raster_file_size_max / (tile_size**2 * 32)) / math.log(4))
    201205                        steps = math.floor((zoom_range.maximum() - zoom_range.minimum()) / delta_zoom)
    202206                        zoom_steps = []
    … …  
    204208                        while step < zoom_range.maximum():
    205209                                zoom_steps.append(step)
    206                                 if step + math.floor(1.5 * delta_zoom) > zoom_range.maximum():
    207                                         break
    208                                 step += delta_zoom
     210                                step += delta_zoom + 1
    209211                        for tile in tiles_zoom_min:
    210                                 raster_slices += self._slice_tile(tile, zoom_steps, zoom_range.maximum(), tile_count_max, tile_size)
     212                                raster_slices += self._slice_tile(tile, zoom_steps, zoom_range.maximum(), tile_size, source_layer)
    211213                return raster_slices
    212214
    213         def _slice_tile(self, parent_tile, zoom_steps, zoom_total_max, tiles_per_slice, tile_size):
     215        def _slice_tile(self, parent_tile, zoom_steps, zoom_total_max, tile_size, source_layer, tiles_with_geometry = True):
    214216                if len(zoom_steps) < 1:
    215217                        raise ValueError('No zoomsteps given to slice tile generation')
    … …  
    232234                        zoom_min_new = zoom_steps_new[0]
    233235                        for child in mercantile.children(parent_tile, zoom=zoom_min_new):
    234                                 raster_slices += self._slice_tile(child, zoom_steps_new, zoom_total_max, tiles_per_slice, tile_size)
     236                                # test, if tile has geometry
     237                                lng_lat_box = mercantile.bounds(child)
     238                                source_layer.SetSpatialFilterRect(lng_lat_box.west, lng_lat_box.south, lng_lat_box.east, lng_lat_box.north)
     239                                if source_layer.GetNextFeature() or not tiles_with_geometry:
     240                                        raster_slices += self._slice_tile(child, zoom_steps_new, zoom_total_max, tile_size, source_layer, tiles_with_geometry = tiles_with_geometry)
     241                                source_layer.SetSpatialFilter(None)
    235242                return raster_slices
    236243
    … …  
    309316                        height = tile_slice.grid_height(),
    310317                        outputSRS = "WGS84",
    311                         outputBounds = [tile_slice.lng_lat_box().east(), tile_slice.lng_lat_box().south(), tile_slice.lng_lat_box().west(), tile_slice.lng_lat_box().north()],
     318                        outputBounds = [tile_slice.lng_lat_bbox().west(), tile_slice.lng_lat_bbox().north(), tile_slice.lng_lat_bbox().east(), tile_slice.lng_lat_bbox().south()],
    312319                        noData = nodata_value,
    313320                        layers = layers,
    314                         #spatFilter = (tile_slice.lng_lat_box().east(), tile_slice.lng_lat_box().south(), tile_slice.lng_lat_box().west(), tile_slice.lng_lat_box().north()),
     321                        spatFilter = (tile_slice.lng_lat_bbox().west(), tile_slice.lng_lat_bbox().south(), tile_slice.lng_lat_bbox().east(), tile_slice.lng_lat_bbox().north()),
    315322                        algorithm = gridding_algorithm
    316323                )
    … …  
    363370                subprocess.run(['gdal2tiles-gnuboat.py', '-q', '-w', 'none', '--tilesize={}'.format(tile_size), '-z', tile_zoom_option, '-t', title, input_file, output_directory], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    364371
    365         def move_tiles_in_place(self, source_path, target_path):
    366                 if not os.path.exists(target_path):
    367                         target_parent = os.path.dirname(target_path)
    368                         if not os.path.exists(target_parent):
    369                                 os.makedirs(target_parent)
    370                         shutil.copytree(source_path, target_path)
    371                         return
    372                 for item in os.listdir(source_path):
    373                         src = os.path.join(source_path, item)
    374                         if os.path.isdir(src):
    375                                 target_path_new = os.path.join(target_path, item)
    376                                 if os.path.exists(target_path_new):
    377                                         self.move_tiles_in_place(src, target_path_new)
    378                                 else:
    379                                         if not os.path.exists(target_path):
    380                                                 os.makedirs(target_path)
    381                                         shutil.copytree(src, target_path_new)
     372        def move_tiles_in_place(self, source_path, target_path, skip_empty = True):
     373                """
     374                        Moves the generated tiles from the source_path into the target_path.
     375                        It moves file per file, so that the tiles are going to be integrated into an existing folder.
     376                        If skip_emtpy = True only one empty tile is copied to the top level directory. All other empty
     377                        tiles are not moved into target_path.
     378                """
     379                copied_empty_tile = False
     380               
     381                src_path = Path(source_path)
     382                trg_path = Path(target_path)
     383                empty_tile = trg_path.joinpath('empty_tile.png')
     384                for path in Path(source_path).rglob('*.png'):
     385                        # Substract source_path from path and make it relative to
     386                        # target_path
     387                        relative = path.relative_to(src_path)
     388                        relative_path = trg_path.joinpath(relative)
     389                        if self._tile_is_empty(path) and skip_empty:
     390                                if not copied_empty_tile:
     391                                        if not empty_tile.parent.exists():
     392                                                os.makedirs(empty_tile.parent)
     393                                        shutil.copy(path, empty_tile)
     394                                        copied_empty_tile = True
    382395                        else:
    383                                 if not os.path.exists(target_path):
    384                                         os.makedirs(target_path)
    385                                 shutil.copy(src, target_path)
     396                                if not relative_path.parent.exists():
     397                                        os.makedirs(relative_path.parent)
     398                                shutil.copy(path, relative_path)
    386399
    387400        def _datasource_open(self, source_file):
    … …  
    392405                        raise ReferenceError('No layers in input file')
    393406                return datasource
     407
     408        def _tile_is_empty(self, tile_file_path):
     409                is_empty = True
     410                colors_tmp = set()
     411                colors_tmp_transparent = set()
     412               
     413                img = Image.open(tile_file_path)
     414                # calculate histogram for blue channel
     415                colors_img = img.getcolors(256)
     416                if not colors_img:
     417                        return False
     418                else:
     419                        for color in colors_img:
     420                                color_hex = ''.join('{:02X}'.format(value) for value in color[1])
     421                                if color[1][3] != 0:
     422                                        return False
     423                return True
    394424
    395425        #def contours_create():
  • src/common/setup.py

    rb72d9c4 rd0a651d  
    2929        "pytz",
    3030        "pynmea2",
    31         "gdal",
     31        "numpy",
     32        "gdal<=2.4.3",
    3233        "mercantile",
     34        "pathlib",
     35        "Pillow",
     36        "requests",
     37        "progressbar2",
    3338]
    3439
  • src/common/tox.ini

    rb72d9c4 rd0a651d  
    44
    55[testenv]
    6 deps =
    7         pytest
     6setenv =
     7        CPLUS_INCLUDE_PATH=/usr/include/gdal
     8        C_INCLUDE_PATH=/usr/include/gdal
     9deps = -rrequirements.txt
     10          pytest
     11install_command = pip install -U {opts} {packages}
    812commands =
    913        pytest
Note: See TracChangeset for help on using the changeset viewer.