Beispiel #1
0
        def __init__(self):
            BaseWMSFactory.__init__(self)
            for data in datas:
                name = data['name']
                title = data['long_name']      
                data = base_path+"/ecohealth/"+name+'.asc'
                
                layer = mapnik.Layer(name,"+init=epsg:4326")
                layer.datasource = mapnik.Gdal(file=str(data),band=1) 
                layer.title = title
                layer.queryable = True
                layer.wms_srs = None
                style = mapnik.Style()
                rule = mapnik.Rule()
                sym = mapnik.RasterSymbolizer()
                sym.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR, mapnik.Color("transparent"))
                scale = getEcohealthScale(name)
                for color in scale:
                    sym.colorizer.add_stop(color['stop'], mapnik.Color(*color['color']))
                rule.symbols.append(sym)
                style.rules.append(rule)

                self.register_style(name,style)
                self.register_layer(layer, name, (name,))
            self.finalize()
Beispiel #2
0
    def style_map(self, Map):
        style = mapnik.Style()
        rule = mapnik.Rule()

        sym = mapnik.RasterSymbolizer()
        sym.opacity = self.opacity

        colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_DISCRETE,
                                           mapnik.Color('white'))
        # colorizer.epsilon = 0.001
        if self.colormap:
            for stop in self.colormap:
                colorizer.add_stop(stop['quantity'],
                                   mapnik.Color(stop['color'].encode('ascii')))

        sym.colorizer = colorizer

        rule.symbols.append(sym)
        style.rules.append(rule)

        Map.append_style('Raster Style', style)

        lyr = mapnik.Layer('GDAL Layer from TIFF', self.layer_srs)

        lyr.datasource = mapnik.Gdal(base=os.path.dirname(self.vrt_path),
                                     file=os.path.basename(self.vrt_path),
                                     band=self.mapnik_band)

        lyr.styles.append('Raster Style')

        Map.layers.append(lyr)

        return Map
Beispiel #3
0
def get_raster_map():
    m = mapnik.Map(map_width, map_height)
    m.background = mapnik.Color('black')
    m.srs = map_srs
    s = mapnik.Style()
    r = mapnik.Rule()
    raster_symbolizer = mapnik.RasterSymbolizer()
    
    raster_symbolizer.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR, mapnik.Color("transparent"))
    
    raster_symbolizer.colorizer.add_stop(0.0, mapnik.COLORIZER_LINEAR, mapnik.Color("black"))
    raster_symbolizer.colorizer.add_stop(1.0, mapnik.COLORIZER_LINEAR, mapnik.Color("white"))
    


    r.symbols.append(raster_symbolizer)

    s.rules.append(r)

    m.append_style('raster_style', s)

    lyr = mapnik.Layer('urban')
    lyr.datasource = mapnik.Gdal(base='./ne_110m_admin_0_countries', file='urban19901.tif', band=1)
    lyr.styles.append('raster_style')
    m.layers.append(lyr)
    return m
def test_raster_warping_does_not_overclip_source():
    lyrSrs = "+init=epsg:32630"
    mapSrs = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'
    lyr = mapnik.Layer('dataraster', lyrSrs)
    if 'gdal' in mapnik.DatasourceCache.plugin_names():
        lyr.datasource = mapnik.Gdal(
            file = '../data/raster/dataraster.tif',
            band = 1,
            )
        sym = mapnik.RasterSymbolizer()
        sym.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_DISCRETE, mapnik.Color(255,255,0))
        rule = mapnik.Rule()
        rule.symbols.append(sym)
        style = mapnik.Style()
        style.rules.append(rule)
        _map = mapnik.Map(256,256, mapSrs)
        _map.background=mapnik.Color('white')
        _map.append_style('foo', style)
        lyr.styles.append('foo')
        _map.layers.append(lyr)
        _map.zoom_to_box(mapnik.Box2d(3,42,4,43))

        im = mapnik.Image(_map.width,_map.height)
        mapnik.render(_map, im)
        expected_file = './images/support/raster_warping_does_not_overclip_source.png'
        actual_file = '/tmp/' + os.path.basename(expected_file)
        im.save(actual_file,'png32')
        if not os.path.exists(expected_file) or os.environ.get('UPDATE'):
            im.save(expected_file,'png32')
        actual = mapnik.Image.open(actual_file)
        expected = mapnik.Image.open(expected_file)
        eq_(actual.tostring('png32'),expected.tostring('png32'), 'failed comparing actual (%s) and expected (%s)' % (actual_file,expected_file))
