Spaces:
Running
Running
File size: 5,767 Bytes
ab0a0fc | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 | """Renderiza una escena sintética con geometría conocida (verdad de terreno).
Raytracer numpy determinista (sin dependencias externas salvo numpy+Pillow).
Coordenadas tipo OpenCV: x derecha, y abajo, z adelante; unidades en metros.
Salida: example-synthetic-room.jpg + synthetic-room-gt.json
"""
import json, math, sys
import numpy as np
from PIL import Image
W, H = 1024, 768
FOV_X = 60.0
fx = (W / 2) / math.tan(math.radians(FOV_X / 2)); fy = fx
cx, cy = W / 2, H / 2
CAM_H = 1.5 # cámara a 1,5 m sobre el suelo (suelo en y=+1.5)
FLOOR_Y = CAM_H
CEIL_Y = CAM_H - 2.8 # techo a 2,8 m del suelo
BACK_Z = 7.0
LEFT_X, RIGHT_X = -2.5, 2.5
# cubo de 1 m apoyado en el suelo
CUBE_MIN = np.array([-1.4, FLOOR_Y - 1.0, 4.0]); CUBE_MAX = CUBE_MIN + 1.0
# esfera de 0,5 m de radio apoyada en el suelo
SPH_C = np.array([0.2, FLOOR_Y - 0.5, 5.0]); SPH_R = 0.5
# puerta en la pared del fondo (0,9 x 2,0 m)
DOOR = dict(x0=0.6, x1=1.5, y0=FLOOR_Y - 2.0, y1=FLOOR_Y)
j, i = np.meshgrid(np.arange(W) + 0.5, np.arange(H) + 0.5)
d = np.stack([(j - cx) / fx, (i - cy) / fy, np.ones_like(j)], -1)
d = d / np.linalg.norm(d, axis=-1, keepdims=True)
N = W * H
d = d.reshape(-1, 3)
t_best = np.full(N, np.inf); nrm = np.zeros((N, 3)); obj = np.zeros(N, int)
def upd(t, n, oid):
global t_best
m = (t > 1e-6) & (t < t_best)
t_best = np.where(m, t, t_best)
nrm[m] = n[m] if n.ndim == 2 else n
obj[m] = oid
with np.errstate(divide='ignore', invalid='ignore'):
# planos: suelo, techo, fondo, paredes
for oid, axis, val, n in [(1, 1, FLOOR_Y, [0, -1, 0]), (2, 1, CEIL_Y, [0, 1, 0]), (3, 2, BACK_Z, [0, 0, -1]),
(4, 0, LEFT_X, [1, 0, 0]), (5, 0, RIGHT_X, [-1, 0, 0])]:
t = val / d[:, axis]
upd(np.where(t > 0, t, np.inf), np.array(n, float), oid)
# cubo (slabs)
t0 = (CUBE_MIN - 0) / d; t1 = (CUBE_MAX - 0) / d
tmin = np.minimum(t0, t1); tmax = np.maximum(t0, t1)
tn = tmin.max(1); tf = tmax.min(1)
hit = (tn <= tf) & (tn > 0)
ax = tmin.argmax(1)
ncube = np.zeros((N, 3)); ncube[np.arange(N), ax] = -np.sign(d[np.arange(N), ax])
upd(np.where(hit, tn, np.inf), ncube, 6)
# esfera
b = d @ SPH_C; c = SPH_C @ SPH_C - SPH_R ** 2
disc = b * b - c
ts = np.where(disc > 0, b - np.sqrt(np.maximum(disc, 0)), np.inf)
p = d * ts[:, None]; ns = (p - SPH_C) / SPH_R
upd(ts, ns, 7)
P = d * t_best[:, None]
light = np.array([0.5, -1.0, 2.5]) # luz puntual cerca del techo
L = light - P; dist = np.linalg.norm(L, axis=1, keepdims=True); L = L / dist
lam = np.clip((nrm * L).sum(1), 0, 1)
# sombra simple (sólo cubo y esfera como oclusores)
def shadow(P, L, dist):
s = np.zeros(len(P), bool)
O = P + nrm * 1e-3
with np.errstate(divide='ignore', invalid='ignore'):
t0 = (CUBE_MIN - O) / L; t1 = (CUBE_MAX - O) / L
tn = np.minimum(t0, t1).max(1); tf = np.maximum(t0, t1).min(1)
s |= (tn <= tf) & (tn > 0) & (tn < dist[:, 0])
oc = O - SPH_C; b = (L * oc).sum(1); c = (oc * oc).sum(1) - SPH_R ** 2
disc = b * b - c; t = -b - np.sqrt(np.maximum(disc, 0))
s |= (disc > 0) & (t > 0) & (t < dist[:, 0])
return s
sh = shadow(P, L, dist)
base = np.zeros((N, 3))
# texturas: suelo ajedrez 0,5 m; paredes yeso; puerta madera; cubo rojo; esfera azul
fl = obj == 1
chk = ((np.floor(P[:, 0] / 0.5) + np.floor(P[:, 2] / 0.5)) % 2 == 0)
base[fl] = np.where(chk[fl, None], [0.82, 0.80, 0.76], [0.35, 0.33, 0.31])
base[obj == 2] = [0.92, 0.92, 0.92]
base[obj == 3] = [0.78, 0.82, 0.86]
door = (obj == 3) & (P[:, 0] > DOOR['x0']) & (P[:, 0] < DOOR['x1']) & (P[:, 1] > DOOR['y0'])
base[door] = [0.55, 0.36, 0.20]
base[(obj == 4) | (obj == 5)] = [0.86, 0.80, 0.70]
base[obj == 6] = [0.80, 0.15, 0.12]
base[obj == 7] = [0.15, 0.35, 0.80]
amb = 0.25
col = base * (amb + 0.85 * lam[:, None] * (~sh)[:, None] * np.clip(6.0 / dist ** 1.0, 0, 1.5))
col = np.clip(col, 0, 1) ** (1 / 2.2)
img = (col.reshape(H, W, 3) * 255).round().astype(np.uint8)
out = sys.argv[1] if len(sys.argv) > 1 else '.'
Image.fromarray(img).save(f'{out}/example-synthetic-room.jpg', quality=92)
def proj(X):
return [float(fx * X[0] / X[2] + cx), float(fy * X[1] / X[2] + cy)]
c0 = CUBE_MIN
# arista frontal inferior del cubo (cara z=3.0): de (-1.2, 1.5, 3) a (-0.2, 1.5, 3)
gt = {
"description": "Escena sintética generada por scripts/render_synthetic.py (CC0, sin fotos de terceros).",
"image": {"width": W, "height": H}, "fov_x_deg": FOV_X, "fx_px": fx, "fy_px": fy, "camera_height_m": CAM_H,
"objects": {
"cube": {"edge_m": 1.0, "min": CUBE_MIN.tolist(), "max": CUBE_MAX.tolist()},
"sphere": {"center": SPH_C.tolist(), "radius_m": SPH_R},
"door": {"width_m": 0.9, "height_m": 2.0, "z": BACK_Z},
"floor_tile_m": 0.5, "back_wall_z_m": BACK_Z, "room_width_m": RIGHT_X - LEFT_X, "room_height_m": FLOOR_Y - CEIL_Y,
},
"measurements": {
"cube_front_width": {"a3d": [-1.37, FLOOR_Y - 0.5, 4.0], "b3d": [-0.43, FLOOR_Y - 0.5, 4.0], "length_m": 0.94},
"cube_front_height": {"a3d": [-0.9, FLOOR_Y - 0.97, 4.0], "b3d": [-0.9, FLOOR_Y - 0.03, 4.0], "length_m": 0.94},
"door_height": {"a3d": [1.05, FLOOR_Y - 1.98, BACK_Z], "b3d": [1.05, FLOOR_Y - 0.03, BACK_Z], "length_m": 1.95},
"door_width": {"a3d": [0.62, FLOOR_Y - 1.0, BACK_Z], "b3d": [1.48, FLOOR_Y - 1.0, BACK_Z], "length_m": 0.86},
},
}
for k, m in gt["measurements"].items():
m["a_px"] = proj(np.array(m["a3d"])); m["b_px"] = proj(np.array(m["b3d"]))
depth = (P[:, 2]).reshape(H, W)
gt["gt_depth_center_m"] = float(depth[H // 2, W // 2])
np.save(f'{out}/../../_work/synthetic_gt_depth.npy', depth.astype(np.float32))
json.dump(gt, open(f'{out}/synthetic-room-gt.json', 'w'), indent=1, ensure_ascii=False)
print(json.dumps(gt["measurements"], indent=1))
|