Exemplo n.º 1
0
def test_render_numpy():
    """Save data to numpy binary."""
    arr = np.random.randint(0, 255, size=(3, 512, 512), dtype=np.uint8)
    mask = np.zeros((512, 512), dtype=np.uint8)

    res = utils.render(arr, mask=mask, img_format="npy")
    arr_res = np.load(BytesIO(res))
    assert arr_res.shape == (4, 512, 512)
    np.array_equal(arr, arr_res[0:3])
    np.array_equal(mask, arr_res[-1])

    res = utils.render(arr, img_format="npy")
    arr_res = np.load(BytesIO(res))
    assert arr_res.shape == (3, 512, 512)
    np.array_equal(arr, arr_res)

    res = utils.render(arr, img_format="npz")
    arr_res = np.load(BytesIO(res))
    assert arr_res.files == ["data"]
    assert arr_res["data"].shape == (3, 512, 512)
    np.array_equal(arr, arr_res["data"])

    res = utils.render(arr, mask, img_format="npz")
    arr_res = np.load(BytesIO(res))
    assert arr_res.files == ["data", "mask"]
    assert arr_res["data"].shape == (3, 512, 512)
    assert arr_res["mask"].shape == (512, 512)
    np.array_equal(arr, arr_res["data"])
    np.array_equal(mask, arr_res["mask"])
Exemplo n.º 2
0
def tiftile():
    x = request.args.get('x')
    y = request.args.get('y')
    z = request.args.get('z')
    tifName = request.args.get('tname')

    tifPath1 = "d:\\data\\3010\\{}.tif".format(tifName)

    try:
        dataset = rasterio.open(tifPath1)
        tile, mask = reader.tile(dataset, int(x), int(y), int(z), tilesize=256)
        dataset.close()
        min = 0
        max = 60

        renderData = np.array([tile[0], tile[1]+tile[2]*0.3, tile[2]])

        renderData = renderData.astype(np.uint8)
        mtdata = to_math_type(renderData)
        data = sigmoidal(mtdata, 10, 0.15)*255

        buffer = render(data.astype(np.uint8), mask=mask)
        return send_file(io.BytesIO(buffer), mimetype="image/png", attachment_filename="{}_{}_{}.jpg".format(x, y, z))
    except Exception as a:
        print(a)
        return abort(404)
    finally:
        pass
Exemplo n.º 3
0
def reformat(
    data: numpy.ndarray,
    mask: numpy.ndarray,
    img_format: ImageType,
    colormap: Optional[Dict[int, Tuple[int, int, int, int]]] = None,
    transform: Optional[affine.Affine] = None,
    crs: Optional[CRS] = None,
):
    """Reformat image data to bytes"""
    if img_format == ImageType.npy:
        sio = BytesIO()
        numpy.save(sio, (data, mask))
        sio.seek(0)
        content = sio.getvalue()
    else:
        driver = drivers[img_format.value]
        options = img_profiles.get(driver.lower(), {})
        if transform and crs and ImageType.tif in img_format:
            options = {"crs": crs, "transform": transform}

        content = render(data,
                         mask,
                         img_format=driver,
                         colormap=colormap,
                         **options)
    return content
Exemplo n.º 4
0
def _img(
    mosaicid: str = None,
    z: int = None,
    x: int = None,
    y: int = None,
    scale: int = 1,
    ext: str = None,
    url: str = None,
    pixel_selection: str = "first",
    resampling_method: str = "nearest",
) -> Tuple:
    """Handle tile requests."""
    if not mosaicid and not url:
        return ("NOK", "text/plain", "Missing 'MosaicID or URL' parameter")

    mosaic_path = _create_mosaic_path(mosaicid) if mosaicid else url
    with MosaicBackend(mosaic_path) as mosaic:
        assets = mosaic.tile(x, y, z)
        if not assets:
            return ("EMPTY", "text/plain", f"No assets found for tile {z}-{x}-{y}")

    tilesize = 256 * scale

    if pixel_selection == "last":
        pixel_selection = "first"
        assets = list(reversed(assets))

    with rasterio.Env(aws_session):
        pixsel_method = PIXSEL_METHODS[pixel_selection]
        tile, mask = mosaic_tiler(
            assets,
            x,
            y,
            z,
            usgs_tiler,
            tilesize=tilesize,
            pixel_selection=pixsel_method(),
            resampling_method=resampling_method,
        )

    if tile is None:
        return ("EMPTY", "text/plain", "empty tiles")

    if not ext:
        ext = "jpg" if mask.all() else "png"

    driver = "jpeg" if ext == "jpg" else ext
    options = img_profiles.get(driver, {})

    if ext == "tif":
        ext = "tiff"
        driver = "GTiff"
        options = geotiff_options(x, y, z, tilesize)

    return (
        "OK",
        f"image/{ext}",
        render(tile, mask, img_format=driver, **options),
    )