Beispiel #5
0
def test_raster_warping_does_not_overclip_source():
    lyrSrs = "+init=epsg:32630"
    mapSrs = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'
    lyr = mapnik.Layer('dataraster', lyrSrs)
    if 'gdal' in mapnik.DatasourceCache.plugin_names():
        lyr.datasource = mapnik.Gdal(
            file='../data/raster/dataraster.tif',
            band=1,
        )
        sym = mapnik.RasterSymbolizer()
        sym.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_DISCRETE,
                                               mapnik.Color(255, 255, 0))
        rule = mapnik.Rule()
        rule.symbols.append(sym)
        style = mapnik.Style()
        style.rules.append(rule)
        _map = mapnik.Map(256, 256, mapSrs)
        _map.background = mapnik.Color('white')
        _map.append_style('foo', style)
        lyr.styles.append('foo')
        _map.layers.append(lyr)
        _map.zoom_to_box(mapnik.Box2d(3, 42, 4, 43))

        im = mapnik.Image(_map.width, _map.height)
        mapnik.render(_map, im)
        assert im.view(0, 200, 1, 1).tostring() == '\xff\xff\x00\xff'
Beispiel #6
0
def test_raster_warping():
    lyrSrs = "+init=epsg:32630"
    mapSrs = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'
    lyr = mapnik.Layer('dataraster', lyrSrs)
    if 'gdal' in mapnik.DatasourceCache.plugin_names():
        lyr.datasource = mapnik.Gdal(
            file='../data/raster/dataraster.tif',
            band=1,
        )
        sym = mapnik.RasterSymbolizer()
        sym.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_DISCRETE,
                                               mapnik.Color(255, 255, 0))
        rule = mapnik.Rule()
        rule.symbols.append(sym)
        style = mapnik.Style()
        style.rules.append(rule)
        _map = mapnik.Map(256, 256, mapSrs)
        _map.append_style('foo', style)
        lyr.styles.append('foo')
        _map.layers.append(lyr)
        map_proj = mapnik.Projection(mapSrs)
        layer_proj = mapnik.Projection(lyrSrs)
        prj_trans = mapnik.ProjTransform(map_proj, layer_proj)
        _map.zoom_to_box(prj_trans.backward(lyr.envelope()))

        im = mapnik.Image(_map.width, _map.height)
        mapnik.render(_map, im)
        imdata = im.tostring()
        assert contains_word('\xff\xff\x00\xff', imdata)
Beispiel #7
0
        def __init__(self):
            BaseWMSFactory.__init__(self)

            layer = mapnik.Layer('TOP', modis_srs)
            layer.datasource = mapnik.Gdal(file=str(data),band=1) 
            layer.title = "Modis VI Layer"
            layer.queryable = True
            layer.wms_srs = None
            style = mapnik.Style()
            rule = mapnik.Rule()
            sym = mapnik.RasterSymbolizer()
            sym.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_DISCRETE, mapnik.Color("transparent"))
            scale = getModisScale(product)
            for color in scale:
                sym.colorizer.add_stop(color['stop'], mapnik.Color(*color['color']))
            rule.symbols.append(sym)
            style.rules.append(rule)
            self.register_style('modis_style', style)
            self.register_layer(layer, "modis_style",("modis_style",))

            layer = mapnik.Layer('ocean_mask')
            layer.datasource = mapnik.Shapefile(file=str("/data/health/data1/web/data/shapes/50m_ocean.shp"))
            layer.queryable = True
            layer.wms_srs = None
            style = mapnik.Style()
            rule = mapnik.Rule()
            poly_sym = mapnik.PolygonSymbolizer(mapnik.Color('#50649B'))
            rule.symbols.append(poly_sym)
            style.rules.append(rule)
            self.register_style('mask_style', style)
            self.register_layer(layer, "mask_style",("mask_style",))
Beispiel #8
0
 def create_colorizer(self):
     band = self.band
     colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR,
                                        mapnik.Color('#00000000'))
     for stop, color in band.palette:
         colorizer.add_stop(stop, mapnik.COLORIZER_LINEAR,
                            mapnik.Color(str(color)))
     return colorizer
