Download visualize_object_contour.py from visioner/DeSOPE: direct link, hf CLI and curl.
- Browser
- Download file 9.54 kB
-
https://huggingface.co/datasets/visioner/DeSOPE/resolve/main/visualize_object_contour.py
- Command line
-
hf download hf://datasets/visioner/DeSOPE/visualize_object_contour.py
-
curl -L -o visualize_object_contour.py https://huggingface.co/datasets/visioner/DeSOPE/resolve/main/visualize_object_contour.py
9.54 kB
| #!/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() | |