Exemplo n.º 5
0
def test_render_valid_colormapDict():
    """Create 'colormaped' PNG image buffer from one band array using discrete cmap."""
    arr = np.random.randint(0, 255, size=(1, 512, 512), dtype=np.uint8)
    cmap = {
        1: [255, 255, 255, 255],
        50: [255, 255, 0, 255],
        100: [255, 0, 0, 255],
        150: [0, 0, 255, 255],
    }
    assert utils.render(arr, colormap=cmap)
Exemplo n.º 6
0
def reformat(
    data: numpy.ndarray,
    mask: numpy.ndarray,
    img_format: ImageType,
    colormap: Optional[Dict[int, Tuple[int, int, int, int]]] = None,
    transform: Optional[affine.Affine] = None,
    crs: Optional[CRS] = None,
):
    """Reformat image data to bytes"""
    driver = drivers[img_format.value]
    options = img_profiles.get(driver.lower(), {})
    if transform and crs and ImageType.tif in img_format:
        options = {"crs": crs, "transform": transform}
    return render(data, mask, img_format=driver, colormap=colormap, **options)
Exemplo n.º 7
0
def _img(
    z: int = None,
    x: int = None,
    y: int = None,
    tile_size: Union[str, int] = 256,
    ext: str = 'png',
    url: str = None,
    encoding: str = 'terrarium',
    pixel_selection: str = "first",
    resampling_method: str = "nearest",
) -> Tuple:
    """Handle tile requests."""
    if not url:
        return ("NOK", "text/plain", "Missing URL parameter")

    tile_size = int(tile_size)
    assets = find_assets(x, y, z, url, tile_size)

    if assets is None:
        return ("NOK", "text/plain", "no assets found")

    rgb = load_assets(x,
                      y,
                      z,
                      assets,
                      tile_size,
                      input_format=url,
                      output_format=encoding,
                      pixel_selection=pixel_selection,
                      resampling_method=resampling_method)

    if rgb is None:
        return ("EMPTY", "text/plain", "empty tiles")

    driver = ext
    options = img_profiles.get(driver, {})

    if ext == "tif":
        ext = "tiff"
        driver = "GTiff"
        options = geotiff_options(x, y, z, tile_size)

    return (
        "OK",
        f"image/{ext}",
        render(rgb, img_format=driver, **options),
    )
Exemplo n.º 8
0
    def _get_tile(self, z, x, y, tileformat, color_ops=None):
        if tileformat == "jpg":
            tileformat = "jpeg"

        if not self.raster.tile_exists(z, x, y):
            raise web.HTTPError(404)

        data, mask = self.raster.read_tile(z, x, y)

        if len(data.shape) == 2:
            data = numpy.expand_dims(data, axis=0)

        if self.scale:
            nbands = data.shape[0]
            scale = self.scale
            if len(scale) != nbands:
                scale = scale * nbands

            for bdx in range(nbands):
                data[bdx] = numpy.where(
                    mask,
                    linear_rescale(data[bdx],
                                   in_range=scale[bdx],
                                   out_range=(0, 255)),
                    0,
                )

            data = data.astype(numpy.uint8)

        if color_ops:
            data = RasterTileHandler.apply_color_operations(data, color_ops)

        options = img_profiles.get(tileformat, {})

        return BytesIO(
            render(data,
                   mask=mask,
                   color_map=self.colormap,
                   img_format=tileformat,
                   **options))