Beispiel #9
0
    def _colorizerFromStyle(self, style):
        """
        Add a specified style to a mapnik raster symbolizer.

        :param style: a style object.
        :returns: a mapnik raster colorizer.
        """
        try:
            scheme = style.get('scheme', 'linear')
            mapnik_scheme = getattr(mapnik,
                                    'COLORIZER_{}'.format(scheme.upper()))
        except AttributeError:
            mapnik_scheme = mapnik.COLORIZER_DISCRETE
            raise TileSourceException(
                'Scheme has to be either "discrete" or "linear".')
        colorizer = mapnik.RasterColorizer(mapnik_scheme,
                                           mapnik.Color(0, 0, 0, 0))
        bandInfo = self.getOneBandInformation(style['band'])
        minimum = style.get('min', 0)
        maximum = style.get('max', 255)
        minimum = bandInfo[minimum] if minimum in ('min', 'max') else minimum
        maximum = bandInfo[maximum] if maximum in ('min', 'max') else maximum
        if minimum == 'auto':
            if not (0 <= bandInfo['min'] <= 255
                    and 1 <= bandInfo['max'] <= 255):
                minimum = bandInfo['min']
            else:
                minimum = 0
        if maximum == 'auto':
            if not (0 <= bandInfo['min'] <= 255
                    and 1 <= bandInfo['max'] <= 255):
                maximum = bandInfo['max']
            else:
                maximum = 255
        if style.get('palette') == 'colortable':
            for value, color in enumerate(bandInfo['colortable']):
                colorizer.add_stop(value, mapnik.Color(*color))
        else:
            colors = style.get('palette', ['#000000', '#ffffff'])
            if not isinstance(colors, list):
                colors = self.getHexColors(colors)
            else:
                colors = [
                    color if isinstance(color, six.binary_type) else
                    color.encode('utf8') for color in colors
                ]
            if len(colors) < 2:
                raise TileSourceException(
                    'A palette must have at least 2 colors.')
            values = self.interpolateMinMax(minimum, maximum, len(colors))
            for value, color in sorted(zip(values, colors)):
                try:
                    colorizer.add_stop(value, mapnik.Color(color))
                except RuntimeError:
                    raise TileSourceException(
                        'Mapnik failed to parse color %r.' % color)

        return colorizer
Beispiel #10
0
def test_dataraster_coloring():
    srs = '+init=epsg:32630'
    lyr = mapnik.Layer('dataraster')
    if 'gdal' in mapnik.DatasourceCache.plugin_names():
        lyr.datasource = mapnik.Gdal(
            file='../data/raster/dataraster.tif',
            band=1,
        )
        lyr.srs = srs
        _map = mapnik.Map(256, 256, srs)
        style = mapnik.Style()
        rule = mapnik.Rule()
        sym = mapnik.RasterSymbolizer()
        # Assigning a colorizer to the RasterSymbolizer tells the later
        # that it should use it to colorize the raw data raster
        colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_DISCRETE,
                                           mapnik.Color("transparent"))

        for value, color in [
            (0, "#0044cc"),
            (10, "#00cc00"),
            (20, "#ffff00"),
            (30, "#ff7f00"),
            (40, "#ff0000"),
            (50, "#ff007f"),
            (60, "#ff00ff"),
            (70, "#cc00cc"),
            (80, "#990099"),
            (90, "#660066"),
            (200, "transparent"),
        ]:
            colorizer.add_stop(value, mapnik.Color(color))
        sym.colorizer = colorizer
        rule.symbols.append(sym)
        style.rules.append(rule)
        _map.append_style('foo', style)
        lyr.styles.append('foo')
        _map.layers.append(lyr)
        _map.zoom_to_box(lyr.envelope())

        im = mapnik.Image(_map.width, _map.height)
        mapnik.render(_map, im)
        expected_file = './images/support/dataraster_coloring.png'
        actual_file = '/tmp/' + os.path.basename(expected_file)
        im.save(actual_file, 'png32')
        if not os.path.exists(expected_file) or os.environ.get('UPDATE'):
            im.save(expected_file, 'png32')
        actual = mapnik.Image.open(actual_file)
        expected = mapnik.Image.open(expected_file)
        eq_(
            actual.tostring('png32'), expected.tostring('png32'),
            'failed comparing actual (%s) and expected (%s)' %
            (actual_file, expected_file))
