Esempio n. 1
0
def post_process_tile(
    tile: numpy.ndarray,
    mask: numpy.ndarray,
    rescale: str = None,
    color_formula: str = None,
) -> Tuple[numpy.ndarray, numpy.ndarray]:
    """Tile data post processing."""
    if rescale:
        rescale_arr = (tuple(map(float, rescale.split(","))), ) * tile.shape[0]
        for bdx in range(tile.shape[0]):
            tile[bdx] = numpy.where(
                mask,
                linear_rescale(tile[bdx],
                               in_range=rescale_arr[bdx],
                               out_range=[0, 255]),
                0,
            )
        tile = tile.astype(numpy.uint8)

    if color_formula:
        if issubclass(tile.dtype.type, numpy.floating):
            tile = tile.astype(numpy.int16)

        # make sure one last time we don't have
        # negative value before applying color formula
        tile[tile < 0] = 0
        for ops in parse_operations(color_formula):
            tile = scale_dtype(ops(to_math_type(tile)), numpy.uint8)

    return tile
Esempio n. 2
0
def _postprocess(
    tile: numpy.ndarray,
    mask: numpy.ndarray,
    rescale: str = None,
    color_formula: str = None,
) -> Tuple[numpy.ndarray, numpy.ndarray]:
    """Post-process tile data."""
    if rescale:
        rescale_arr = list(map(float, rescale.split(",")))
        rescale_arr = list(_chunks(rescale_arr, 2))
        if len(rescale_arr) != tile.shape[0]:
            rescale_arr = ((rescale_arr[0]),) * tile.shape[0]

        for bdx in range(tile.shape[0]):
            tile[bdx] = numpy.where(
                mask,
                linear_rescale(
                    tile[bdx], in_range=rescale_arr[bdx], out_range=[0, 255]
                ),
                0,
            )
        tile = tile.astype(numpy.uint8)

    if color_formula:
        # make sure one last time we don't have
        # negative value before applying color formula
        tile[tile < 0] = 0
        for ops in parse_operations(color_formula):
            tile = scale_dtype(ops(to_math_type(tile)), numpy.uint8)

    return tile, mask
Esempio n. 3
0
def _postprocess(
    tile: numpy.ndarray,
    mask: numpy.ndarray,
    tilesize: int,
    rescale: str = None,
    color_formula: str = None,
) -> Tuple[numpy.ndarray, numpy.ndarray]:

    if tile is None:
        # Return empty tile
        tile = numpy.zeros((1, tilesize, tilesize), dtype=numpy.uint8)
        mask = numpy.zeros((tilesize, tilesize), dtype=numpy.uint8)
    else:
        if rescale:
            rescale_arr = (tuple(map(float,
                                     rescale.split(","))), ) * tile.shape[0]
            for bdx in range(tile.shape[0]):
                tile[bdx] = numpy.where(
                    mask,
                    linear_rescale(tile[bdx],
                                   in_range=rescale_arr[bdx],
                                   out_range=[0, 255]),
                    0,
                )
            tile = tile.astype(numpy.uint8)

        if color_formula:
            # make sure one last time we don't have
            # negative value before applying color formula
            tile[tile < 0] = 0
            for ops in parse_operations(color_formula):
                tile = scale_dtype(ops(to_math_type(tile)), numpy.uint8)

    return tile, mask
Esempio n. 4
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
Esempio n. 5
0
def arr_rgba():
    return to_math_type(
        np.array([
            [[1, 2], [3, 4]],  # red
            [[5, 6], [7, 8]],  # green
            [[9, 10], [11, 12]],  # blue
            [[0, 0], [25.5, 25.5]],  # alpha
        ]).astype("uint8") * 10)
Esempio n. 6
0
    def post_process(
        self,
        in_range: Optional[Tuple[NumType, NumType]] = None,
        out_dtype: Union[str, numpy.number] = "uint8",
        color_formula: Optional[str] = None,
        **kwargs: Any,
    ) -> "ImageData":
        """Post-process image data.

        Args:
            in_range (tuple): input min/max bounds value to rescale from.
            out_dtype (str, optional): output datatype after rescaling. Defaults to `uint8`.
            color_formula (str, optional): rio-color formula (see: https://github.com/mapbox/rio-color).
            kwargs (optional): keyword arguments to forward to `rio_tiler.utils.linear_rescale`.

        Returns:
            ImageData: new ImageData object with the updated data.

        Examples:
            >>> img.post_process(in_range=(0, 16000))

            >>> img.post_process(color_formula="Gamma RGB 4.1")

        """
        data = self.data.copy()
        mask = self.mask.copy()

        if in_range:
            rescale_arr = tuple(_chunks(in_range, 2))
            if len(rescale_arr) != self.count:
                rescale_arr = ((rescale_arr[0]), ) * self.count

            for bdx in range(self.count):
                data[bdx] = numpy.where(
                    self.mask,
                    linear_rescale(
                        data[bdx],
                        in_range=rescale_arr[bdx],
                        **kwargs,
                    ),
                    0,
                )
            data = data.astype(out_dtype)

        if color_formula:
            data[data < 0] = 0
            for ops in parse_operations(color_formula):
                data = scale_dtype(ops(to_math_type(data)), numpy.uint8)

        return ImageData(
            data,
            mask,
            crs=self.crs,
            bounds=self.bounds,
            assets=self.assets,
            metadata=self.metadata,
        )
Esempio n. 7
0
def arr():

    return to_math_type(
        np.array([
            # red
            [[1, 2], [3, 4]],
            # green
            [[5, 6], [7, 8]],
            # blue
            [[9, 10], [11, 12]],
        ]).astype("uint8") * 10)