Exemplo n.º 9
0
def _tile(
        z: int,
        x: int,
        y: int,
        scale: int = Query(
            1,
            gt=0,
            lt=4,
            description="Tile size scale. 1=256x256, 2=512x512..."),
        identifier: str = Query("WebMercatorQuad", title="TMS identifier"),
        filename: str = Query(...),
):
    """Handle /tiles requests."""
    tms = morecantile.tms.get(identifier)
    with COGReader(f"{filename}.tif", tms=tms) as cog:  # type: ignore
        tile, mask = cog.tile(x, y, z, tilesize=scale * 256)

    ext = ImageType.png
    driver = drivers[ext.value]
    options = img_profiles.get(driver.lower(), {})

    img = render(tile, mask, img_format="png", **options)

    return TileResponse(img, media_type=mimetype[ext.value])
Exemplo n.º 10
0
    def get(self,
            request,
            pk=None,
            project_pk=None,
            tile_type="",
            z="",
            x="",
            y="",
            scale=1):
        """
        Get a tile image
        """
        task = self.get_and_check_task(request, pk)

        z = int(z)
        x = int(x)
        y = int(y)

        scale = int(scale)
        ext = "png"
        driver = "jpeg" if ext == "jpg" else ext

        indexes = None
        nodata = None
        rgb_tile = None

        formula = self.request.query_params.get('formula')
        bands = self.request.query_params.get('bands')
        rescale = self.request.query_params.get('rescale')
        color_map = self.request.query_params.get('color_map')
        hillshade = self.request.query_params.get('hillshade')
        boundaries_feature = self.request.query_params.get('boundaries')
        if boundaries_feature == '':
            boundaries_feature = None
        if boundaries_feature is not None:
            try:
                boundaries_feature = json.loads(boundaries_feature)
            except json.JSONDecodeError:
                raise exceptions.ValidationError(
                    _("Invalid boundaries parameter"))

        if formula == '': formula = None
        if bands == '': bands = None
        if rescale == '': rescale = None
        if color_map == '': color_map = None
        if hillshade == '' or hillshade == '0': hillshade = None

        try:
            expr, _discard_ = lookup_formula(formula, bands)
        except ValueError as e:
            raise exceptions.ValidationError(str(e))

        if tile_type in ['dsm', 'dtm'] and rescale is None:
            rescale = "0,1000"
        if tile_type == 'orthophoto' and rescale is None:
            rescale = "0,255"

        if tile_type in ['dsm', 'dtm'] and color_map is None:
            color_map = "gray"

        if tile_type == 'orthophoto' and formula is not None:
            if color_map is None:
                color_map = "gray"
            if rescale is None:
                rescale = "-1,1"

        if nodata is not None:
            nodata = np.nan if nodata == "nan" else float(nodata)
        tilesize = scale * 256
        url = get_raster_path(task, tile_type)
        if not os.path.isfile(url):
            raise exceptions.NotFound()

        with COGReader(url) as src:
            if not src.tile_exists(z, x, y):
                raise exceptions.NotFound(_("Outside of bounds"))

        with COGReader(url) as src:
            minzoom, maxzoom = get_zoom_safe(src)
            has_alpha = has_alpha_band(src.dataset)
            if z < minzoom - ZOOM_EXTRA_LEVELS or z > maxzoom + ZOOM_EXTRA_LEVELS:
                raise exceptions.NotFound()
            if boundaries_feature is not None:
                try:
                    boundaries_cutline = create_cutline(
                        src.dataset, boundaries_feature,
                        CRS.from_string('EPSG:4326'))
                except:
                    raise exceptions.ValidationError(_("Invalid boundaries"))
            else:
                boundaries_cutline = None
            # Handle N-bands datasets for orthophotos (not plant health)
            if tile_type == 'orthophoto' and expr is None:
                ci = src.dataset.colorinterp
                # More than 4 bands?
                if len(ci) > 4:
                    # Try to find RGBA band order
                    if ColorInterp.red in ci and \
                            ColorInterp.green in ci and \
                            ColorInterp.blue in ci:
                        indexes = (
                            ci.index(ColorInterp.red) + 1,
                            ci.index(ColorInterp.green) + 1,
                            ci.index(ColorInterp.blue) + 1,
                        )
                    else:
                        # Fallback to first three
                        indexes = (
                            1,
                            2,
                            3,
                        )
                elif has_alpha:
                    indexes = non_alpha_indexes(src.dataset)

            # Workaround for https://github.com/OpenDroneMap/WebODM/issues/894
            if nodata is None and tile_type == 'orthophoto':
                nodata = 0

        resampling = "nearest"
        padding = 0
        if tile_type in ["dsm", "dtm"]:
            resampling = "bilinear"
            padding = 16

        try:
            with COGReader(url) as src:
                if expr is not None:
                    if boundaries_cutline is not None:
                        tile = src.tile(
                            x,
                            y,
                            z,
                            expression=expr,
                            tilesize=tilesize,
                            nodata=nodata,
                            padding=padding,
                            resampling_method=resampling,
                            vrt_options={'cutline': boundaries_cutline})
                    else:
                        tile = src.tile(x,
                                        y,
                                        z,
                                        expression=expr,
                                        tilesize=tilesize,
                                        nodata=nodata,
                                        padding=padding,
                                        resampling_method=resampling)
                else:
                    if boundaries_cutline is not None:
                        tile = src.tile(
                            x,
                            y,
                            z,
                            tilesize=tilesize,
                            nodata=nodata,
                            padding=padding,
                            resampling_method=resampling,
                            vrt_options={'cutline': boundaries_cutline})
                    else:
                        tile = src.tile(x,
                                        y,
                                        z,
                                        indexes=indexes,
                                        tilesize=tilesize,
                                        nodata=nodata,
                                        padding=padding,
                                        resampling_method=resampling)

        except TileOutsideBounds:
            raise exceptions.NotFound(_("Outside of bounds"))

        if color_map:
            try:
                colormap.get(color_map)
            except InvalidColorMapName:
                raise exceptions.ValidationError(
                    _("Not a valid color_map value"))

        intensity = None
        try:
            rescale_arr = list(map(float, rescale.split(",")))
        except ValueError:
            raise exceptions.ValidationError(_("Invalid rescale value"))

        options = img_profiles.get(driver, {})
        if hillshade is not None:
            try:
                hillshade = float(hillshade)
                if hillshade <= 0:
                    hillshade = 1.0
            except ValueError:
                raise exceptions.ValidationError(_("Invalid hillshade value"))
            if tile.data.shape[0] != 1:
                raise exceptions.ValidationError(
                    _("Cannot compute hillshade of non-elevation raster (multiple bands found)"
                      ))
            delta_scale = (maxzoom + ZOOM_EXTRA_LEVELS + 1 - z) * 4
            dx = src.dataset.meta["transform"][0] * delta_scale
            dy = -src.dataset.meta["transform"][4] * delta_scale
            ls = LightSource(azdeg=315, altdeg=45)
            # Hillshading is not a local tile operation and
            # requires neighbor tiles to be rendered seamlessly
            elevation = get_elevation_tiles(tile.data[0], url, x, y, z,
                                            tilesize, nodata, resampling,
                                            padding)
            intensity = ls.hillshade(elevation,
                                     dx=dx,
                                     dy=dy,
                                     vert_exag=hillshade)
            intensity = intensity[tilesize:tilesize * 2, tilesize:tilesize * 2]

        if intensity is not None:
            rgb = tile.post_process(in_range=(rescale_arr, ))
            if colormap:
                rgb, _discard_ = apply_cmap(rgb.data, colormap.get(color_map))
            if rgb.data.shape[0] != 3:
                raise exceptions.ValidationError(
                    _("Cannot process tile: intensity image provided, but no RGB data was computed."
                      ))
            intensity = intensity * 255.0
            rgb = hsv_blend(rgb, intensity)
            if rgb is not None:
                return HttpResponse(render(rgb,
                                           tile.mask,
                                           img_format=driver,
                                           **options),
                                    content_type="image/{}".format(ext))

        if color_map is not None:
            return HttpResponse(
                tile.post_process(in_range=(rescale_arr, )).render(
                    img_format=driver,
                    colormap=colormap.get(color_map),
                    **options),
                content_type="image/{}".format(ext))
        return HttpResponse(tile.post_process(in_range=(rescale_arr, )).render(
            img_format=driver, **options),
                            content_type="image/{}".format(ext))
