# Copyright (c) 2025 The University of Washington
#
# This file is part of rapidtools.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# You should have received a copy of the BSD 3-Clause License along with
# rapidtools. If not, see <http://www.opensource.org/licenses/>.
#
# Contributors:
# Barbaros Cetiner
#
#
# Last updated:
# 11-28-2026
"""
Tiles of a full-resolution street-level frame, for objects too small to
find in a thumbnail.
A fire hydrant 20 m from the camera is a dozen pixels wide in a 2,048 pixel
thumbnail of a panorama and close to a hundred in the photo as it was
taken. A segmentation model looks at about a thousand pixels a side, so the
full-resolution frame is cut into tiles of that size and the model sees each
one at the resolution it was taken at.
Of a panorama, only the band of elevations in which things stand on the
ground is cut: from just above the horizon down to where the ground is a
few meters from the camera, one row of tiles around the horizon for a
13,504 pixel panorama. Neighboring tiles overlap so that an object on a
seam is whole in one of them, and the masks of all tiles are joined on the
frame, so an object two tiles show comes back once.
Example:
>>> tiles = tile_layout(13504, 6752, is_pano=True)
>>> len(tiles), tiles[0]
(16, (0, 3357, 1013))
"""
from __future__ import annotations
import math
from collections.abc import Sequence
import numpy as np
from shapely import STRtree
from shapely.affinity import translate
from shapely.geometry import MultiPolygon, Polygon
from shapely.ops import unary_union
from .street_instances import mask_outlines
Tile = tuple[int, int, int]
def band_rows(height: int, elevation_deg: tuple[float, float]) -> tuple[int, int]:
"""
Pixel rows of an equirectangular panorama between two elevations.
Args:
height: Height of the panorama in pixels.
elevation_deg: Lower and upper elevation of the band in degrees,
negative below the horizon.
Returns:
tuple[int, int]: First row of the band and the row after its last.
Example:
>>> band_rows(6752, (-26.5, 0.5))
(3357, 4370)
"""
low, high = sorted(elevation_deg)
top = int(round((0.5 - high / 180.0) * height))
bottom = int(round((0.5 - low / 180.0) * height))
return max(0, top), min(height, max(bottom, top + 1))
[docs]
def tile_layout(
width: int,
height: int,
is_pano: bool,
tile_px: int = 1024,
overlap: float = 0.125,
elevation_deg: tuple[float, float] = (-26.5, 0.5),
) -> list[Tile]:
"""
Square tiles that cover the part of a frame where objects stand.
Args:
width: Width of the frame in pixels.
height: Height of the frame.
is_pano: Whether the frame is an equirectangular panorama. Its
tiles cover the band ``elevation_deg`` all the way around, and
the last one reaches across the seam. A perspective frame is
covered whole.
tile_px: Side of a tile. A band about this high is cut as one row
of tiles of its own height.
overlap: Share of a tile that the next one repeats, at least.
elevation_deg: Lower and upper elevation of a panorama's band.
Returns:
list[tuple[int, int, int]]: ``(left, top, side)`` of every tile, in
pixels. ``left + side`` exceeds ``width`` for a tile across the
seam of a panorama.
Example:
>>> tile_layout(4000, 3000, is_pano=False)[-1]
(2976, 1976, 1024)
>>> len(tile_layout(5760, 2880, is_pano=True)) # a band 432 pixels high
16
"""
if is_pano:
top, bottom = band_rows(height, elevation_deg)
else:
top, bottom = 0, height
span = bottom - top
rows = max(1, int(round(span / tile_px)))
side = min(span if rows == 1 else tile_px, width)
step = max(1.0, side * (1.0 - overlap))
tops = _starts(top, bottom, side, step)
if is_pano:
cols = max(1, int(math.ceil(width / step)))
lefts = [int(round(c * width / cols)) for c in range(cols)]
else:
lefts = _starts(0, width, side, step)
return [(left, t, side) for t in tops for left in lefts]
def _starts(first: int, end: int, side: int, step: float) -> list[int]:
"""Evenly spaced starts of windows ``side`` long that cover ``first`` to ``end``."""
room = end - first - side
if room <= 0:
return [first]
n = int(math.ceil(room / step)) + 1
return [first + int(round(k * room / (n - 1))) for k in range(n)]
[docs]
def cut_tile(image: np.ndarray, tile: Tile, top: int = 0) -> np.ndarray:
"""
Cut one tile out of a frame, across the seam of a panorama if need be.
Args:
image: The frame, or the rows of it from ``top`` down, as an array
with rows first.
tile: ``(left, top, side)`` in pixels of the whole frame.
top: Row of the frame that ``image`` starts at.
Returns:
numpy.ndarray: The tile.
Example:
>>> import numpy as np
>>> frame = np.arange(40).reshape(4, 10)
>>> cut_tile(frame, (8, 1, 3))[0].tolist()
[18, 19, 10]
"""
left, tile_top, side = tile
columns = np.arange(left, left + side) % image.shape[1]
return image[tile_top - top : tile_top - top + side][:, columns]
[docs]
def join_tile_masks(
tiles: Sequence[Tile],
masks: Sequence[np.ndarray | None],
scores: Sequence[Sequence[float] | None],
width: int,
height: int,
is_pano: bool,
) -> list[tuple[list[tuple[float, float]], float | None]]:
"""
Outlines, on the whole frame, of the masks found in its tiles.
Masks that overlap are one object: two tiles show what stands where
they overlap, and a mask cut by the edge of one tile continues in the
next. An outline that reaches the lower edge of the tiled part of the
frame is left out, because the foot of that object is not in it and its
distance cannot be read.
Args:
tiles: The tiles of :func:`tile_layout`.
masks: For every tile, an ``(n, side, side)`` array of masks, or
``None`` when it has none.
scores: For every tile, the confidence of each mask, or ``None``.
width: Width of the frame in pixels.
height: Height of the frame.
is_pano: Whether the frame wraps around.
Returns:
list[tuple[list[tuple[float, float]], float | None]]: One outline
per object as ``(x, y)`` vertices in normalized frame coordinates,
with the highest confidence among the masks it was joined from. An
outline across the seam of a panorama has vertices on both sides
of it.
Example:
>>> import numpy as np
>>> a, b = np.zeros((1, 100, 100), bool), np.zeros((1, 100, 100), bool)
>>> a[0, 40:60, 90:] = True # cut by the right edge of the first tile
>>> b[0, 40:60, 10:25] = True # and continued in the second
>>> ((outline, score),) = join_tile_masks(
... [(0, 0, 100), (80, 0, 100)], [a, b], [[0.9], [0.7]], 180, 100, False)
>>> xs = [round(x * 180) for x, _ in outline]
>>> min(xs), max(xs)
(90, 105)
>>> score
0.9
"""
shapes: list[Polygon] = []
confidence: list[float | None] = []
side = max((t[2] for t in tiles), default=0)
for (left, top, tile_side), stack, tile_scores in zip(
tiles, masks, scores, strict=True
):
if stack is None:
continue
stack = np.asarray(stack)
if stack.ndim == 2:
stack = stack[None]
for n, mask in enumerate(stack):
score = (
float(tile_scores[n])
if tile_scores is not None and n < len(tile_scores)
else None
)
for ring in mask_outlines(mask):
shape = Polygon(
[(left + x * tile_side, top + y * tile_side) for x, y in ring]
).buffer(0)
if shape.is_empty:
continue
shapes.append(shape)
confidence.append(score)
if is_pano and shape.bounds[2] <= side:
# Also where the tile across the seam shows it.
shapes.append(translate(shape, xoff=width))
confidence.append(score)
if not shapes:
return []
joined = unary_union(shapes)
parts = list(joined.geoms) if isinstance(joined, MultiPolygon) else [joined]
tree = STRtree(shapes)
bottom = max(t[1] + t[2] for t in tiles)
out: list[tuple[list[tuple[float, float]], float | None]] = []
for part in parts:
if not isinstance(part, Polygon) or part.is_empty:
continue
x = part.centroid.x
if is_pano and not (side / 2.0 <= x < width + side / 2.0):
continue # its other copy is the whole one
if part.bounds[3] >= bottom - 1.5:
continue # no foot in the picture
found = [
confidence[int(k)]
for k in tree.query(part)
if shapes[int(k)].intersects(part)
]
known = [s for s in found if s is not None]
outline = [
((px % width) / width if is_pano else px / width, py / height)
for px, py in part.exterior.coords[:-1]
]
out.append((outline, max(known) if known else None))
return out
def ground_range_m(camera_height_m: float, elevation_deg: tuple[float, float]) -> float:
"""
Distance at which the ground enters a panorama's band of tiles.
Nearer than this the tiles do not show the ground, so a frame cannot
say that nothing stands there.
Example:
>>> round(ground_range_m(2.4, (-26.5, 0.5)), 1)
4.8
"""
low = min(elevation_deg)
if low >= 0.0:
return math.inf
if low <= -90.0:
return 0.0
return camera_height_m / math.tan(math.radians(-low))