"""Vector rebuild + high quality upscale for a flat two-colour logo. Steps 1. binarise (the source is 1-bit: #000000 / #6F849C, no anti-aliasing) 2. optional morphological closing limited to a region (fills hairline cracks) 3. trace boundaries, simplify with Douglas-Peucker at a tight tolerance 4. round the residual pixel staircases: vertices with a small turn angle get a tiny quadratic-Bezier fillet, real corners (>= corner_deg) stay razor sharp 5. render with supersampled anti-aliasing at the requested scale Usage: python vector_up2.py in.png out.png [--scale 4] [--eps 0.6] [--round 1.6] [--corner-deg 55] [--close R:x0,y0,x1,y1] [--svg out.svg] """ from __future__ import annotations import math import sys import cv2 import numpy as np from PIL import Image, ImageDraw Image.MAX_IMAGE_PIXELS = None BG = (0, 0, 0) def binarise(img: Image.Image, thresh: int = 60) -> np.ndarray: return (np.asarray(img.convert("L")) > thresh).astype(np.uint8) def close_region(mask: np.ndarray, radius: int, box: tuple[int, int, int, int]) -> np.ndarray: x0, y0, x1, y1 = box x0, y0 = max(0, x0), max(0, y0) x1, y1 = min(mask.shape[1], x1), min(mask.shape[0], y1) sub = mask[y0:y1, x0:x1] k = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (radius * 2 + 1, radius * 2 + 1)) out = mask.copy() out[y0:y1, x0:x1] = cv2.morphologyEx(sub, cv2.MORPH_CLOSE, k) return out def smooth_dense(pts: np.ndarray, window: int) -> np.ndarray: """Circular moving average over a dense (per-pixel) closed contour.""" if window < 3 or len(pts) < window * 3: return pts n = len(pts) pad = window // 2 ext = np.concatenate([pts[-pad:], pts, pts[:pad]], axis=0) ker = np.ones(window, dtype=np.float64) / window x = np.convolve(ext[:, 0], ker, mode="valid") y = np.convolve(ext[:, 1], ker, mode="valid") return np.stack([x, y], axis=1)[:n] def trace(mask: np.ndarray, eps: float, smooth: int = 0, zone: tuple | None = None, alt: tuple | None = None) -> tuple[list[np.ndarray], list[int]]: """Trace + simplify. `zone` = (x0, y0, x1, y1) and `alt` = (eps, smooth) let contours inside that box use different simplification settings (fine detail zone). """ contours, _ = cv2.findContours(mask * 255, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) polys: list[np.ndarray] = [] for cnt in contours: if len(cnt) < 3: continue this_eps, this_smooth = eps, smooth if zone is not None and alt is not None: x, y, w, h = cv2.boundingRect(cnt) if x >= zone[0] and y >= zone[1] and x + w <= zone[2] and y + h <= zone[3]: this_eps, this_smooth = alt dense = cnt.reshape(-1, 2).astype(np.float64) if this_smooth >= 3: dense = smooth_dense(dense, this_smooth) approx = cv2.approxPolyDP(dense.reshape(-1, 1, 2).astype(np.float32), this_eps, True) approx = approx.reshape(-1, 2).astype(np.float64) else: approx = cv2.approxPolyDP(cnt, this_eps, True).reshape(-1, 2).astype(np.float64) if len(approx) < 3: approx = dense if len(approx) < 3: continue if abs(shoelace(approx)) < 3.0: continue polys.append(approx) depths = [0] * len(polys) for i, p in enumerate(polys): pt = (float(p[0][0]), float(p[0][1])) depths[i] = sum( 1 for j, q in enumerate(polys) if j != i and cv2.pointPolygonTest(q.astype(np.int32), pt, False) > 0 ) order = sorted(range(len(polys)), key=lambda k: depths[k]) return [polys[k] for k in order], [depths[k] for k in order] def shoelace(p: np.ndarray) -> float: x, y = p[:, 0], p[:, 1] return 0.5 * float(np.dot(x, np.roll(y, -1)) - np.dot(y, np.roll(x, -1))) def round_corners(poly: np.ndarray, radius: float, corner_deg: float, steps: int = 4) -> list[tuple[float, float]]: """Fillet shallow vertices, keep sharp corners untouched.""" n = len(poly) cos_limit = math.cos(math.radians(corner_deg)) out: list[tuple[float, float]] = [] for i in range(n): prev, cur, nxt = poly[i - 1], poly[i], poly[(i + 1) % n] v1 = cur - prev v2 = nxt - cur l1 = float(np.hypot(*v1)) l2 = float(np.hypot(*v2)) if l1 < 1e-9 or l2 < 1e-9: out.append((float(cur[0]), float(cur[1]))) continue u1 = v1 / l1 u2 = v2 / l2 cos_turn = float(np.dot(u1, u2)) # cos ~1 -> straight ahead, cos ~-1 -> full reversal, 0 -> 90 deg if cos_turn < cos_limit: # sharp corner: keep it out.append((float(cur[0]), float(cur[1]))) continue t = min(radius, 0.45 * l1, 0.45 * l2, 0.5 * l2 if l1 > 0 else radius) if t < 0.15: out.append((float(cur[0]), float(cur[1]))) continue p1 = cur - u1 * t p2 = cur + u2 * t for s in range(steps + 1): w = s / steps a = (1 - w) ** 2 b = 2 * (1 - w) * w c = w * w out.append((float(a * p1[0] + b * cur[0] + c * p2[0]), float(a * p1[1] + b * cur[1] + c * p2[1]))) return out def offset_polygon(poly: np.ndarray, d: float) -> np.ndarray: """Miter-offset a closed polygon by d pixels along its outward normal.""" p = np.asarray(poly, dtype=np.float64) n = len(p) if n < 3 or d == 0: return p s = shoelace(p) nxt = np.roll(p, -1, axis=0) prv = np.roll(p, 1, axis=0) e1 = p - prv # incoming edge e2 = nxt - p # outgoing edge l1 = np.hypot(e1[:, 0], e1[:, 1]) l2 = np.hypot(e2[:, 0], e2[:, 1]) l1[l1 == 0] = 1 l2[l2 == 0] = 1 e1 /= l1[:, None] e2 /= l2[:, None] if s > 0: # y-down: clockwise on screen -> outward is (dy, -dx) n1 = np.stack([e1[:, 1], -e1[:, 0]], axis=1) n2 = np.stack([e2[:, 1], -e2[:, 0]], axis=1) else: n1 = np.stack([-e1[:, 1], e1[:, 0]], axis=1) n2 = np.stack([-e2[:, 1], e2[:, 0]], axis=1) dot = np.clip((n1 * n2).sum(axis=1), -0.999, 0.999) miter = (n1 + n2) / (1 + dot)[:, None] length = np.hypot(miter[:, 0], miter[:, 1]) limit = 3.0 scale = np.where(length > limit, limit / np.maximum(length, 1e-9), 1.0) return p + miter * (d * scale)[:, None] def iou(alpha_small: Image.Image, ref: np.ndarray, thresh: int = 128) -> float: a = np.asarray(alpha_small) > thresh b = ref.astype(bool) union = (a | b).sum() return float((a & b).sum() / union) if union else 0.0 def render(polys, depths, size, scale: float, supersample: int) -> Image.Image: W, H = int(round(size[0] * scale)), int(round(size[1] * scale)) f = supersample mask = Image.new("L", (W * f, H * f), 0) draw = ImageDraw.Draw(mask) for poly, depth in zip(polys, depths): pts = [(x * scale * f, y * scale * f) for x, y in poly] if len(pts) >= 3: draw.polygon(pts, fill=0 if depth % 2 else 255) if f > 1: mask = mask.reduce(f) if f in (2, 4, 8) else mask.resize((W, H), Image.BOX) return mask def to_rgb(alpha: Image.Image, ink: tuple[int, int, int]) -> Image.Image: a = np.asarray(alpha, dtype=np.float32)[..., None] / 255.0 arr = np.empty(a.shape[:2] + (3,), dtype=np.uint8) for c in range(3): arr[..., c] = np.clip(a[..., 0] * ink[c] + (1 - a[..., 0]) * BG[c], 0, 255).astype(np.uint8) return Image.fromarray(arr, "RGB") def write_svg(path, polys, size, color): parts = [] for poly in polys: pts = " L ".join(f"{x:.2f} {y:.2f}" for x, y in poly) parts.append(f"M {pts} Z") svg = ( f'\n' f'\n' f'\n\n' ) with open(path, "w", encoding="utf-8") as fh: fh.write(svg) def main(argv: list[str]) -> int: a = list(argv) scale, eps, rnd, corner_deg, ss, close, svg_path, smooth = 4.0, 0.6, 1.6, 55.0, 2, None, None, 0 offset = 0.5 def take(flag, cast=float): nonlocal a i = a.index(flag) val = cast(a[i + 1]) del a[i:i + 2] return val if "--scale" in a: scale = take("--scale") if "--eps" in a: eps = take("--eps") if "--round" in a: rnd = take("--round") if "--smooth" in a: smooth = take("--smooth", int) if "--offset" in a: offset = take("--offset") if "--corner-deg" in a: corner_deg = take("--corner-deg") if "--supersample" in a: ss = take("--supersample", int) if "--svg" in a: svg_path = a[a.index("--svg") + 1]; del a[a.index("--svg"):a.index("--svg") + 2] if "--close" in a: raw = a[a.index("--close") + 1] del a[a.index("--close"):a.index("--close") + 2] r, box = raw.split(":") close = (int(r), tuple(int(v) for v in box.split(","))) zone, alt = None, None if "--zone" in a: raw = a[a.index("--zone") + 1] del a[a.index("--zone"):a.index("--zone") + 2] zone = tuple(int(v) for v in raw.split(",")) alt = (1.0, 0) # replaced below if given if "--zone-eps" in a: alt = (take("--zone-eps"), alt[1] if alt else 0) if "--zone-smooth" in a: alt = (alt[0] if alt else 1.0, take("--zone-smooth", int)) if len(a) != 3: print(__doc__) return 2 src_path, dst_path = a[1], a[2] src = Image.open(src_path).convert("RGB") mask = binarise(src) if close is not None: mask = close_region(mask, close[0], close[1]) print("closing applied:", close) ink = (111, 132, 156) polys, depths = trace(mask, eps, smooth, zone, alt) if rnd > 0: polys = [round_corners(p, rnd, corner_deg) for p in polys] if offset != 0.0: base_alpha = render(polys, depths, src.size, 1.0, 2).resize(src.size, Image.BOX) base_iou = iou(base_alpha, mask) best = (base_iou, 0.0, polys) for sign in (1.0, -1.0): cand = [offset_polygon(p, sign * offset) for p in polys] a1 = render(cand, depths, src.size, 1.0, 2).resize(src.size, Image.BOX) score = iou(a1, mask) if score > best[0]: best = (score, sign * offset, cand) print(f"offset chosen: {best[1]:+.2f}px IoU {base_iou:.4f} -> {best[0]:.4f}") polys = best[2] print(f"contours: {len(polys)} eps={eps} round={rnd}") alpha = render(polys, depths, src.size, scale, ss) out = to_rgb(alpha, ink) out.save(dst_path, "PNG", optimize=True) print(f"written: {dst_path} {out.size[0]}x{out.size[1]}") if svg_path: write_svg(svg_path, polys, src.size, "#%02x%02x%02x" % ink) print(f"written: {svg_path}") return 0 if __name__ == "__main__": raise SystemExit(main(sys.argv))