File size: 9,535 Bytes
5221018
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
#!/usr/bin/env python3
import argparse
import json
import struct
from pathlib import Path

import numpy as np
from PIL import Image, ImageDraw


def load_camera_matrix(path: Path) -> np.ndarray:
    if path.suffix.lower() == ".json":
        data = json.loads(path.read_text())
        if isinstance(data, dict):
            for key in ("cam_K", "K", "camera_matrix", "intrinsic", "intrinsics"):
                if key in data:
                    data = data[key]
                    break
        arr = np.asarray(data, dtype=np.float64)
    else:
        arr = np.loadtxt(path, dtype=np.float64)
    if arr.size == 9:
        arr = arr.reshape(3, 3)
    if arr.shape != (3, 3):
        raise ValueError(f"Camera matrix must be 3x3 or 9 values, got {arr.shape} from {path}")
    return arr


def parse_ply_header(f):
    first = f.readline().decode("ascii", errors="replace").strip()
    if first != "ply":
        raise ValueError("Only PLY files are supported")

    fmt = None
    vertex_count = None
    face_count = None
    vertex_props = []
    current_element = None

    while True:
        line = f.readline().decode("ascii", errors="replace").strip()
        if line == "end_header":
            break
        parts = line.split()
        if not parts:
            continue
        if parts[0] == "format":
            fmt = parts[1]
        elif parts[0] == "element":
            current_element = parts[1]
            if parts[1] == "vertex":
                vertex_count = int(parts[2])
            elif parts[1] == "face":
                face_count = int(parts[2])
        elif parts[0] == "property" and current_element == "vertex":
            vertex_props.append((parts[1], parts[2]))

    if fmt not in {"binary_little_endian", "ascii"}:
        raise ValueError(f"Unsupported PLY format: {fmt}")
    if vertex_count is None or face_count is None:
        raise ValueError("PLY must contain vertex and face elements")
    return fmt, vertex_count, face_count, vertex_props


def load_ply_mesh(path: Path):
    scalar_formats = {
        "char": "b", "int8": "b",
        "uchar": "B", "uint8": "B",
        "short": "h", "int16": "h",
        "ushort": "H", "uint16": "H",
        "int": "i", "int32": "i",
        "uint": "I", "uint32": "I",
        "float": "f", "float32": "f",
        "double": "d", "float64": "d",
    }

    with path.open("rb") as f:
        fmt, vertex_count, face_count, vertex_props = parse_ply_header(f)
        prop_names = [name for _, name in vertex_props]
        try:
            x_i, y_i, z_i = prop_names.index("x"), prop_names.index("y"), prop_names.index("z")
        except ValueError as exc:
            raise ValueError(f"PLY vertices in {path} must have x/y/z properties") from exc

        if fmt == "ascii":
            vertices = np.empty((vertex_count, 3), dtype=np.float32)
            for i in range(vertex_count):
                values = f.readline().decode("ascii").split()
                vertices[i] = [float(values[x_i]), float(values[y_i]), float(values[z_i])]
            faces = []
            for _ in range(face_count):
                values = f.readline().decode("ascii").split()
                n = int(values[0])
                ids = [int(v) for v in values[1:1 + n]]
                for j in range(1, n - 1):
                    faces.append((ids[0], ids[j], ids[j + 1]))
            return vertices, np.asarray(faces, dtype=np.int32)

        vertex_struct = "<" + "".join(scalar_formats[t] for t, _ in vertex_props)
        vertex_size = struct.calcsize(vertex_struct)
        raw = f.read(vertex_count * vertex_size)
        unpacked = struct.iter_unpack(vertex_struct, raw)
        vertices = np.empty((vertex_count, 3), dtype=np.float32)
        for i, values in enumerate(unpacked):
            vertices[i] = [values[x_i], values[y_i], values[z_i]]

        faces = []
        for _ in range(face_count):
            n = struct.unpack("<B", f.read(1))[0]
            ids = struct.unpack("<" + "i" * n, f.read(4 * n))
            for j in range(1, n - 1):
                faces.append((ids[0], ids[j], ids[j + 1]))
        return vertices, np.asarray(faces, dtype=np.int32)


def get_pose(pose_path: Path, img_id: str, obj_id: int, occurrence: int = 0):
    data = json.loads(pose_path.read_text())
    keys = [img_id, str(int(img_id)) if str(img_id).isdigit() else img_id, f"{int(img_id):06d}" if str(img_id).isdigit() else img_id]
    frame = None
    for key in keys:
        if key in data:
            frame = data[key]
            break
    if frame is None:
        raise KeyError(f"Image id {img_id} not found in {pose_path}")

    matches = [item for item in frame if int(item["obj_id"]) == obj_id]
    if not matches:
        available = sorted({int(item["obj_id"]) for item in frame})
        raise KeyError(f"Object id {obj_id} not found for image {img_id}. Available: {available}")
    if occurrence >= len(matches):
        raise IndexError(f"Object id {obj_id} has only {len(matches)} occurrence(s), requested {occurrence}")

    item = matches[occurrence]
    R = np.asarray(item["cam_R_m2c"], dtype=np.float64).reshape(3, 3)
    t = np.asarray(item["cam_t_m2c"], dtype=np.float64).reshape(3)
    return R, t