Exemplo n.º 11
0
def tiles(
    url: str,
    z: int,
    x: int,
    y: int,
    scale: int = 1,
    ext: str = "png",
    bands: str = None,
    expr: str = None,
    rescale: str = None,
    color_ops: str = None,
    color_map: str = None,
    pan: bool = False,
    pixel_selection: str = "first",
) -> Tuple[str, str, BinaryIO]:
    """Handle tile requests."""
    with MosaicBackend(url) as mosaic:
        assets = mosaic.tile(x, y, z)

    if not assets:
        return ("EMPTY", "text/plain", f"No assets found for tile {z}-{x}-{y}")

    tilesize = 256 * scale

    pixel_selection = pixSel[pixel_selection]
    if expr is not None:
        tile, mask = mosaic_tiler(
            assets,
            x,
            y,
            z,
            expressionTiler,
            pixel_selection=pixel_selection(),
            expr=expr,
            tilesize=tilesize,
            pan=pan,
        )

    elif bands is not None:
        tile, mask = mosaic_tiler(
            assets,
            x,
            y,
            z,
            landsatTiler,
            pixel_selection=pixel_selection(),
            bands=tuple(bands.split(",")),
            tilesize=tilesize,
            pan=pan,
        )
    else:
        return ("NOK", "text/plain", "No bands nor expression given")

    if tile is None:
        return ("EMPTY", "text/plain", "empty tiles")

    if color_map:
        color_map = get_colormap(color_map, format="gdal")

    assets_str = json.dumps(assets, separators=(",", ":"))
    return_kwargs = {"custom_headers": {"X-ASSETS": assets_str}}

    if ext == "gif":
        frames = []
        options = img_profiles.get("png", {})
        for i in range(len(tile)):
            img = post_process_tile(tile[i].copy(),
                                    mask[i].copy(),
                                    rescale=rescale,
                                    color_formula=color_ops)
            frames.append(
                Image.open(
                    io.BytesIO(
                        render(
                            img,
                            mask[i],
                            img_format="png",
                            colormap=color_map,
                            **options,
                        ))))
        sio = io.BytesIO()
        frames[0].save(
            sio,
            "gif",
            save_all=True,
            append_images=frames[1:],
            duration=300,
            loop=0,
            optimize=True,
        )
        sio.seek(0)
        return ("OK", f"image/{ext}", sio.getvalue(), return_kwargs)

    rtile = post_process_tile(tile,
                              mask,
                              rescale=rescale,
                              color_formula=color_ops)

    if ext == "bin":
        # Flatten in Row-major order
        buf = rtile.tobytes(order='C')
        return ("OK", "application/x-binary", buf, return_kwargs)

    driver = "jpeg" if ext == "jpg" else ext
    options = img_profiles.get(driver, {})

    if ext == "tif":
        ext = "tiff"
        driver = "GTiff"
        tile_bounds = mercantile.xy_bounds(mercantile.Tile(x=x, y=y, z=z))
        options = dict(
            crs={"init": "EPSG:3857"},
            transform=from_bounds(*tile_bounds, tilesize, tilesize),
        )

    return (
        "OK",
        f"image/{ext}",
        render(rtile, mask, img_format=driver, colormap=color_map, **options),
        return_kwargs,
    )