Beispiel #11
0
def test_dataraster_coloring():
    srs = '+init=epsg:32630'
    lyr = mapnik.Layer('dataraster')
    if 'gdal' in mapnik.DatasourceCache.plugin_names():
        lyr.datasource = mapnik.Gdal(
            file='../data/raster/dataraster.tif',
            band=1,
        )
        lyr.srs = srs
        _map = mapnik.Map(256, 256, srs)
        style = mapnik.Style()
        rule = mapnik.Rule()
        sym = mapnik.RasterSymbolizer()
        # Assigning a colorizer to the RasterSymbolizer tells the later
        # that it should use it to colorize the raw data raster
        sym.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_DISCRETE,
                                               mapnik.Color("transparent"))

        for value, color in [
            (0, "#0044cc"),
            (10, "#00cc00"),
            (20, "#ffff00"),
            (30, "#ff7f00"),
            (40, "#ff0000"),
            (50, "#ff007f"),
            (60, "#ff00ff"),
            (70, "#cc00cc"),
            (80, "#990099"),
            (90, "#660066"),
            (200, "transparent"),
        ]:
            sym.colorizer.add_stop(value, mapnik.Color(color))
        rule.symbols.append(sym)
        style.rules.append(rule)
        _map.append_style('foo', style)
        lyr.styles.append('foo')
        _map.layers.append(lyr)
        _map.zoom_to_box(lyr.envelope())

        im = mapnik.Image(_map.width, _map.height)
        mapnik.render(_map, im)
        # save a png somewhere so we can see it
        save_data('test_dataraster_coloring.png', im.tostring('png'))
        imdata = im.tostring()
        # we have some values in the [20,30) interval so check that they're colored
        assert contains_word('\xff\xff\x00\xff', imdata)
def test_get_color_exact():
    #setup
    colorizer = mapnik.RasterColorizer()
    colorizer.default_color = mapnik.Color(0, 0, 0, 0)
    colorizer.default_mode = mapnik.COLORIZER_EXACT

    colorizer.add_stop(10, mapnik.Color(100, 100, 100, 100))
    colorizer.add_stop(20, mapnik.Color(200, 200, 200, 200))

    #should be default colour
    eq_(colorizer.get_color(-50), mapnik.Color(0, 0, 0, 0))
    eq_(colorizer.get_color(11), mapnik.Color(0, 0, 0, 0))
    eq_(colorizer.get_color(20.001), mapnik.Color(0, 0, 0, 0))

    #should be stop 1
    eq_(colorizer.get_color(10), mapnik.Color(100, 100, 100, 100))

    #should be stop 2
    eq_(colorizer.get_color(20), mapnik.Color(200, 200, 200, 200))
def test_get_color_discrete():
    #setup
    colorizer = mapnik.RasterColorizer()
    colorizer.default_color = mapnik.Color(0, 0, 0, 0)
    colorizer.default_mode = mapnik.COLORIZER_DISCRETE

    colorizer.add_stop(10, mapnik.Color(100, 100, 100, 100))
    colorizer.add_stop(20, mapnik.Color(200, 200, 200, 200))

    #should be default colour
    eq_(colorizer.get_color(-50), mapnik.Color(0, 0, 0, 0))
    eq_(colorizer.get_color(0), mapnik.Color(0, 0, 0, 0))

    #now in stop 1
    eq_(colorizer.get_color(10), mapnik.Color(100, 100, 100, 100))
    eq_(colorizer.get_color(19), mapnik.Color(100, 100, 100, 100))

    #now in stop 2
    eq_(colorizer.get_color(20), mapnik.Color(200, 200, 200, 200))
    eq_(colorizer.get_color(1000), mapnik.Color(200, 200, 200, 200))
def test_get_color_linear():
    #setup
    colorizer = mapnik.RasterColorizer()
    colorizer.default_color = mapnik.Color(0, 0, 0, 0)
    colorizer.default_mode = mapnik.COLORIZER_LINEAR

    colorizer.add_stop(10, mapnik.Color(100, 100, 100, 100))
    colorizer.add_stop(20, mapnik.Color(200, 200, 200, 200))

    #should be default colour
    eq_(colorizer.get_color(-50), mapnik.Color(0, 0, 0, 0))
    eq_(colorizer.get_color(9.9), mapnik.Color(0, 0, 0, 0))

    #should be stop 1
    eq_(colorizer.get_color(10), mapnik.Color(100, 100, 100, 100))

    #should be stop 2
    eq_(colorizer.get_color(20), mapnik.Color(200, 200, 200, 200))

    #half way between stops 1 and 2
    eq_(colorizer.get_color(15), mapnik.Color(150, 150, 150, 150))

    #after stop 2
    eq_(colorizer.get_color(100), mapnik.Color(200, 200, 200, 200))
