vsg_eval / dataset_quality /visualize_pe_obj.py
royguw's picture
Add files using upload-large-folder tool
72555a4 verified
Raw History Blame Contribute Delete
17.7 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Visualize PE-Video samples with:
- colored instance masks (per object id)
- centroid label box (object name)
- relationship text panel appended under the video
Assumptions:
- training JSON entries look like:
{
"video": ".../xxx.mp4",
"mask_json": "..._rle.json",
"obj_list": [0,1,...],
"has_relationships": True/False,
"conversations": [
{"from":"human", ...},
{"from":"gpt", "value": "<json string of objects/relationships>"}
],
"mode": "mode_6"
}
- mask_json file format:
masks = List[List[rle]]
masks[frame_idx][object_idx] = {"size":[H,W], "counts": ...}
- relationships format inside gpt JSON:
"relationships": [
[sub_id, "rel", obj_id, [[t0,t1],[t2,t3], ...]],
...
]
where each interval [t0,t1] is inclusive frame indices (we treat as inclusive).
"""
import os
import re
import json
import math
import random
import argparse
from typing import Any, Dict, List, Tuple, Optional
import cv2
import numpy as np
import shutil
try:
from pycocotools import mask as mask_utils
except Exception as e:
raise RuntimeError(
"pycocotools is required. Install via: pip install pycocotools"
) from e
# -----------------------------
# Utilities
# -----------------------------
def draw_top_left_hud(frame_bgr: np.ndarray, text: str):
x, y = 10, 10
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 0.5
thickness = 2
pad = 8
(tw, th), baseline = cv2.getTextSize(text, font, font_scale, thickness)
box_w = tw + pad * 2
box_h = th + baseline + pad * 2
overlay = frame_bgr.copy()
cv2.rectangle(overlay, (x, y), (x + box_w, y + box_h), (0, 0, 0), thickness=-1)
cv2.addWeighted(overlay, 0.45, frame_bgr, 0.55, 0, frame_bgr)
cv2.putText(frame_bgr, text, (x + pad, y + pad + th),
font, font_scale, (255, 255, 255), thickness, cv2.LINE_AA)
def draw_id_at_centroid(frame_bgr: np.ndarray, obj_id: int, center_xy: Tuple[int,int], color_bgr: Tuple[int,int,int]):
cx, cy = center_xy
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 0.5
thickness = 1
text = str(obj_id)
(tw, th), baseline = cv2.getTextSize(text, font, font_scale, thickness)
pad = 4
x1 = cx - tw // 2 - pad
y1 = cy - th // 2 - pad
x2 = cx + tw // 2 + pad
y2 = cy + th // 2 + pad
H, W = frame_bgr.shape[:2]
x1 = max(0, min(W - 1, x1))
x2 = max(0, min(W - 1, x2))
y1 = max(0, min(H - 1, y1))
y2 = max(0, min(H - 1, y2))
cv2.rectangle(frame_bgr, (x1, y1), (x2, y2), color_bgr, thickness=-1)
txt_color = (0, 0, 0) if (sum(color_bgr) > 380) else (255, 255, 255)
cv2.putText(frame_bgr, text, (x1 + pad, y2 - pad),
font, font_scale, txt_color, thickness, cv2.LINE_AA)
def _wrap_text_to_width(text: str, font, font_scale: float, thickness: int, max_w: int) -> List[str]:
if max_w <= 0:
return [""]
text = str(text)
(tw, _), _b = cv2.getTextSize(text, font, font_scale, thickness)
if tw <= max_w:
return [text]
words = text.split(" ")
lines: List[str] = []
cur = ""
def fits(s: str) -> bool:
(w, _), _b2 = cv2.getTextSize(s, font, font_scale, thickness)
return w <= max_w
for w in words:
cand = w if cur == "" else (cur + " " + w)
if fits(cand):
cur = cand
else:
if cur:
lines.append(cur)
cur = ""
if not fits(w):
chunk = ""
for ch in w:
cand2 = chunk + ch
if fits(cand2):
chunk = cand2
else:
if chunk:
lines.append(chunk)
chunk = ch
if chunk:
cur = chunk
else:
cur = w
if cur:
lines.append(cur)
return lines if lines else [""]
def render_object_list_panel_two_cols(
width: int,
panel_h: int,
lines: List[str],
font_scale: float = 0.5,
thickness: int = 1,
col_gap: int = 18,
margin_x: int = 12,
top_y: int = 24,
line_h: int = 16,
) -> np.ndarray:
"""
Two-column panel for object list lines like: "3: hand"
Supports wrap inside each column.
"""
panel = np.zeros((panel_h, width, 3), dtype=np.uint8)
font = cv2.FONT_HERSHEY_SIMPLEX
col_w = (width - 2 * margin_x - col_gap) // 2
x1 = margin_x
x2 = margin_x + col_w + col_gap
pairs = [(lines[i], lines[i+1] if i+1 < len(lines) else "") for i in range(0, len(lines), 2)]
y = top_y
used = 0
for left_text, right_text in pairs:
left_wrapped = _wrap_text_to_width(left_text, font, font_scale, thickness, col_w) if left_text else []
right_wrapped = _wrap_text_to_width(right_text, font, font_scale, thickness, col_w) if right_text else []
row_lines = max(len(left_wrapped), len(right_wrapped), 1)
row_h = row_lines * line_h
if y + row_h > panel_h - 8:
break
yy = y
for t in left_wrapped:
cv2.putText(panel, t, (x1, yy), font, font_scale, (255, 255, 255), thickness, cv2.LINE_AA)
yy += line_h
yy = y
for t in right_wrapped:
cv2.putText(panel, t, (x2, yy), font, font_scale, (255, 255, 255), thickness, cv2.LINE_AA)
yy += line_h
y += row_h
used += 2
remaining = max(0, len(lines) - used)
if remaining > 0:
hint = f"... (+{remaining} more)"
cv2.putText(panel, hint, (margin_x, panel_h - 10), font, font_scale, (200, 200, 200), thickness, cv2.LINE_AA)
return panel
def safe_makedirs(p: str):
os.makedirs(p, exist_ok=True)
def stable_color_for_id(obj_id: int) -> Tuple[int, int, int]:
"""
Deterministic distinct-ish BGR color per object id.
Uses HSV wheel -> BGR.
"""
# golden ratio steps to spread hues
hue = (obj_id * 0.61803398875) % 1.0
h = int(hue * 179) # OpenCV hue range [0,179]
s = 200
v = 255
hsv = np.uint8([[[h, s, v]]])
bgr = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)[0, 0]
return int(bgr[0]), int(bgr[1]), int(bgr[2])
def parse_gpt_json_from_conversations(convs: List[Dict[str, Any]]) -> Dict[str, Any]:
"""
Extract and parse the 'gpt' message JSON (stored as a string in 'value').
We make it robust to leading/trailing text by searching for the first {...} block.
"""
gpt_msgs = [c for c in convs if c.get("from") == "gpt"]
if not gpt_msgs:
return {}
raw = gpt_msgs[-1].get("value", "")
if not raw:
return {}
# If it's already valid JSON, parse directly.
try:
return json.loads(raw)
except Exception:
pass
# Otherwise, try to find the first JSON object substring.
m = re.search(r"\{.*\}", raw, flags=re.DOTALL)
if not m:
return {}
try:
return json.loads(m.group(0))
except Exception:
return {}
def decode_rle_to_mask(rle: Dict[str, Any]) -> np.ndarray:
"""
Robust RLE decode:
- If rle['counts'] is list (uncompressed), use frPyObjects then decode.
- If it's already compressed (bytes/str), decode directly.
Returns uint8 mask of shape (H, W) with values 0/1.
"""
if rle is None:
return None
if "size" not in rle or "counts" not in rle:
return None
h, w = rle["size"]
counts = rle["counts"]
try:
if isinstance(counts, list):
# uncompressed RLE -> convert using frPyObjects
rle_obj = mask_utils.frPyObjects(rle, h, w)
m = mask_utils.decode(rle_obj)
else:
# compressed (string/bytes)
m = mask_utils.decode(rle)
except Exception:
# last attempt: sometimes need list-wrapping
try:
m = mask_utils.decode([rle])[:, :, 0]
except Exception:
return None
# m can be (H,W) or (H,W,1)
if m.ndim == 3:
m = m[:, :, 0]
m = (m > 0).astype(np.uint8)
return m
def mask_centroid(mask01: np.ndarray) -> Optional[Tuple[int, int]]:
"""
Compute centroid of binary mask (0/1). Returns (cx, cy) or None if empty.
"""
if mask01 is None:
return None
ys, xs = np.where(mask01 > 0)
if len(xs) == 0:
return None
cx = int(xs.mean())
cy = int(ys.mean())
return cx, cy
def overlay_mask(frame_bgr: np.ndarray, mask01: np.ndarray, color_bgr: Tuple[int,int,int], alpha: float) -> np.ndarray:
"""
Alpha-blend colored mask onto frame.
"""
if mask01 is None:
return frame_bgr
if mask01.sum() == 0:
return frame_bgr
out = frame_bgr.copy()
color = np.array(color_bgr, dtype=np.float32).reshape(1, 1, 3)
m = mask01.astype(bool)
out_f = out.astype(np.float32)
out_f[m] = out_f[m] * (1.0 - alpha) + color * alpha
out = np.clip(out_f, 0, 255).astype(np.uint8)
return out
def draw_label_box(frame_bgr: np.ndarray, text: str, center_xy: Tuple[int,int], color_bgr: Tuple[int,int,int]):
"""
Draw filled rectangle with text centered at center_xy.
"""
cx, cy = center_xy
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 0.5
thickness = 1
(tw, th), baseline = cv2.getTextSize(text, font, font_scale, thickness)
pad = 6
x1 = int(cx - tw / 2) - pad
y1 = int(cy - th / 2) - pad
x2 = int(cx + tw / 2) + pad
y2 = int(cy + th / 2) + pad
# clamp
h, w = frame_bgr.shape[:2]
x1 = max(0, min(w - 1, x1))
x2 = max(0, min(w - 1, x2))
y1 = max(0, min(h - 1, y1))
y2 = max(0, min(h - 1, y2))
cv2.rectangle(frame_bgr, (x1, y1), (x2, y2), color_bgr, thickness=-1)
# choose contrasting text color
txt_color = (0, 0, 0) if (color_bgr[0] + color_bgr[1] + color_bgr[2]) > 380 else (255, 255, 255)
cv2.putText(frame_bgr, text, (x1 + pad, y2 - pad),
font, font_scale, txt_color, thickness, cv2.LINE_AA)
def relationship_active(rel_item: List[Any], frame_idx: int, fps: float) -> bool:
"""
rel_item = [sub_id, rel_str, obj_id, intervals]
intervals = [[t0,t1], ...] where t0/t1 are seconds (float or int)
We treat intervals inclusive on ends in time.
"""
if len(rel_item) < 4:
return False
intervals = rel_item[3]
if not isinstance(intervals, list) or fps <= 1e-6:
return False
t = frame_idx / fps # current time in seconds
for itv in intervals:
if not (isinstance(itv, (list, tuple))) or len(itv) < 2:
continue
t0 = float(itv[0])
t1 = float(itv[1])
if t0 <= t <= t1:
return True
return False
def render_relationship_panel(
width: int,
panel_h: int,
lines: List[str],
font_scale: float = 0.5
) -> np.ndarray:
"""
Create a black panel and draw relationship lines.
"""
panel = np.zeros((panel_h, width, 3), dtype=np.uint8)
font = cv2.FONT_HERSHEY_SIMPLEX
thickness = 1
y = 28
for line in lines[: max(1, panel_h // 22) ]:
cv2.putText(panel, line, (12, y), font, font_scale, (255, 255, 255), thickness, cv2.LINE_AA)
y += 22
if y > panel_h - 10:
break
return panel
# -----------------------------
# Core pipeline
# -----------------------------
def visualize_one(
item: Dict[str, Any],
out_path: str,
alpha: float = 0.3,
panel_h: int = 600,
max_rels: int = 100,
max_frames: Optional[int] = None,
verbose: bool = True,
):
video_path = item["video"]
mask_path = item["mask_json"]
obj_list = item.get("obj_list", None)
g = parse_gpt_json_from_conversations(item.get("conversations", []))
objects = g.get("objects", [])
rels = g.get("relationships", [])
# object id -> name (best effort)
id2name: Dict[int, str] = {}
for i, obj in enumerate(objects):
if isinstance(obj, dict):
# expected {"object_0":"hand", "attributes":[...]}
# find key starting with object_
name = None
for k, v in obj.items():
if isinstance(k, str) and k.startswith("object_"):
name = str(v)
# parse idx from key
try:
idx = int(k.split("_")[1])
id2name[idx] = name
except Exception:
pass
# fallback: if it’s ordered list and missing explicit id
if name is not None and i not in id2name:
id2name[i] = name
# load masks (2D list)
with open(mask_path, "r") as f:
masks_2d = json.load(f)
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
raise RuntimeError(f"Failed to open video: {video_path}")
fps = cap.get(cv2.CAP_PROP_FPS)
if not fps or math.isnan(fps) or fps <= 1e-3:
fps = 30.0
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
# output writer with extra panel
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
writer = cv2.VideoWriter(out_path, fourcc, fps, (w, h + panel_h))
if not writer.isOpened():
raise RuntimeError(f"Failed to open writer: {out_path}")
n_masks_frames = len(masks_2d)
frame_idx = 0
# decide which object ids to visualize
if obj_list is None:
# fallback to all objects present in gpt JSON
obj_ids = sorted(id2name.keys())
else:
obj_ids = list(obj_list)
if verbose:
print(f"[viz] video={os.path.basename(video_path)} frames(video?) ~, masks_frames={n_masks_frames} obj_ids={obj_ids} rels={len(rels)} -> {out_path}")
total_objs = len(obj_ids)
obj_lines = []
for oid in sorted(obj_ids):
name = id2name.get(oid, f"obj_{oid}")
obj_lines.append(f"{oid}: {name}")
while True:
ok, frame = cap.read()
if not ok:
break
if frame_idx >= n_masks_frames:
break
if max_frames is not None and frame_idx >= max_frames:
break
draw_top_left_hud(frame, f"Os: {total_objs}")
for obj_id in obj_ids:
if obj_id >= len(masks_2d[frame_idx]):
continue
rle = masks_2d[frame_idx][obj_id]
mask01 = decode_rle_to_mask(rle)
if mask01 is None or mask01.sum() == 0:
continue
color = stable_color_for_id(obj_id)
frame = overlay_mask(frame, mask01, color, alpha=alpha)
cxy = mask_centroid(mask01)
if cxy is not None:
draw_id_at_centroid(frame, obj_id, cxy, color)
panel = render_object_list_panel_two_cols(
w, panel_h, obj_lines,
font_scale=0.5,
line_h=16
)
out_frame = np.vstack([frame, panel])
writer.write(out_frame)
frame_idx += 1
cap.release()
writer.release()
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--data_json", type=str, required=True,
help="Path to pe_with_relationships.json (800k items).")
ap.add_argument("--out_dir", type=str, required=True,
help="Output directory for visualization videos.")
ap.add_argument("--num_samples", type=int, default=100)
ap.add_argument("--seed", type=int, default=42)
ap.add_argument("--alpha", type=float, default=0.45)
ap.add_argument("--panel_h", type=int, default=700)
ap.add_argument("--max_rels", type=int, default=100)
ap.add_argument("--max_frames", type=int, default=None,
help="Optional cap on frames per video (debug speed).")
args = ap.parse_args()
safe_makedirs(args.out_dir)
raw_dir = args.out_dir + "_raw"
safe_makedirs(raw_dir)
with open(args.data_json, "r") as f:
data = json.load(f)
n = len(data)
if n == 0:
raise RuntimeError("Empty dataset JSON.")
k = min(args.num_samples, n)
rng = random.Random(args.seed)
idxs = rng.sample(range(n), k)
# dump sampled metadata (so you can reproduce)
sampled_items = [data[i] for i in idxs]
with open(os.path.join(args.out_dir, "sampled_items.json"), "w") as f:
json.dump(sampled_items, f, indent=2)
for j, i in enumerate(idxs):
item = data[i]
video_path = item["video"]
base = os.path.splitext(os.path.basename(video_path))[0]
# ===== 1. copy raw video =====
raw_out_path = os.path.join(raw_dir, f"{j:03d}_{base}.mp4")
if not os.path.exists(raw_out_path):
try:
shutil.copy2(video_path, raw_out_path)
except Exception as e:
print(f"[warn] failed to copy raw video: {video_path} -> {raw_out_path}: {e}")
out_path = os.path.join(args.out_dir, f"{j:03d}_{base}_viz.mp4")
try:
visualize_one(
item=item,
out_path=out_path,
alpha=args.alpha,
panel_h=args.panel_h,
max_rels=args.max_rels,
max_frames=args.max_frames,
verbose=True,
)
except Exception as e:
# keep going; log failures
err_path = os.path.join(args.out_dir, "errors.txt")
with open(err_path, "a") as ef:
ef.write(f"[ERROR] idx={i} video={video_path}\n{repr(e)}\n\n")
print(f"[error] idx={i} video={video_path}: {e}")
print(f"[done] wrote {k} videos into: {args.out_dir}")
if __name__ == "__main__":
main()