Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899"""Put exact content (a sign, screen, poster, meter face, board position, formula) onto a flat surface seen inperspective in a generated frame. Image models garble exact text and values; render them in code and warp them in.
uv run --with opencv-python-headless --with numpy python previz/perspective_insert.py frame.png out.png \ --quad 513,603 873,603 882,688 505,688 --texture sign.png [--clear] [--light 0.8] [--grain 0.03] ... --text "OPEN 24/7" --fg 20,20,20 --bg 235,230,215 # render a simple text texture instead of --texture
--quad: the surface's corners in image pixels, in order top-left, top-right, bottom-right, bottom-left (as seen on thesurface). Measure them on a zoomed crop of the frame. The texture fills the quad (homography, cv2.getPerspectiveTransform).Recipe (each step is an option or a function to reuse in other scripts, e.g. per frame for a tracked insert):1. clear (--clear): remove old content inside the quad — mask very dark / very bright blobs (HSV), dilate, inpaint, then rebuild the surface as its low-frequency light (heavy Gaussian blur keeps a spotlight pool/falloff) plus synthetic grain so it doesn't look airbrushed.2. warp the texture in a supersampled crop (SS x) with anti-aliasing and downsample with INTER_AREA, so thin lines stay crisp.3. match light (--light): multiply the texture by the surface's own low-frequency luminance (normalised), so the insert picks up the scene's shading instead of looking pasted on; add the same grain (--grain) as the plate.For 3D objects on the surface (stones, pieces, buttons) render lit primitives in the same supersampled crop: an ellipsetop + short side band per object, dome shading, a specular highlight toward the key light, a blurred contact shadow,extra brightness inside the spotlight, far objects first. Always check a zoomed crop AND the full frame."""import argparseimport cv2import numpy as np
def pts(s): return tuple(float(v) for v in s.split(","))
def text_texture(text, fg=(20, 20, 20), bg=(235, 230, 215), size=(1200, 400)): """A plain text card (BGR), auto-sized font; replace with any code-rendered texture.""" img = np.full((size[1], size[0], 3), bg[::-1], np.uint8) scale = 10.0 while scale > 0.5: (w, h), base = cv2.getTextSize(text, cv2.FONT_HERSHEY_DUPLEX, scale, max(1, int(scale * 2))) if w < size[0] * 0.9 and h < size[1] * 0.7: break scale *= 0.9 cv2.putText(img, text, ((size[0] - w) // 2, (size[1] + h) // 2), cv2.FONT_HERSHEY_DUPLEX, scale, fg[::-1], max(1, int(scale * 2)), cv2.LINE_AA) return img
def clear_surface(crop, mask, seed=0): """Inpaint dark/bright blobs inside mask, then rebuild the surface as low-frequency light + fine grain.""" hsv = cv2.cvtColor(crop, cv2.COLOR_BGR2HSV) blobs = ((hsv[..., 2] < 95) | ((hsv[..., 1] < 45) & (hsv[..., 2] > 170))) & (mask > 0) blobs = cv2.dilate(blobs.astype(np.uint8) * 255, np.ones((9, 9), np.uint8), iterations=3) base = cv2.inpaint(crop, blobs, 12, cv2.INPAINT_TELEA) low = cv2.GaussianBlur(base.astype(np.float32), (0, 0), max(4, crop.shape[1] / 60)) rng = np.random.default_rng(seed) grain = cv2.GaussianBlur(rng.normal(0, 1, crop.shape[:2]).astype(np.float32), (0, 0), sigmaX=14, sigmaY=0.8) grain = grain / (grain.std() + 1e-6) * 0.035 clean = np.clip(low * (1 + grain[..., None]), 0, 255).astype(np.uint8) return np.where(mask[..., None] > 0, clean, crop)
def insert(img, quad, texture, clear=False, light=0.8, grain=0.03, ss=4, pad=12, seed=0): """Return img (BGR) with texture warped into quad [(x,y) TL, TR, BR, BL].""" q = np.float32(quad) x0, y0 = np.floor(q.min(0) - pad).astype(int).clip(0) x1, y1 = np.ceil(q.max(0) + pad).astype(int) x1, y1 = min(x1, img.shape[1]), min(y1, img.shape[0]) crop = cv2.resize(img[y0:y1, x0:x1], None, fx=ss, fy=ss, interpolation=cv2.INTER_CUBIC) qs = np.float32((q - [x0, y0]) * ss) mask = np.zeros(crop.shape[:2], np.uint8) cv2.fillConvexPoly(mask, np.int32(qs), 255) if clear: crop = clear_surface(crop, mask, seed) th, tw = texture.shape[:2] M = cv2.getPerspectiveTransform(np.float32([(0, 0), (tw, 0), (tw, th), (0, th)]), qs) warped = cv2.warpPerspective(texture, M, (crop.shape[1], crop.shape[0]), flags=cv2.INTER_LANCZOS4).astype(np.float32) alpha = cv2.warpPerspective(np.full((th, tw), 1, np.float32), M, (crop.shape[1], crop.shape[0]), flags=cv2.INTER_LINEAR) alpha = cv2.GaussianBlur(alpha, (0, 0), 0.6 * ss / 4)[..., None] if light: # the surface's own shading, normalised to its mean, applied to the insert lum = cv2.GaussianBlur(cv2.cvtColor(crop, cv2.COLOR_BGR2GRAY).astype(np.float32), (0, 0), 8 * ss) shade = lum / (lum[mask > 0].mean() + 1e-6) warped *= (1 - light + light * shade)[..., None] if grain: g = cv2.GaussianBlur(np.random.default_rng(seed + 1).normal(0, 1, crop.shape[:2]).astype(np.float32), (0, 0), ss / 2) warped *= (1 + grain * g / (g.std() + 1e-6))[..., None] crop = np.clip(crop * (1 - alpha) + warped * alpha, 0, 255).astype(np.uint8) out = img.copy() out[y0:y1, x0:x1] = cv2.resize(crop, (x1 - x0, y1 - y0), interpolation=cv2.INTER_AREA) return out
if __name__ == "__main__": ap = argparse.ArgumentParser() ap.add_argument("src"); ap.add_argument("dst") ap.add_argument("--quad", nargs=4, type=pts, required=True, metavar="X,Y", help="TL TR BR BL corners in pixels") ap.add_argument("--texture", help="flat content image (any size; aspect should match the surface)") ap.add_argument("--text", help="render a simple text card instead of --texture") ap.add_argument("--fg", type=pts, default=(20, 20, 20)); ap.add_argument("--bg", type=pts, default=(235, 230, 215)) ap.add_argument("--clear", action="store_true", help="inpaint the old content inside the quad first") ap.add_argument("--light", type=float, default=0.8, help="0 = flat paste, 1 = full surface shading") ap.add_argument("--grain", type=float, default=0.03) ap.add_argument("--ss", type=int, default=4, help="supersampling factor") a = ap.parse_args() img = cv2.imread(a.src) tex = cv2.imread(a.texture) if a.texture else text_texture(a.text or "SAMPLE", a.fg, a.bg) cv2.imwrite(a.dst, insert(img, a.quad, tex, a.clear, a.light, a.grain, a.ss)) print("wrote", a.dst)