Beispiel #15
0
def tile(request, version, rasterlayer_id, zoom, x, y):
    try:
        rasterlayer = RasterLayer.objects.get(id=rasterlayer_id)

        if version != "1.0":
            raise Http404

        zoom = int(zoom)
        x = int(x)
        y = int(y)

        if zoom < 0 or zoom > MAX_ZOOM_LEVEL:
            raise Http404

        xExtent = _unitsPerPixel(zoom) * TILE_WIDTH
        yExtent = _unitsPerPixel(zoom) * TILE_HEIGHT

        minLong = x * xExtent - 20026376.39
        minLat = y * yExtent - 20026376.39
        maxLong = minLong + xExtent
        maxLat = minLat + yExtent

        map = mapnik.Map(
            TILE_WIDTH, TILE_HEIGHT,
            "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +units=m +k=1.0 +nadgrids=@null +no_defs"
        )
        map.background = mapnik.Color("#00000000")
        raster = mapnik.Layer("raster")
        raster.srs = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over"

        # se carga el archivo
        file_path = rasterlayer.file_path
        file_name = rasterlayer.file_name
        file_format = rasterlayer.file_format
        ext = file_format
        file_name = file_name.replace(ext, "-proj" + ext)
        fullName = join(file_path, file_name)
        numBands = rasterlayer.numBands

        # se obtiene el estilo
        layer_styles = Style.objects.filter(layers__id=rasterlayer.id)
        if numBands == 1 and layer_styles.count() == 1:
            raster.datasource = mapnik.Gdal(file=fullName, band=1)
        else:
            raster.datasource = mapnik.Gdal(file=fullName)

        style = mapnik.Style()
        rule = mapnik.Rule()

        symbol = mapnik.RasterSymbolizer()

        # agregar estilo si existe
        if layer_styles.count() == 1:
            layer_style = layer_styles[0]
            colorMap = getColorMap(layer_style)
            c = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR,
                                       mapnik.Color(0, 0, 0, 0))

            for entry in colorMap:
                color = entry["color"]
                quantity = entry["quantity"]
                c.add_stop(quantity, mapnik.Color(color))

            symbol.colorizer = c

        rule.symbols.append(symbol)
        style.rules.append(rule)
        map.append_style("estilo", style)
        raster.styles.append("estilo")
        map.layers.append(raster)

        map.zoom_to_box(mapnik.Box2d(minLong, minLat, maxLong, maxLat))
        image = mapnik.Image(TILE_WIDTH, TILE_HEIGHT)
        mapnik.render(map, image)

        imageData = image.tostring('png')
        return HttpResponse(imageData, content_type="image/png")
    except:
        traceback.print_exc()
        return HttpResponse("Error")
Beispiel #16
0
import mapnik
import os
import fnmatch
import logging

# Set up logging
logging.basicConfig(format="%(asctime)s|%(levelname)s|%(message)s",
                    level=logging.INFO)

# Parameters
rastDir = "C:/Projects/BirthsAndPregnanciesMapping/results/raster"
outPngDir = "C:/Projects/BirthsAndPregnanciesMapping/results/png"
max_img_size = 5000  # Max width or height of output image

# Define raster color scheme
c = mapnik.RasterColorizer(mapnik.COLORIZER_DISCRETE,
                           mapnik.Color(54, 97, 255))
c.add_stop(0, mapnik.COLORIZER_EXACT, mapnik.Color(87, 36, 255))
c.add_stop(0)  # Uses default colour value
c.add_stop(0.1, mapnik.Color(79, 159, 227))
c.add_stop(0.2, mapnik.Color(0, 255, 255))
c.add_stop(0.5, mapnik.Color(102, 255, 77))
c.add_stop(1, mapnik.Color(209, 255, 105))
c.add_stop(1.5, mapnik.Color(230, 230, 0))
c.add_stop(2, mapnik.Color(230, 153, 0))
c.add_stop(2.5, mapnik.Color(255, 64, 0))
c.add_stop(10, mapnik.Color(168, 0, 0))