Esempio n. 8
0
def _postprocess_tile(tile, mask, rescale=None, color_ops=None):
    """Tile data post-processing."""
    if rescale:
        rescale = (tuple(map(float, rescale.split(","))), ) * tile.shape[0]
        for bdx in range(tile.shape[0]):
            tile[bdx] = numpy.where(
                mask,
                linear_rescale(tile[bdx],
                               in_range=rescale[bdx],
                               out_range=[0, 255]),
                0,
            )
        tile = tile.astype(numpy.uint8)

    if color_ops:
        # make sure one last time we don't have
        # negative value before applying color formula
        tile[tile < 0] = 0
        for ops in parse_operations(color_ops):
            tile = scale_dtype(ops(to_math_type(tile)), numpy.uint8)

    return tile, mask
Esempio n. 9
0
def _postprocess(tile, mask, tilesize, rescale=None, color_formula=None):
    if tile is None:
        # Return empty tile
        tile = numpy.zeros((1, tilesize, tilesize), dtype=numpy.uint8)
        mask = numpy.zeros((tilesize, tilesize), dtype=numpy.uint8)
    else:
        if rescale:
            rescale = (tuple(map(float, rescale.split(","))), ) * tile.shape[0]
            for bdx in range(tile.shape[0]):
                tile[bdx] = numpy.where(
                    mask,
                    linear_rescale(tile[bdx],
                                   in_range=rescale[bdx],
                                   out_range=[0, 255]),
                    0,
                )
            tile = tile.astype(numpy.uint8)

        if color_formula:
            for ops in parse_operations(color_formula):
                tile = scale_dtype(ops(to_math_type(tile)), numpy.uint8)

    return tile, mask
Esempio n. 10
0
    def _apply_color_operations(self, img, color_ops):
        for ops in parse_operations(color_ops):
            img = scale_dtype(ops(to_math_type(img)), numpy.uint8)

        return img
Esempio n. 11
0
def test_scale_round_trip(arr):
    x = to_math_type(arr)
    y = scale_dtype(x, arr.dtype)
    assert np.array_equal(arr, y)
Esempio n. 12
0
def test_to_math_type(arr):
    x = to_math_type(arr)
    assert x.dtype == math_type
    assert x.max() <= 1.0
    assert x.min() >= 0.0
Esempio n. 13
0
def test_scale_round_trip(arr):
    x = to_math_type(arr)
    y = scale_dtype(x, arr.dtype)
    assert np.array_equal(arr, y)
Esempio n. 14
0
def test_to_math_type(arr):
    x = to_math_type(arr)
    assert x.dtype == math_type
    assert x.max() <= 1.0
    assert x.min() >= 0.0
Esempio n. 15
0
def main(source, reference, downsample, steps, plot):
    """Given a source image and a reference image,
    Find the rio color formula which results in an
    output with similar histogram to the reference image.

    Uses simulated annealing to determine optimal settings.

    Increase the --downsample option to speed things up.
    Increase the --steps to get better results (longer runtime).
    """
    global fig, txt, imgs

    click.echo("Reading source data...", err=True)
    with rasterio.open(source) as src:
        if downsample is None:
            ratio = calc_downsample(src.width, src.height)
        else:
            ratio = downsample
        w = int(src.width // ratio)
        h = int(src.height // ratio)
        rgb = src.read((1, 2, 3), out_shape=(3, h, w))
        orig_rgb = to_math_type(rgb)

    click.echo("Reading reference data...", err=True)
    with rasterio.open(reference) as ref:
        if downsample is None:
            ratio = calc_downsample(ref.width, ref.height)
        else:
            ratio = downsample
        w = int(ref.width / ratio)
        h = int(ref.height / ratio)
        rgb = ref.read((1, 2, 3), out_shape=(3, h, w))
        ref_rgb = to_math_type(rgb)

    click.echo("Annealing...", err=True)
    est = ColorEstimator(orig_rgb, ref_rgb)

    if plot:
        import matplotlib.pyplot as plt

        fig = plt.figure(figsize=(20, 10))
        fig.suptitle("Color Formula Optimization", fontsize=18, fontweight="bold")
        txt = fig.text(0.02, 0.05, "foo", family="monospace", fontsize=16)
        type(txt)
        axs = (
            fig.add_subplot(1, 4, 1),
            fig.add_subplot(1, 4, 2),
            fig.add_subplot(1, 4, 3),
            fig.add_subplot(1, 4, 4),
        )
        fig.tight_layout()
        axs[0].set_title("Source")
        axs[1].set_title("Current Formula")
        axs[2].set_title("Best Formula")
        axs[3].set_title("Reference")
        imgs.append(axs[0].imshow(reshape_as_image(est.src)))
        imgs.append(axs[1].imshow(reshape_as_image(est.src)))
        imgs.append(axs[2].imshow(reshape_as_image(est.src)))
        imgs.append(axs[3].imshow(reshape_as_image(est.ref)))
        fig.show()

    schedule = dict(
        tmax=25.0,  # Max (starting) temperature
        tmin=1e-4,  # Min (ending) temperature
        steps=steps,  # Number of iterations
        updates=steps / 20,  # Number of updates
    )

    est.set_schedule(schedule)
    est.save_state_on_exit = False
    optimal, score = est.anneal()
    optimal["energy"] = score
    ops = est.cmd(optimal)
    click.echo("rio color -j4 {} {} {}".format(source, "/tmp/output.tif", ops))
Esempio 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)