Exemplo n.º 12
0
def test_render_geotiff():
    """Creates GeoTIFF image buffer from 3 bands array."""
    arr = np.random.randint(0, 255, size=(3, 512, 512), dtype=np.uint8)
    mask = np.zeros((512, 512), dtype=np.uint8) + 255
    ops = utils.geotiff_options(1, 0, 0)
    assert utils.render(arr, mask=mask, img_format="GTiff", **ops)
Exemplo n.º 13
0
def test_render_valid_options():
    """Creates image buffer with driver options."""
    arr = np.random.randint(0, 255, size=(3, 512, 512), dtype=np.uint8)
    mask = np.zeros((512, 512), dtype=np.uint8) + 255
    assert utils.render(arr, mask=mask, img_format="png", ZLEVEL=9)
Exemplo n.º 14
0
def _tile(
    z: int,
    x: int,
    y: int,
    scale: int = 1,
    ext: str = None,
    url: str = None,
    indexes: Optional[Union[str, Tuple]] = None,
    expr: Optional[str] = None,
    nodata: Optional[Union[str, int, float]] = None,
    rescale: Optional[str] = None,
    color_formula: Optional[str] = None,
    color_map: Optional[str] = None,
    resampling_method: str = "bilinear",
    **kwargs,
) -> Tuple[str, str, bytes]:
    """Handle /tiles requests."""
    if indexes and expr:
        raise TilerError("Cannot pass indexes and expression")

    if not url:
        raise TilerError("Missing 'url' parameter")

    if nodata is not None:
        nodata = numpy.nan if nodata == "nan" else float(nodata)

    tilesize = scale * 256

    if isinstance(indexes, str):
        indexes = tuple(map(int, indexes.split(",")))

    with rasterio.Env(aws_session):
        with COGReader(url) as cog:
            tile, mask = cog.tile(
                x,
                y,
                z,
                tilesize=tilesize,
                indexes=indexes,
                expression=expr,
                nodata=nodata,
                resampling_method=resampling_method,
                **kwargs,
            )
            color_map = cmap.get(color_map) if color_map else cog.colormap

    if not ext:
        ext = "jpg" if mask.all() else "png"

    tile = utils.postprocess(tile, mask, rescale=rescale, color_formula=color_formula)

    if ext == "npy":
        sio = io.BytesIO()
        numpy.save(sio, (tile, mask))
        sio.seek(0)
        content = sio.getvalue()
    else:
        driver = drivers[ext]
        options = img_profiles.get(driver.lower(), {})

        if ext == "tif":
            options = geotiff_options(x, y, z, tilesize=tilesize)

        if color_map:
            options["colormap"] = color_map

        content = render(tile, mask, img_format=driver, **options)

    return ("OK", mimetype[ext], content)
