File size: 2,674 Bytes
1b140f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Render a FLAME mesh overlay with a separately obtained FLAME model's topology."""
import argparse
import pickle
from pathlib import Path

import numpy as np
from PIL import Image, ImageDraw

from load_sample import load_sample


def visualize(sample, faces, output):
    camera = sample["camera"]
    vertices = sample["vertices_world"] @ np.asarray(camera["R"]).T + np.asarray(camera["t"])
    K = np.asarray(camera["K"])
    projection = vertices @ K.T
    assert (vertices[:, 2] > 0).all()
    uv = projection[:, :2] / projection[:, 2:]
    image = Image.fromarray(sample["image"])
    width, height = image.size
    assert [width, height] == [camera["width"], camera["height"]]
    # Painter's algorithm, back to front; opaque triangles hide rear surfaces.
    mesh = Image.new("RGB", image.size, (0, 0, 0))
    mask = Image.new("L", image.size, 0)
    draw, draw_mask = ImageDraw.Draw(mesh), ImageDraw.Draw(mask)
    triangles = vertices[faces]
    normals = np.cross(triangles[:, 1] - triangles[:, 0], triangles[:, 2] - triangles[:, 0])
    normals /= np.maximum(np.linalg.norm(normals, axis=1, keepdims=True), 1e-12)
    colors = ((normals * 0.5 + 0.5) * 255).astype(np.uint8)
    for index in np.argsort(triangles[..., 2].mean(axis=1))[::-1]:
        points = [tuple(p) for p in uv[faces[index]].tolist()]
        draw.polygon(points, fill=tuple(colors[index].tolist()))
        draw_mask.polygon(points, fill=255)
    overlay = Image.composite(Image.blend(image, mesh, 0.55), image, mask)
    x0, y0, x1, y1 = sample["metadata"]["bbox_xyxy"]
    ImageDraw.Draw(overlay).rectangle((x0, y0, x1, y1), outline=(255, 180, 0), width=2)
    segmentation = Image.fromarray(np.repeat((sample["foreground"] * 255).astype(np.uint8)[..., None], 3, axis=2))
    result = Image.new("RGB", (width * 3, height))
    for index, panel in enumerate((image, overlay, segmentation)):
        result.paste(panel, (index * width, 0))
    result.thumbnail((1500, 900))
    result.save(output)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--root", type=Path, required=True)
    parser.add_argument("--subject", required=True)
    parser.add_argument("--frame", required=True)
    parser.add_argument("--camera", required=True)
    parser.add_argument("--flame-model", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    with args.flame_model.open("rb") as stream:
        faces = np.asarray(pickle.load(stream, encoding="latin1")["f"], dtype=np.int32)
    visualize(load_sample(args.root, args.subject, args.frame, args.camera), faces, args.output)