# Create style
style = mapnik.Style()
rule = mapnik.Rule()
symbolizer = mapnik.RasterSymbolizer()
Beispiel #17
0
def _add_elevation(m):
    s = mapnik.Style()
    r = mapnik.Rule()
    # rs = mapnik.RasterSymbolizer()
    # rs.opacity = 1.0
    # rs.scaling = 'bilinear'
    # rs.comp_op = 'multiply'

    rs = mapnik.RasterSymbolizer()

    # COLORIZER_DISCRETE is a binned/classified renderer.
    # Other options are COLORIZER_LINEAR (stretched) and
    # COLORIZER_EXACT (unique)
    rs.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_DISCRETE,
                                          mapnik.Color(0, 0, 0, 0))
    #rs.colorizer.add_stop(0, mapnik.Color(217, 217, 229))

    rs.colorizer.add_stop(250, mapnik.Color(58, 130, 72))
    rs.colorizer.add_stop(500, mapnik.Color(37, 117, 69))
    rs.colorizer.add_stop(1000, mapnik.Color(27, 75, 46))

    r.symbols.append(rs)
    s.rules.append(r)

    m.append_style('HillShade', s)

    # old ETOPO5 data from 1988 with poor resolution
    # https://www.eea.europa.eu/data-and-maps/data/world-digital-elevation-model-etopo5
    # ds = mapnik.Gdal(
    #     base = '/Users/larsga/Desktop/DEM_geotiff',
    #     file = 'alwdgg.tif',
    #     band = 1,
    # )
    # srs = '+proj=longlat +ellps=clrk66 +no_defs'

    # new, huge EU-EDM v1.0
    # https://land.copernicus.eu/imagery-in-situ/eu-dem/eu-dem-v1-0-and-derived-products
    # The x,y-coordinates in the tiles are based on the EPSG:3035
    # (ETRS89-LAEA) projection. ->
    # ds = mapnik.Gdal(
    #     base = '/Users/larsga/Desktop/EUDEM1',
    #     file = 'EUD_CP-DEMS_4500045000-AA.tif',
    #     band = 1,
    # )
    # srs = '+proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +no_defs'

    # ETOPO1
    # https://www.ngdc.noaa.gov/mgg/global/
    ds = mapnik.Gdal(
        base=SHAPEDIR + '/ETOPO1',
        file='ETOPO1_Ice_c_geotiff.tif',
        band=1,
    )
    srs = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'

    # ds = mapnik.Gdal(
    #     base = '/Users/larsga/Desktop/DTM50_UTM33_20200904',
    #     file = 'norge.tif',
    #     band = 1,
    # )
    # srs = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'

    layer = mapnik.Layer('Elevation')
    layer.datasource = ds
    layer.srs = srs

    layer.styles.append('HillShade')
    m.layers.append(layer)
Beispiel #18
0
import mapnik
import sys

diseases = ("cchf", "chik", "deng", "hat", "melio", "nwcl", "owcl", "scrub")
variants = ("1A", "1B", "1C", "2C", "2D", "3B", "4A", "5A", "6A")