Exemplo n.º 15
0
def test_render_valid_1band():
    """Creates PNG image buffer from one band array."""
    arr = np.random.randint(0, 255, size=(512, 512), dtype=np.uint8)
    assert utils.render(arr)
Exemplo n.º 16
0
band = rasterio.band(dataset, 1)


print(band)

tile, mask = reader.tile(dataset, 852, 418, 10, tilesize=1024)

min = 0
max = 60


tile1 = (tile[0]-min)/max*255
tile2 = (tile[1]-min)/max*255
tile3 = (tile[2]-min)/max*255

tileList = np.array([tile[0], tile[1], tile[2]])

renderData = np.where(tileList > 255, 255, tileList)
renderData = np.where(renderData < 0, 0, renderData)

renderData = renderData.astype(np.uint8)
mtdata = to_math_type(renderData)
data = gamma(mtdata, 1.7)

data = sigmoidal(mtdata, 10, 0)*255

buffer = render(data.astype(np.uint8), mask=mask)
with open("reraster2.png", "wb") as f:
    f.write(buffer)
Exemplo n.º 17
0
def test_render_valid_colormap():
    """Creates 'colormaped' PNG image buffer from one band array."""
    arr = np.random.randint(0, 255, size=(1, 512, 512), dtype=np.uint8)
    mask = np.zeros((512, 512), dtype=np.uint8)
    cmap = colormap.get_colormap("cfastie")
    assert utils.render(arr, mask, colormap=cmap, img_format="jpeg")
Exemplo n.º 18
0
def _img(
    mosaicid: str = None,
    z: int = None,
    x: int = None,
    y: int = None,
    scale: int = 1,
    ext: str = None,
    url: str = None,
    indexes: Optional[Sequence[int]] = None,
    rescale: str = None,
    color_ops: str = None,
    color_map: str = None,
    pixel_selection: str = "first",
    resampling_method: str = "nearest",
) -> Tuple:
    """Handle tile requests."""
    if not mosaicid and not url:
        return ("NOK", "text/plain", "Missing 'MosaicID or URL' parameter")

    mosaic_path = _create_mosaic_path(mosaicid) if mosaicid else url
    with MosaicBackend(mosaic_path) as mosaic:
        assets = mosaic.tile(x, y, z)
        if not assets:
            return ("EMPTY", "text/plain", f"No assets found for tile {z}-{x}-{y}")

    if indexes is not None and isinstance(indexes, str):
        indexes = list(map(int, indexes.split(",")))

    tilesize = 256 * scale

    if pixel_selection == "last":
        pixel_selection = "first"
        assets = list(reversed(assets))

    with rasterio.Env(aws_session):
        pixsel_method = PIXSEL_METHODS[pixel_selection]
        tile, mask = mosaic_tiler(
            assets,
            x,
            y,
            z,
            cogeoTiler,
            indexes=indexes,
            tilesize=tilesize,
            pixel_selection=pixsel_method(),
            resampling_method=resampling_method,
        )

    if tile is None:
        return ("EMPTY", "text/plain", "empty tiles")

    rtile = _postprocess(tile, mask, rescale=rescale, color_formula=color_ops)

    if not ext:
        ext = "jpg" if mask.all() else "png"

    driver = "jpeg" if ext == "jpg" else ext
    options = img_profiles.get(driver, {})

    if ext == "tif":
        ext = "tiff"
        driver = "GTiff"
        options = geotiff_options(x, y, z, tilesize)

    if color_map:
        options["colormap"] = cmap.get(color_map)

    return (
        "OK",
        f"image/{ext}",
        render(rtile, mask, img_format=driver, **options),
    )