def project_vertices(vertices, R, t, K):
    cam = vertices.astype(np.float64) @ R.T + t.reshape(1, 3)
    z = cam[:, 2]
    uv = np.empty((len(vertices), 2), dtype=np.float64)
    uv[:, 0] = K[0, 0] * cam[:, 0] / z + K[0, 2]
    uv[:, 1] = K[1, 1] * cam[:, 1] / z + K[1, 2]
    return uv, z


def render_mask(vertices, faces, R, t, K, width, height):
    uv, z = project_vertices(vertices, R, t, K)
    mask = Image.new("L", (width, height), 0)
    draw = ImageDraw.Draw(mask)

    for face in faces:
        zs = z[face]
        if np.any(zs <= 1e-8):
            continue
        pts = uv[face]
        if (pts[:, 0].max() < 0 or pts[:, 0].min() >= width or
                pts[:, 1].max() < 0 or pts[:, 1].min() >= height):
            continue
        draw.polygon([tuple(p) for p in pts], fill=255)
    return np.asarray(mask, dtype=np.uint8) > 0


def mask_edges(mask, thickness):
    pad = thickness
    padded = np.pad(mask, pad, mode="constant", constant_values=False)
    eroded = np.ones_like(mask, dtype=bool)
    for dy in range(-thickness, thickness + 1):
        for dx in range(-thickness, thickness + 1):
            if dx * dx + dy * dy <= thickness * thickness:
                eroded &= padded[pad + dy:pad + dy + mask.shape[0], pad + dx:pad + dx + mask.shape[1]]
    return mask & ~eroded


def overlay_edges(image, edges, color, alpha):
    rgb = np.asarray(image.convert("RGB"), dtype=np.float32)
    edge_color = np.asarray(color, dtype=np.float32).reshape(1, 1, 3)
    rgb[edges] = rgb[edges] * (1.0 - alpha) + edge_color * alpha
    return Image.fromarray(np.clip(rgb, 0, 255).astype(np.uint8))


def make_img_id(value: str) -> str:
    return f"{int(value):06d}" if str(value).isdigit() else value


def main():
    parser = argparse.ArgumentParser(description="Render a posed object mesh silhouette edge on an RGB image.")
    parser.add_argument("--seq-id", type=int, required=True, help="Sequence id, e.g. 1 for static/seq_1")
    parser.add_argument("--img-id", required=True, help="Image id, e.g. 0 or 000000")
    parser.add_argument("--obj-id", type=int, required=True, help="Object/model id, e.g. 1 for models/1.ply")
    parser.add_argument("--occurrence", type=int, default=0, help="Occurrence index if the same obj_id appears multiple times")
    parser.add_argument("--root", default=".", help="Dataset root containing static/, models/, and cam_K.txt/cam_K.json")
    parser.add_argument("--camera", default=None, help="Camera intrinsic file. Defaults to cam_K.json if present, otherwise cam_K.txt")
    parser.add_argument("--output", default=None, help="Output image path")
    parser.add_argument("--edge-thickness", type=int, default=3, help="Rendered silhouette edge thickness in pixels")
    parser.add_argument("--color", nargs=3, type=int, default=[255, 0, 0], metavar=("R", "G", "B"), help="Edge color")
    parser.add_argument("--alpha", type=float, default=1.0, help="Edge overlay alpha in [0, 1]")
    args = parser.parse_args()

    root = Path(args.root)
    img_id = make_img_id(args.img_id)
    seq_dir = root / "static" / f"seq_{args.seq_id}"
    rgb_path = seq_dir / "rgb" / f"{img_id}.png"
    pose_path = seq_dir / "pose.json"
    model_path = root / "models" / f"{args.obj_id}.ply"

    if args.camera is not None:
        camera_path = Path(args.camera)
    else:
        json_path = root / "cam_K.json"
        txt_path = root / "cam_K.txt"
        camera_path = json_path if json_path.exists() else txt_path

    for path in (rgb_path, pose_path, model_path, camera_path):
        if not path.exists():
            raise FileNotFoundError(path)

    image = Image.open(rgb_path).convert("RGB")
    width, height = image.size
    K = load_camera_matrix(camera_path)
    R, t = get_pose(pose_path, img_id, args.obj_id, args.occurrence)
    vertices, faces = load_ply_mesh(model_path)

    mask = render_mask(vertices, faces, R, t, K, width, height)
    edges = mask_edges(mask, max(1, args.edge_thickness))
    result = overlay_edges(image, edges, args.color, np.clip(args.alpha, 0.0, 1.0))

    output = Path(args.output) if args.output else root / f"edge_seq{args.seq_id}_img{img_id}_obj{args.obj_id}.png"
    output.parent.mkdir(parents=True, exist_ok=True)
    result.save(output)
    print(f"Saved {output}")


if __name__ == "__main__":
    main()