sidrefresh's picture
Add files using upload-large-folder tool
7ec48b5 verified
Raw History Blame Contribute Delete
5.22 kB
"""Render one .blend from its own active camera at frame 1 to a small PNG, then
(optionally) compare two such renders. Runs INSIDE Blender, headless:
blender -b <file.blend> -Y --python render_view.py -- render <out.png> [assets_dir]
blender -b -Y --python render_view.py -- compare <a.png> <b.png> <out.json>
This is the render half of the reference-driven grader, after the pattern of
refresh-platform's ``render_compare`` (both sides rendered inside the verifier
sandbox with identical settings, compared with numpy only; no third-party
image libraries; PNGs read through ``bpy.data.images``).
Render settings are forced identical on both sides so the comparison measures
the scene, not the render configuration: Cycles CPU, fixed seed, 480x270,
few samples + denoise, the scene's own view transform/look kept (the tutorial
sets AgX Medium High Contrast in Part 11 and that IS part of the look being
graded). Missing texture paths are re-linked against ``assets_dir`` so a
reference copied out of its folder renders with its textures.
Similarity = 0.35 * (1 - mean |ΔRGB|) + 0.30 * luminance-edge agreement
+ 0.35 * colour-histogram intersection (all in [0, 1])
"""
import json
import math
import os
import sys
import bpy
args = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
mode = args[0] if args else "render"
def do_render(out_png, assets_dir=None):
scene = bpy.context.scene
if assets_dir and os.path.isdir(assets_dir):
try:
bpy.ops.file.find_missing_files(directory=assets_dir, find_all=True)
except Exception as e: # noqa: BLE001
print("find_missing_files:", e)
scene.frame_set(scene.frame_start)
scene.render.engine = "CYCLES"
scene.cycles.device = "CPU"
scene.cycles.samples = int(os.environ.get("T19_RENDER_SAMPLES", "24"))
scene.cycles.use_adaptive_sampling = False
scene.cycles.seed = 7
scene.cycles.use_denoising = True
try:
scene.cycles.denoiser = "OPENIMAGEDENOISE"
except Exception:
pass
scene.cycles.time_limit = float(os.environ.get("T19_RENDER_TIME_LIMIT", "240"))
scene.render.resolution_x, scene.render.resolution_y = 480, 270
scene.render.resolution_percentage = 100
scene.render.film_transparent = False
scene.render.image_settings.file_format = "PNG"
scene.render.image_settings.color_mode = "RGB"
scene.render.image_settings.color_depth = "8"
scene.render.use_compositing = False # compositor glare would dominate the comparison
scene.render.use_sequencer = False
scene.render.filepath = out_png
if scene.camera is None:
cams = [o for o in scene.objects if o.type == "CAMERA"]
if not cams:
print("NO_CAMERA")
sys.exit(3)
scene.camera = cams[0]
bpy.ops.render.render(write_still=True)
print("RENDERED", out_png)
def load_rgb(path, size=(480, 270)):
img = bpy.data.images.load(path, check_existing=False)
if tuple(img.size) != tuple(size): # the learner's frame is 1920x1080: resample, never crop
img.scale(*size)
w, h = img.size
import numpy as np
px = np.empty(w * h * 4, dtype=np.float32)
img.pixels.foreach_get(px)
rgb = px.reshape(h, w, 4)[:, :, :3]
bpy.data.images.remove(img)
return np.ascontiguousarray(rgb[::-1])
def compare(a_png, b_png, out_json):
import numpy as np
a, b = load_rgb(a_png), load_rgb(b_png)
if a.shape != b.shape:
h = min(a.shape[0], b.shape[0]); w = min(a.shape[1], b.shape[1])
a, b = a[:h, :w], b[:h, :w]
# 1. pixel colour: mean absolute difference (0 = identical)
mae = float(np.mean(np.abs(a - b)))
pixel_color = max(0.0, 1.0 - 2.5 * mae) # MAE 0.4 -> 0
# 2. luminance edges: gradient-magnitude maps, normalised correlation
def lum(x):
return 0.2126 * x[:, :, 0] + 0.7152 * x[:, :, 1] + 0.0722 * x[:, :, 2]
def edges(x):
l = lum(x)
gx = np.abs(np.diff(l, axis=1))[:-1, :]
gy = np.abs(np.diff(l, axis=0))[:, :-1]
return gx + gy
ea, eb = edges(a), edges(b)
ea = (ea - ea.mean()) / (ea.std() + 1e-6); eb = (eb - eb.mean()) / (eb.std() + 1e-6)
edge_corr = float(np.clip(np.mean(ea * eb), 0.0, 1.0))
# 3. colour histogram intersection (8x8x8 bins)
def hist(x):
q = np.clip((x * 7.999).astype(int), 0, 7)
idx = q[:, :, 0] * 64 + q[:, :, 1] * 8 + q[:, :, 2]
h = np.bincount(idx.ravel(), minlength=512).astype(np.float64)
return h / max(h.sum(), 1.0)
hist_int = float(np.minimum(hist(a), hist(b)).sum())
similarity = 0.35 * pixel_color + 0.30 * edge_corr + 0.35 * hist_int
res = {"mae": mae, "pixel_color": pixel_color, "edge_corr": edge_corr, "hist_intersection": hist_int,
"similarity": similarity, "shape": list(a.shape)}
with open(out_json, "w") as f:
json.dump(res, f, indent=1)
print("COMPARE", json.dumps(res))
if mode == "render":
do_render(args[1], args[2] if len(args) > 2 else None)
elif mode == "compare":
compare(args[1], args[2], args[3])
else:
print("usage: render <out.png> [assets_dir] | compare <a> <b> <out.json>")
sys.exit(2)