Exemplo n.º 19
0
def test_render_valid_mask():
    """Creates image buffer from 3 bands array and mask."""
    arr = np.random.randint(0, 255, size=(3, 512, 512), dtype=np.uint8)
    mask = np.zeros((512, 512), dtype=np.uint8)
    assert utils.render(arr, mask=mask)
    assert utils.render(arr, mask=mask, img_format="jpeg")
Exemplo n.º 20
0
async def cog_tile(
        z: int = Path(
            ..., ge=0, le=30, description="Mercator tiles's zoom level"),
        x: int = Path(..., description="Mercator tiles's column"),
        y: int = Path(..., description="Mercator tiles's row"),
        TileMatrixSetId: TileMatrixSetNames = Query(
            TileMatrixSetNames.WebMercatorQuad,  # type: ignore
            description="TileMatrixSet Name (default: 'WebMercatorQuad')",
        ),
        scale: int = Query(
            1,
            gt=0,
            lt=4,
            description="Tile size scale. 1=256x256, 2=512x512..."),
        format: ImageType = Query(
            None, description="Output image type. Default is auto."),
        url: str = Query(..., description="Cloud Optimized GeoTIFF URL."),
        image_params: CommonTileParams = Depends(),
        cache_client: CacheLayer = Depends(utils.get_cache),
        request_id: str = Depends(request_hash),
):
    """Create map tile from a COG."""
    timings = []
    headers: Dict[str, str] = {}

    tilesize = scale * 256
    tms = morecantile.tms.get(TileMatrixSetId.name)

    content = None
    if cache_client:
        try:
            content, ext = cache_client.get_image_from_cache(request_id)
            format = ImageType[ext]
            headers["X-Cache"] = "HIT"
        except Exception:
            content = None

    if not content:
        with utils.Timer() as t:
            with COGReader(url, tms=tms) as cog:
                tile, mask = cog.tile(
                    x,
                    y,
                    z,
                    tilesize=tilesize,
                    indexes=image_params.indexes,
                    expression=image_params.expression,
                    nodata=image_params.nodata,
                    **image_params.kwargs,
                )
                colormap = image_params.color_map or cog.colormap
        timings.append(("Read", t.elapsed))

        if not format:
            format = ImageType.jpg if mask.all() else ImageType.png

        with utils.Timer() as t:
            tile = utils.postprocess(
                tile,
                mask,
                rescale=image_params.rescale,
                color_formula=image_params.color_formula,
            )
        timings.append(("Post-process", t.elapsed))

        with utils.Timer() as t:
            if format == ImageType.npy:
                sio = BytesIO()
                numpy.save(sio, (tile, mask))
                sio.seek(0)
                content = sio.getvalue()
            else:
                driver = drivers[format.value]
                options = img_profiles.get(driver.lower(), {})
                if format == ImageType.tif:
                    bounds = tms.xy_bounds(x, y, z)
                    dst_transform = from_bounds(*bounds, tilesize, tilesize)
                    options = {"crs": tms.crs, "transform": dst_transform}
                content = render(tile,
                                 mask,
                                 img_format=driver,
                                 colormap=colormap,
                                 **options)
        timings.append(("Format", t.elapsed))

        if cache_client and content:
            cache_client.set_image_cache(request_id, (content, format.value))

    if timings:
        headers["X-Server-Timings"] = "; ".join([
            "{} - {:0.2f}".format(name, time * 1000)
            for (name, time) in timings
        ])

    return ImgResponse(
        content,
        media_type=ImageMimeTypes[format.value].value,
        headers=headers,
    )
Exemplo n.º 21
0
def test_render_geotiff16Bytes():
    """Creates GeoTIFF image buffer from 3 bands array."""
    arr = np.random.randint(0, 255, size=(3, 512, 512), dtype=np.uint16)
    mask = np.zeros((512, 512), dtype=np.uint8) + 255
    assert utils.render(arr, mask=mask, img_format="GTiff")
