"""Rendering of query images: labelled panels with anchors, curves, candidates. Panels are cropped, scaled, and rotated before anything is drawn, so labels stay upright for camera streams that are stored rotated (Aria). Coordinates passed to the drawing helpers are always native image pixels. """ import os from functools import lru_cache import numpy as np from PIL import Image, ImageDraw, ImageFont import matplotlib _FONT_DIR = os.path.join(os.path.dirname(matplotlib.__file__), "mpl-data", "fonts", "ttf") FONT_BOLD = os.path.join(_FONT_DIR, "DejaVuSans-Bold.ttf") FONT_REG = os.path.join(_FONT_DIR, "DejaVuSans.ttf") COLOR_ANCHOR = (255, 40, 255) COLOR_CURVE = (255, 220, 0) COLOR_CAND = (0, 230, 255) COLOR_TRACK = (60, 255, 60) COLOR_BG = (22, 22, 22) COLOR_HEADER = (245, 245, 245) @lru_cache(maxsize=32) def font(size, bold=True): """Fonts are parsed once per size; loading one per label dominated frame rendering.""" return ImageFont.truetype(FONT_BOLD if bold else FONT_REG, size) def native_to_panel(xy, box, scale, rotation, pre_size): """Native image pixels to pixels of a cropped, scaled, rotated panel.""" p = (np.asarray(xy, dtype=float) - np.array([box[0], box[1]])) * scale W, H = pre_size rotation = int(rotation) % 360 if rotation == 90: p = np.stack([H - p[..., 1], p[..., 0]], axis=-1) elif rotation == 180: p = np.stack([W - p[..., 0], H - p[..., 1]], axis=-1) elif rotation == 270: p = np.stack([p[..., 1], W - p[..., 0]], axis=-1) return p def panel_to_native(xy, box, scale, rotation, pre_size): """Inverse of `native_to_panel`.""" p = np.asarray(xy, dtype=float) W, H = pre_size rotation = int(rotation) % 360 if rotation == 90: p = np.stack([p[..., 1], H - p[..., 0]], axis=-1) elif rotation == 180: p = np.stack([W - p[..., 0], H - p[..., 1]], axis=-1) elif rotation == 270: p = np.stack([W - p[..., 1], p[..., 0]], axis=-1) return p / scale + np.array([box[0], box[1]]) class Panel: """An image region with a mapping from native pixels to (rotated) panel pixels.""" def __init__(self, image, box=None, scale=1.0, rotation=0, header=None, header_height=28): h, w = image.shape[:2] box = [0, 0, w, h] if box is None else box x0, y0, x1, y1 = [int(round(float(v))) for v in box] x0, y0 = max(0, x0), max(0, y0) x1, y1 = min(w, x1), min(h, y1) self.box = [x0, y0, x1, y1] crop = image[y0:y1, x0:x1] if crop.ndim == 2: crop = np.repeat(crop[..., None], 3, axis=2) self.scale = float(scale) size = (max(1, int(round((x1 - x0) * scale))), max(1, int(round((y1 - y0) * scale)))) self.pre_size = size img = Image.fromarray(np.ascontiguousarray(crop[..., :3])).resize(size, Image.LANCZOS) self.rotation = int(rotation) % 360 if self.rotation: img = img.rotate(-self.rotation, expand=True) # PIL rotates counter-clockwise self.image = img self.header = header self.header_height = header_height self.draw = ImageDraw.Draw(self.image) def to_panel(self, xy): return native_to_panel(xy, self.box, self.scale, self.rotation, self.pre_size) def from_panel(self, xy): """Inverse of `to_panel`: (rotated) panel pixels back to native pixels.""" return panel_to_native(xy, self.box, self.scale, self.rotation, self.pre_size) def mapping(self): """The panel geometry as plain data, enough to invert `to_panel` elsewhere.""" return {"box": [float(v) for v in self.box], "scale": self.scale, "rotation": self.rotation, "pre_size": list(self.pre_size), "header_height": self.header_height if self.header else 0} def contains(self, xy): p = self.to_panel(xy) return bool(0 <= p[0] < self.image.width and 0 <= p[1] < self.image.height) def draw_anchor(self, xy, radius=11, color=COLOR_ANCHOR, label="A", scale=1.0, line=3, label_size=15, label_background=(0, 0, 0), arms_inside=3): """`scale` grows or shrinks the whole marker (ring, arms, line width, label) for other frame sizes; `radius`, `line` (width) and `label_size` are the marker's own proportions at scale 1. The arms start `arms_inside` px inside the ring (0 keeps the inside of the ring clear).""" x, y = self.to_panel(xy) r, k = radius * scale, scale width = max(1, int(round(line * k))) self.draw.ellipse([x - r, y - r, x + r, y + r], outline=color, width=width) for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]: start = r - arms_inside * k self.draw.line([x + dx * start, y + dy * start, x + dx * (r + 6 * k), y + dy * (r + 6 * k)], fill=color, width=width) if label: # Up and to the right of the ring; flipped below or to the left where that would leave the image. dx, dy, half = r + label_size * k * 2 / 3, r + label_size * k * 0.4, label_size * k * 0.6 lx = x + dx if x + dx + half <= self.image.width else x - dx ly = y - dy if y - dy - half >= 0 else y + dy _label(self.draw, (lx, ly), label, color, f=None if scale == 1.0 and label_size == 15 else font(max(8, int(round(label_size * k)))), centre=True, background=label_background) def draw_crosshair_center(self, color=COLOR_ANCHOR, gap=8, length=18, scale=1.0, line=3, size=1.0, dot=True): """`size` grows the arms and the centre dot; `line` is the stroke width at scale 1. Without `dot` the centre pixel is left uncovered.""" cx, cy = self.image.width / 2, self.image.height / 2 draw_dot = dot gap, length, dot = gap * scale * size, length * scale * size, 3 * scale * size for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]: self.draw.line([cx + dx * gap, cy + dy * gap, cx + dx * (gap + length), cy + dy * (gap + length)], fill=color, width=max(1, int(round(line * scale)))) if not draw_dot: return self.draw.ellipse([cx - dot, cy - dot, cx + dot, cy + dot], outline=color, width=max(1, int(round(line * 2 / 3 * scale)))) def draw_polyline(self, pts, color=COLOR_CURVE, width=2): pts = np.asarray(pts, dtype=float) if len(pts) < 2: return p = self.to_panel(pts) self.draw.line([tuple(q) for q in p], fill=color, width=width) def draw_candidates(self, candidates, radius=10, color=COLOR_CAND, number_from=1, label_mode="curve"): """Numbered circles; a candidate's own 'label' overrides its running number. label_mode: 'curve' alternates sides of the local tangent, 'radial' pushes labels away from the centroid, 'fixed' puts them upper-right.""" if not candidates: return f = font(15) pts = np.array([self.to_panel(c["xy"]) for c in candidates]) centroid = pts.mean(axis=0) for i, (x, y) in enumerate(pts): self.draw.ellipse([x - radius, y - radius, x + radius, y + radius], outline=color, width=3) self.draw.ellipse([x - 2, y - 2, x + 2, y + 2], fill=color) off = np.array([radius + 12, -(radius + 6)], dtype=float) if label_mode == "curve" and len(pts) >= 2: d = pts[min(i + 1, len(pts) - 1)] - pts[max(i - 1, 0)] n = np.linalg.norm(d) normal = np.array([-d[1], d[0]]) / n if n > 1e-6 else np.array([0.7, -0.7]) off = normal * (1 if i % 2 == 0 else -1) * (radius + 13) elif label_mode == "radial" and len(pts) >= 2: d = np.array([x, y]) - centroid n = np.linalg.norm(d) d = d / n if n > 1e-6 else np.array([0.7, -0.7]) off = d * (radius + 13) text = str(candidates[i].get("label", i + number_from)) _label(self.draw, (x + off[0], y + off[1]), text, color, f, centre=True) def draw_marker(self, xy, label=None, radius=5, color=COLOR_CURVE, width=2, offset=None): """A small ring with an optional text label, used for depth ticks. `offset` places the label centre relative to the ring, in panel pixels. """ x, y = self.to_panel(xy) self.draw.ellipse([x - radius, y - radius, x + radius, y + radius], outline=color, width=width) if label: dx, dy = (radius + 11, -(radius + 4)) if offset is None else offset _label(self.draw, (x + dx, y + dy), label, color, font(13), centre=True) def draw_points(self, pts, color, radius=4): for x, y in self.to_panel(np.asarray(pts, dtype=float).reshape(-1, 2)): self.draw.ellipse([x - radius, y - radius, x + radius, y + radius], outline=color, width=2) def finish(self): img = self.image if self.header: hh = self.header_height out = Image.new("RGB", (img.width, img.height + hh), COLOR_BG) out.paste(img, (0, hh)) d = ImageDraw.Draw(out) d.text((6, 5), self.header, fill=COLOR_HEADER, font=font(16)) img = out return img def _label(draw, xy, text, color, f=None, centre=False, background=(0, 0, 0)): f = f or font(15) x, y = xy if centre: l, t, r, b = draw.textbbox((0, 0), text, font=f) x, y = x - (r - l) / 2 - l, y - (b - t) / 2 - t bbox = draw.textbbox((x, y), text, font=f) pad = max(2, int(round(f.size / 7))) draw.rectangle([bbox[0] - pad - 1, bbox[1] - pad, bbox[2] + pad + 1, bbox[3] + pad], fill=background) draw.text((x, y), text, fill=color, font=f) GRID_LINE, GRID_TEXT = (255, 40, 40), (210, 0, 0) def pixel_zoom(image, centre, half, size): """A window 2*half native px wide centred exactly on `centre` (sub-pixel), shown at `size` px with nearest-neighbour, so every native pixel is a visible block. Native pixel i spans [i, i+1): a point at x is drawn at (x - origin) * zoom. Outside the frame is grey. Returns (PIL image, origin (x0, y0), zoom).""" zoom = size / (2 * half) x0, y0 = centre[0] - half, centre[1] - half ix = np.floor(x0 + (np.arange(size) + 0.5) / zoom).astype(int) iy = np.floor(y0 + (np.arange(size) + 0.5) / zoom).astype(int) h, w = image.shape[:2] out = image[np.clip(iy, 0, h - 1)][:, np.clip(ix, 0, w - 1)][..., :3].copy() out[~(((iy >= 0) & (iy < h))[:, None] & ((ix >= 0) & (ix < w))[None, :])] = 90 return Image.fromarray(out), (x0, y0), zoom def gap_crosshair(draw, at, color, gap, length, width): """Four arms around `at` that leave a `gap` so the marked pixel stays visible.""" x, y = at for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]: draw.line([x + dx * gap, y + dy * gap, x + dx * (gap + length), y + dy * (gap + length)], fill=color, width=width) def pixel_grid(view, origin, zoom, lines=6, label_size=13): """Red grid lines at round native coordinates (about `lines` per side), labelled red on white.""" draw, extent = ImageDraw.Draw(view), view.width / zoom step = next(s for s in (1, 2, 5, 10, 20, 25, 50, 100, 200, 500) if extent / s <= lines) f = font(label_size) for axis in (0, 1): start = origin[axis] for value in range(int(np.ceil(start / step) * step), int(start + extent) + 1, step): p = (value - start) * zoom draw.line([(p, 0), (p, view.height)] if axis == 0 else [(0, p), (view.width, p)], fill=GRID_LINE, width=1) at = (p + 2, 1) if axis == 0 else (1, p + 1) box = draw.textbbox(at, str(value), font=f) draw.rectangle([box[0] - 1, box[1] - 1, box[2] + 1, box[3] + 1], fill=(255, 255, 255)) draw.text(at, str(value), fill=GRID_TEXT, font=f) def paste_inset(base, inset, corner="tr", margin=12, border=(245, 245, 245), width=2): """Composite a small context/zoom image into a corner of `base`, with a border. `margin` is one number or an (x, y) pair; give it a y that clears the header strip. """ out = base.copy() mx, my = (margin, margin) if np.isscalar(margin) else margin x = mx if corner[1] == "l" else out.width - inset.width - mx y = my if corner[0] == "t" else out.height - inset.height - my out.paste(inset, (x, y)) ImageDraw.Draw(out).rectangle([x - width, y - width, x + inset.width + width - 1, y + inset.height + width - 1], outline=border, width=width) return out def draw_box(panel, box, color=COLOR_CURVE, width=2): """Outline a native-pixel box on a panel, following the panel's rotation.""" x0, y0, x1, y1 = [float(v) for v in box] corners = [(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)] panel.draw_polyline(np.array(corners), color=color, width=width) def concat_horizontal(images, gap=10, bg=COLOR_BG): h = max(im.height for im in images) w = sum(im.width for im in images) + gap * (len(images) - 1) out = Image.new("RGB", (w, h), bg) x = 0 for im in images: out.paste(im, (x, 0)) x += im.width + gap return out def zoom_panel(image, xy, half_size, out_size, header=None, rotation=0, scale=1.0, color=COLOR_ANCHOR, line=3, crosshair=1.0, dot=True): """Square crop around xy, upscaled; the anchor is at the crop centre.""" h, w = image.shape[:2] x, y = float(xy[0]), float(xy[1]) pad = np.zeros((h + 2 * half_size, w + 2 * half_size) + image.shape[2:], dtype=image.dtype) pad[half_size:half_size + h, half_size:half_size + w] = image box = [x, y, x + 2 * half_size, y + 2 * half_size] # shifted by the padding p = Panel(pad, box=box, scale=out_size / (2.0 * half_size), rotation=rotation, header=header) p.draw_crosshair_center(scale=scale, color=color, line=line, size=crosshair, dot=dot) return p