Esempio n. 1
0
    def save_image_to_response(
            self, response, framenr=0,
            colormap=None, maxvalue=None):
        if colormap is None:
            colormap = 'PuBu'
        if maxvalue is None:
            maxvalue = self.maxvalue

        dataset = gdal.Open(self.get_dataset_path(framenr))
        colormap = get_mpl_cmap(colormap)

        # Colormaps from CSVs have a fixed maxvalue, which is in the
        # attribute 'csv_max_value'.
        maxvalue = getattr(colormap, 'csv_max_value', maxvalue)

        # Get data as masked array
        data = np.ma.masked_less(
            dataset.GetRasterBand(1).ReadAsArray(), LIMIT, copy=False)

        # Normalize
        normalize = colors.Normalize(vmin=0, vmax=maxvalue, clip=True)

        # Apply colormap
        rgba = colormap(normalize(data), bytes=True)

        # Turn into PIL image
        image = Image.fromarray(rgba)

        # Save into response
        response['Content-type'] = 'image/png'
        image.save(response, 'png')
Esempio n. 2
0
def get_response_for_getcounts(get_parameters):
    """ Return json with curve coordinates. """
    geometry = get_geometry(**get_parameters)
    layers = get_parameters['layers'].split(',')
    data = tuple(get_data(l, geometry) for l in layers)
    bins = np.arange(0, 256)
    histograms = [np.histogram(d.compressed(), bins)[0] for d in data]
    nonzeros = [h.nonzero() for h in histograms]
    nbins = [bins[:-1][n] for n in nonzeros]
    nhistograms = [h[n] for n, h in zip(nonzeros, histograms)]
    # Determine the ordering
    argsorts = [h.argsort() for h in nhistograms]
    arg10 = [a[:-10:-1] for a in argsorts]
    argrest = [a[-10::-1] for a in argsorts]
    # Use it to group
    rests = [h[argrest].sum() for h, a in zip(nhistograms, argsorts)]
    pairs = [np.array([b[arg10], h[arg10]]).transpose()
             for b, h, a in zip(nbins, nhistograms, argsorts)]
    # Prepare result data
    styles = get_parameters['styles'].split(',')
    colormaps = [
        get_mpl_cmap(s.split(':')[0], settings_module=settings)
        for s in styles]

    result = [[dict(label=LANDUSE.get(b, b),
                    data=d,
                    color=colors.rgb2hex((c(b))))
               for b, d in p.tolist()] for p, c in zip(pairs, colormaps)]

    for r, s in zip(result, rests):
        if s:
            r.append(dict(label='Overig', data=float(s), color='#ffffff'))
    return jsonify(result)
Esempio n. 3
0
def get_response_for_getcounts(get_parameters):
    """ Return json with curve coordinates. """
    geometry = get_geometry(**get_parameters)
    layers = get_parameters['layers'].split(',')
    data = tuple(get_data(l, geometry) for l in layers)
    bins = np.arange(0, 256)
    histograms = [np.histogram(d.compressed(), bins)[0] for d in data]
    nonzeros = [h.nonzero() for h in histograms]
    nbins = [bins[:-1][n] for n in nonzeros]
    nhistograms = [h[n] for n, h in zip(nonzeros, histograms)]
    # Determine the ordering
    argsorts = [h.argsort() for h in nhistograms]
    arg10 = [a[:-10:-1] for a in argsorts]
    argrest = [a[-10::-1] for a in argsorts]
    # Use it to group
    rests = [h[argrest].sum() for h, a in zip(nhistograms, argsorts)]
    pairs = [
        np.array([b[arg10], h[arg10]]).transpose()
        for b, h, a in zip(nbins, nhistograms, argsorts)
    ]
    # Prepare result data
    styles = get_parameters['styles'].split(',')
    colormaps = [
        get_mpl_cmap(s.split(':')[0], settings_module=settings) for s in styles
    ]

    result = [[
        dict(label=LANDUSE.get(b, b), data=d, color=colors.rgb2hex((c(b))))
        for b, d in p.tolist()
    ] for p, c in zip(pairs, colormaps)]

    for r, s in zip(result, rests):
        if s:
            r.append(dict(label='Overig', data=float(s), color='#ffffff'))
    return jsonify(result)