Exemplo n.º 22
0
async def cog_part(
        minx: float = Path(..., description="Bounding box min X"),
        miny: float = Path(..., description="Bounding box min Y"),
        maxx: float = Path(..., description="Bounding box max X"),
        maxy: float = Path(..., description="Bounding box max Y"),
        format: ImageType = Query(None, description="Output image type."),
        url: str = Query(..., description="Cloud Optimized GeoTIFF URL."),
        image_params: CommonImageParams = Depends(),
):
    """Create image from part of a COG."""
    timings = []
    headers: Dict[str, str] = {}

    with utils.Timer() as t:
        with COGReader(url) as cog:
            data, mask = cog.part(
                [minx, miny, maxx, maxy],
                height=image_params.height,
                width=image_params.width,
                max_size=image_params.max_size,
                indexes=image_params.indexes,
                expression=image_params.expression,
                nodata=image_params.nodata,
                **image_params.kwargs,
            )
            colormap = image_params.color_map or cog.colormap
    timings.append(("Read", t.elapsed))

    with utils.Timer() as t:
        data = utils.postprocess(
            data,
            mask,
            rescale=image_params.rescale,
            color_formula=image_params.color_formula,
        )
    timings.append(("Post-process", t.elapsed))

    with utils.Timer() as t:
        if format == ImageType.npy:
            sio = BytesIO()
            numpy.save(sio, (data, mask))
            sio.seek(0)
            content = sio.getvalue()
        else:
            driver = drivers[format.value]
            options = img_profiles.get(driver.lower(), {})
            content = render(data,
                             mask,
                             img_format=driver,
                             colormap=colormap,
                             **options)
    timings.append(("Format", t.elapsed))

    if timings:
        headers["X-Server-Timings"] = "; ".join([
            "{} - {:0.2f}".format(name, time * 1000)
            for (name, time) in timings
        ])

    return ImgResponse(
        content,
        media_type=ImageMimeTypes[format.value].value,
        headers=headers,
    )
Exemplo n.º 23
0
def test_render_valid_1bandWebp():
    """Creates WEBP image buffer from 1 band array."""
    arr = np.random.randint(0, 255, size=(1, 512, 512), dtype=np.uint8)
    assert utils.render(arr, img_format="WEBP")
Exemplo n.º 24
0
async def stac_part(
        minx: float = Path(..., description="Bounding box min X"),
        miny: float = Path(..., description="Bounding box min Y"),
        maxx: float = Path(..., description="Bounding box max X"),
        maxy: float = Path(..., description="Bounding box max Y"),
        format: ImageType = Query(None, description="Output image type."),
        url: str = Query(..., description="STAC Item URL."),
        assets: str = Query(
            "", description="comma (,) separated list of asset names."),
        image_params: CommonImageParams = Depends(),
):
    """Create image from part of STAC assets."""
    timings = []
    headers: Dict[str, str] = {}

    if not image_params.expression and not assets:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Must pass Expression or Asset list.",
        )

    with utils.Timer() as t:
        with STACReader(url) as stac:
            data, mask = stac.part(
                [minx, miny, maxx, maxy],
                height=image_params.height,
                width=image_params.width,
                max_size=image_params.max_size,
                assets=assets.split(","),
                expression=image_params.expression,
                indexes=image_params.indexes,
                nodata=image_params.nodata,
                **image_params.kwargs,
            )
    timings.append(("Read", t.elapsed))

    with utils.Timer() as t:
        data = utils.postprocess(
            data,
            mask,
            rescale=image_params.rescale,
            color_formula=image_params.color_formula,
        )
    timings.append(("Post-process", t.elapsed))

    with utils.Timer() as t:
        if format == ImageType.npy:
            sio = BytesIO()
            numpy.save(sio, (data, mask))
            sio.seek(0)
            content = sio.getvalue()
        else:
            driver = drivers[format.value]
            options = img_profiles.get(driver.lower(), {})
            content = render(
                data,
                mask,
                img_format=driver,
                colormap=image_params.color_map,
                **options,
            )
    timings.append(("Format", t.elapsed))

    if timings:
        headers["X-Server-Timings"] = "; ".join([
            "{} - {:0.2f}".format(name, time * 1000)
            for (name, time) in timings
        ])

    return ImgResponse(
        content,
        media_type=ImageMimeTypes[format.value].value,
        headers=headers,
    )