for disease in diseases:
    for variant in variants:
        geotiff = "all/results/" + disease + "_" + variant + "/mean_prediction_masked.tif"
        png = "all/results/" + disease + "_" + variant + "/mean_prediction_masked.png"
        symbolizer = mapnik.RasterSymbolizer()
        colorizer = mapnik.RasterColorizer(
            default_mode=mapnik.COLORIZER_LINEAR,
            default_color=mapnik.Color("transparent"))
        symbolizer.colorizer = colorizer
        colorizer.add_stop(-9999.0, mapnik.Color("#000000"))
        colorizer.add_stop(0.0, mapnik.Color("#91ab84"))
        colorizer.add_stop(0.25, mapnik.Color("#c3d4bb"))
        colorizer.add_stop(0.5, mapnik.Color("#ffffcb"))
        colorizer.add_stop(0.75, mapnik.Color("#cf93ba"))
        colorizer.add_stop(1.0, mapnik.Color("#a44883"))
        colorizer.add_stop(9999.0, mapnik.Color("#eaeaea"))
        style = mapnik.Style()
        rule = mapnik.Rule()
        rule.symbols.append(symbolizer)
        style.rules.append(rule)
        layer = mapnik.Layer("raster")
        layer.datasource = mapnik.Gdal(file=geotiff, nodata=-9999, band=1)
        layer.styles.append("raster")
        world = mapnik.Map(1656, 667)
        world.append_style("raster", style)
 def _test_data_subquery(lbl, pixtype, value):
     #
     #      3   8   13
     #    +---+---+---+
     #  3 | v | v | v |  NOTE: writes different values
     #    +---+---+---+        in 13,8 and 8,13
     #  8 | v | v | a |
     #    +---+---+---+
     # 13 | v | b | v |
     #    +---+---+---+
     #
     val_a = value / 3
     val_b = val_a * 2
     sql = "(select 3 as i, " \
           " ST_SetValues(" \
           "  ST_SetValues(" \
           "   ST_AsRaster(" \
           "    ST_MakeEnvelope(0,0,14,14), " \
           "    1.0, -1.0, '%s', %s" \
           "   ), " \
           "   11, 6, 5, 5, %s::float8" \
           "  )," \
           "  6, 11, 5, 5, %s::float8" \
           " ) as \"R\"" \
           ") as foo" % (pixtype,value, val_a, val_b)
     overview = ''
     rescale = 0
     clip = 0
     if rescale:
         lbl += ' Sc'
     if clip:
         lbl += ' Cl'
     ds = mapnik.PgRaster(dbname=MAPNIK_TEST_DBNAME,
                          table=sql,
                          raster_field='R',
                          use_overviews=0 if overview else 0,
                          band=1,
                          prescale_rasters=rescale,
                          clip_rasters=clip)
     fs = ds.featureset()
     feature = fs.next()
     eq_(feature['i'], 3)
     lyr = mapnik.Layer('data_subquery')
     lyr.datasource = ds
     expenv = mapnik.Box2d(0, 0, 14, 14)
     env = lyr.envelope()
     assert_almost_equal(env.minx, expenv.minx, places=0)
     assert_almost_equal(env.miny, expenv.miny, places=0)
     assert_almost_equal(env.maxx, expenv.maxx, places=0)
     assert_almost_equal(env.maxy, expenv.maxy, places=0)
     mm = mapnik.Map(15, 15)
     style = mapnik.Style()
     col = mapnik.RasterColorizer()
     col.default_mode = mapnik.COLORIZER_DISCRETE
     col.add_stop(val_a, mapnik.Color(0xff, 0x00, 0x00, 255))
     col.add_stop(val_b, mapnik.Color(0x00, 0xff, 0x00, 255))
     col.add_stop(value, mapnik.Color(0x00, 0x00, 0xff, 255))
     sym = mapnik.RasterSymbolizer()
     sym.colorizer = col
     rule = mapnik.Rule()
     rule.symbols.append(sym)
     style.rules.append(rule)
     mm.append_style('foo', style)
     lyr.styles.append('foo')
     mm.layers.append(lyr)
     mm.zoom_to_box(expenv)
     im = mapnik.Image(mm.width, mm.height)
     t0 = time.time()  # we want wall time to include IO waits
     mapnik.render(mm, im)
     lap = time.time() - t0
     log('T ' + str(lap) + ' -- ' + lbl + ' E:full')
     expected = 'images/support/pgraster/%s-%s-%s-%s.png' % (lyr.name, lbl,
                                                             pixtype, value)
     compare_images(expected, im)
    def _test_dataraster_16bsi_rendering(lbl, overview, rescale, clip):
        if rescale:
            lbl += ' Sc'
        if clip:
            lbl += ' Cl'
        ds = mapnik.PgRaster(dbname=MAPNIK_TEST_DBNAME,
                             table='"dataRaster"',
                             band=1,
                             use_overviews=1 if overview else 0,
                             prescale_rasters=rescale,
                             clip_rasters=clip)
        fs = ds.featureset()
        feature = fs.next()
        eq_(feature['rid'], 1)
        lyr = mapnik.Layer('dataraster_16bsi')
        lyr.datasource = ds
        expenv = mapnik.Box2d(-14637, 3903178, 1126863, 4859678)
        env = lyr.envelope()
        # As the input size is a prime number both horizontally
        # and vertically, we expect the extent of the overview
        # tables to be a pixel wider than the original, whereas
        # the pixel size in geographical units depends on the
        # overview factor. So we start with the original pixel size
        # as base scale and multiply by the overview factor.
        # NOTE: the overview table extent only grows north and east
        pixsize = 500  # see gdalinfo dataraster.tif
        pixsize = 2497  # see gdalinfo dataraster-small.tif
        tol = pixsize * max(overview.split(',')) if overview else 0
        assert_almost_equal(env.minx, expenv.minx)
        assert_almost_equal(env.miny, expenv.miny, delta=tol)
        assert_almost_equal(env.maxx, expenv.maxx, delta=tol)
        assert_almost_equal(env.maxy, expenv.maxy)
        mm = mapnik.Map(256, 256)
        style = mapnik.Style()
        col = mapnik.RasterColorizer()
        col.default_mode = mapnik.COLORIZER_DISCRETE
        col.add_stop(0, mapnik.Color(0x40, 0x40, 0x40, 255))
        col.add_stop(10, mapnik.Color(0x80, 0x80, 0x80, 255))
        col.add_stop(20, mapnik.Color(0xa0, 0xa0, 0xa0, 255))
        sym = mapnik.RasterSymbolizer()
        sym.colorizer = col
        rule = mapnik.Rule()
        rule.symbols.append(sym)
        style.rules.append(rule)
        mm.append_style('foo', style)
        lyr.styles.append('foo')
        mm.layers.append(lyr)
        mm.zoom_to_box(expenv)
        im = mapnik.Image(mm.width, mm.height)
        t0 = time.time()  # we want wall time to include IO waits
        mapnik.render(mm, im)
        lap = time.time() - t0
        log('T ' + str(lap) + ' -- ' + lbl + ' E:full')
        # no data
        eq_(im.view(1, 1, 1, 1).tostring(), '\x00\x00\x00\x00')
        eq_(im.view(255, 255, 1, 1).tostring(), '\x00\x00\x00\x00')
        eq_(im.view(195, 116, 1, 1).tostring(), '\x00\x00\x00\x00')
        # A0A0A0
        eq_(im.view(100, 120, 1, 1).tostring(), '\xa0\xa0\xa0\xff')
        eq_(im.view(75, 80, 1, 1).tostring(), '\xa0\xa0\xa0\xff')
        # 808080
        eq_(im.view(74, 170, 1, 1).tostring(), '\x80\x80\x80\xff')
        eq_(im.view(30, 50, 1, 1).tostring(), '\x80\x80\x80\xff')
        # 404040
        eq_(im.view(190, 70, 1, 1).tostring(), '\x40\x40\x40\xff')
        eq_(im.view(140, 170, 1, 1).tostring(), '\x40\x40\x40\xff')

        # Now zoom over a portion of the env (1/10)
        newenv = mapnik.Box2d(273663, 4024478, 330738, 4072303)
        mm.zoom_to_box(newenv)
        t0 = time.time()  # we want wall time to include IO waits
        mapnik.render(mm, im)
        lap = time.time() - t0
        log('T ' + str(lap) + ' -- ' + lbl + ' E:1/10')
        # nodata
        eq_(hexlify(im.view(255, 255, 1, 1).tostring()), '00000000')
        eq_(hexlify(im.view(200, 254, 1, 1).tostring()), '00000000')
        # A0A0A0
        eq_(hexlify(im.view(90, 232, 1, 1).tostring()), 'a0a0a0ff')
        eq_(hexlify(im.view(96, 245, 1, 1).tostring()), 'a0a0a0ff')
        # 808080
        eq_(hexlify(im.view(1, 1, 1, 1).tostring()), '808080ff')
        eq_(hexlify(im.view(128, 128, 1, 1).tostring()), '808080ff')
        # 404040
        eq_(hexlify(im.view(255, 0, 1, 1).tostring()), '404040ff')
Beispiel #21
0
import mapnik
import time

if __name__ == '__main__':
    start = time.time()
    m = mapnik.Map(256, 256)
    m.srs = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'
    s = mapnik.Style()
    r = mapnik.Rule()
    raster_symbolizer = mapnik.RasterSymbolizer()

    raster_symbolizer.colorizer = mapnik.RasterColorizer(
        mapnik.COLORIZER_LINEAR, mapnik.Color("transparent"))

    raster_symbolizer.colorizer.add_stop(0.0, mapnik.Color("black"))
    raster_symbolizer.colorizer.add_stop(1.0, mapnik.Color("white"))

    print -9999, raster_symbolizer.colorizer.get_color(-9999)
    print 0.0, raster_symbolizer.colorizer.get_color(0.0)
    print 1.0, raster_symbolizer.colorizer.get_color(1.0)
    print 0, raster_symbolizer.colorizer.get_color(0)
    print 1, raster_symbolizer.colorizer.get_color(1)
    print 0.5, raster_symbolizer.colorizer.get_color(0.5)

    r.symbols.append(raster_symbolizer)

    s.rules.append(r)

    m.append_style('raster_style', s)

    lyr = mapnik.Layer('urban')