Esempio n. 4
0
def get_image(data, style):
    """ Return PIL image. """
    parts = style.split(':')
    colormap = get_mpl_cmap(parts[0] if parts[0] else 'jet',
                            settings_module=settings)

    if isinstance(colormap, colors.ListedColormap):
        normalize = lambda x: x
    if (isinstance(colormap, colors.LinearSegmentedColormap)
            and hasattr(colormap, 'csv_max_value')):
        normalize = lambda x: x / colormap.csv_max_value
    else:
        normalize = colors.Normalize(*map(float_or_none, parts[1:]), clip=True)
    rgba = colormap(normalize(data), bytes=True)
    return Image.fromarray(rgba)
Esempio n. 5
0
def get_image(data, style):
    """ Return PIL image. """
    parts = style.split(':')
    colormap = get_mpl_cmap(
        parts[0] if parts[0] else 'jet',
        settings_module=settings)

    if isinstance(colormap, colors.ListedColormap):
        normalize = lambda x: x
    if (isinstance(colormap, colors.LinearSegmentedColormap) and
        hasattr(colormap, 'csv_max_value')):
        normalize = lambda x: x / colormap.csv_max_value
    else:
        normalize = colors.Normalize(*map(float_or_none, parts[1:]), clip=True)
    rgba = colormap(normalize(data), bytes=True)
    return Image.fromarray(rgba)
Esempio n. 6
0
def result_legend(result, presentationlayer, colormap=None, maxvalue=None):
    presentationtype = presentationlayer.presentationtype

    default_colormap, default_maxvalue = presentationtype.colormap_info(
        project=result.scenario.main_project)

    try:
        maxvalue = float(maxvalue)
    except (ValueError, TypeError):
        maxvalue = default_maxvalue

    if colormap is None:
        colormap = default_colormap

    if not colormap.endswith('.csv'):
        show_maxvalue = True
        # Matplotlib colormap -- use given maxvalue, and always do 10 steps
        cmap = get_mpl_cmap(colormap)
        arr = np.array(values_in_range(maxvalue, 10))
        # Color the way that the grids are colored
        normalize = colors.Normalize(vmin=0, vmax=maxvalue)
        rgba = cmap(normalize(arr), bytes=True)

        legend = [
            (arr[i], rgba_to_html(tuple(rgba[i])))
            for i in range(10)
            ]
    else:
        # Our own .csv colormaps.
        show_maxvalue = False
        cmap = ColorMap(os.path.join(
            settings.FLOODING_LIB_COLORMAP_DIR, colormap))
        legend = [
            (value, rgba_to_html(cmap.value_to_color(value)))
            for value in cmap.legend_values()
            ]

    return {
        'title': unicode(presentationtype),
        'content': legend,
        'colormaps': models.Colormap.colormaps(),
        'active_colormap': colormap,
        'current_maxvalue': maxvalue,
        'show_maxvalue': show_maxvalue,
        }
Esempio n. 7
0
def result_legend(result, presentationlayer, colormap=None, maxvalue=None):
    presentationtype = presentationlayer.presentationtype

    default_colormap, default_maxvalue = presentationtype.colormap_info(
        project=result.scenario.main_project)

    try:
        maxvalue = float(maxvalue)
    except (ValueError, TypeError):
        maxvalue = default_maxvalue

    if colormap is None:
        colormap = default_colormap

    if not colormap.endswith('.csv'):
        show_maxvalue = True
        # Matplotlib colormap -- use given maxvalue, and always do 10 steps
        cmap = get_mpl_cmap(colormap)
        arr = np.array(values_in_range(maxvalue, 10))
        # Color the way that the grids are colored
        normalize = colors.Normalize(vmin=0, vmax=maxvalue)
        rgba = cmap(normalize(arr), bytes=True)

        legend = [
            (arr[i], rgba_to_html(tuple(rgba[i])))
            for i in range(10)
            ]
    else:
        # Our own .csv colormaps.
        show_maxvalue = False
        cmap = ColorMap(os.path.join(
            settings.FLOODING_LIB_COLORMAP_DIR, colormap))
        legend = [
            (value, rgba_to_html(cmap.value_to_color(value)))
            for value in cmap.legend_values()
            ]

    return {
        'title': unicode(presentationtype),
        'content': legend,
        'colormaps': models.Colormap.colormaps(),
        'active_colormap': colormap,
        'current_maxvalue': maxvalue,
        'show_maxvalue': show_maxvalue,
        }