DataFurnace-AMR / scripts /draw_bbox_overlay.py
jp-cypress's picture
Update scripts/draw_bbox_overlay.py
dd662a4 verified
Raw
History Blame Contribute Delete
7.03 kB
"""
Constructive Furnace: 3D Bounding Box Visualization Tool
(空間認識AI・SLAM評価用 3Dバウンディングボックス可視化ツール)
This script reads a procedural synthetic dataset (RGB images and JSON metadata)
and projects physically accurate 3D bounding boxes onto the 2D image plane.
Usage:
1. Place this script in the same directory as the dataset files.
2. Run: python draw_bbox_overlay.py --input ./ --output ./output_bbox
Dependencies:
pip install opencv-python numpy
"""
import os
import glob
import json
import sys
import argparse
try:
import cv2
import numpy as np
except ImportError:
print(" [Error] Missing required packages: pip install opencv-python numpy")
sys.exit(1)
# ==========================================
# 設定(Settings)
# ==========================================
# キャリブレーション済みのカメラ内部パラメータ
FOCAL_LENGTH_MM = 18.0
SENSOR_WIDTH_MM = 36.0
COLOR_MAP = {
"Box": (0, 165, 255),
"Pallet": (0, 255, 0),
"Rack": (255, 0, 0),
"Unknown": (0, 0, 255),
"DEFAULT": (0, 0, 255)
}
# 描画用パラメータ
THICKNESS = 2
FONT = cv2.FONT_HERSHEY_SIMPLEX
FONT_SCALE = 0.5
FONT_THICKNESS = 1
# ==========================================
# 3D 座標変換・数学ロジック
# ==========================================
def get_euler_matrix(rx, ry, rz):
cx, sx = np.cos(rx), np.sin(rx)
cy, sy = np.cos(ry), np.sin(ry)
cz, sz = np.cos(rz), np.sin(rz)
Rx = np.array([[1, 0, 0], [0, cx, -sx], [0, sx, cx]])
Ry = np.array([[cy, 0, sy], [0, 1, 0], [-sy, 0, cy]])
Rz = np.array([[cz, -sz, 0], [sz, cz, 0], [0, 0, 1]])
return Rz @ Ry @ Rx
def project_3d_points(local_corners, obj_pose, cam_pose, img_w, img_h):
# オブジェクトの回転と位置
rx, ry, rz = obj_pose["rotation_euler"]
R_obj = get_euler_matrix(rx, ry, rz)
T_obj = np.array(obj_pose["location"])
# 8頂点を一括でワールド座標へ変換
world_pts = (R_obj @ local_corners.T).T + T_obj
# カメラの回転と位置
R_cam = get_euler_matrix(cam_pose["rotation"]["x"], cam_pose["rotation"]["y"], cam_pose["rotation"]["z"])
T_cam = np.array([cam_pose["location"]["x"], cam_pose["location"]["y"], cam_pose["location"]["z"]])
# 一括でカメラローカル座標へ変換 (R_cam.T は逆行列と等価)
cam_local_pts = (R_cam.T @ (world_pts - T_cam).T).T
# Blender -> OpenCV の座標系変換 (Y, Zの符号を反転)
pts_cv = np.zeros_like(cam_local_pts)
pts_cv[:, 0] = cam_local_pts[:, 0]
pts_cv[:, 1] = -cam_local_pts[:, 1]
pts_cv[:, 2] = -cam_local_pts[:, 2]
# カメラ内部パラメータによる透視投影
f_pixels = img_w * (FOCAL_LENGTH_MM / SENSOR_WIDTH_MM)
cx, cy = img_w / 2.0, img_h / 2.0
pts_2d = []
for x, y, z in pts_cv:
# カメラの背後(Z<=0.1)にある頂点は破綻を防ぐためクリッピング
if z <= 0.1:
return None
u = int((x / z) * f_pixels + cx)
v = int((y / z) * f_pixels + cy)
pts_2d.append((u, v))
return pts_2d
# ==========================================
# メイン処理(汎用化バッチ)
# ==========================================
def main():
parser = argparse.ArgumentParser(description="Draw 3D Bounding Boxes on RGB images.")
parser.add_argument("--input", "-i", default="./", help="Directory containing RGB images and JSON metadata")
parser.add_argument("--output", "-o", default="./output_bbox", help="Directory to save output images")
args = parser.parse_args()
input_dir = args.input
output_dir = args.output
if not os.path.exists(output_dir):
os.makedirs(output_dir)
search_pattern = os.path.join(input_dir, "*_RGB.png")
rgb_files = glob.glob(search_pattern)
if not rgb_files:
print(f" [Warn] No RGB images found in {input_dir}. Please check the path.")
return
print(f" [Info] Found {len(rgb_files)} images. Starting BBox projection...")
for rgb_path in rgb_files:
base_name = rgb_path.replace("_RGB.png", "")
json_path = f"{base_name}_BBox.json"
if not os.path.exists(json_path):
print(f" [Skip] JSON not found for {os.path.basename(rgb_path)}")
continue
with open(json_path, 'r', encoding='utf-8') as f:
data = json.load(f)
img = cv2.imread(rgb_path)
if img is None:
continue
img_h, img_w = img.shape[:2]
cam_pose = data.get("camera_pose", data.get("camera"))
objects = data.get("objects", [])
for obj in objects:
# 1. クラス名の取得と色の割り当て
class_name = obj.get("class", "DEFAULT")
color = COLOR_MAP.get(class_name, COLOR_MAP["DEFAULT"])
# 2. リスト形式 [w, d, h] として取得する
w, d, h = obj["dimensions"]
# 3. オフセット無し、純粋な中心(0,0,0)から広がる8頂点
x_min, x_max = -w/2, w/2
y_min, y_max = -d/2, d/2
z_min, z_max = -h/2, h/2
local_corners = np.array([
[x_min, y_min, z_min], [x_max, y_min, z_min], [x_max, y_max, z_min], [x_min, y_max, z_min],
[x_min, y_min, z_max], [x_max, y_min, z_max], [x_max, y_max, z_max], [x_min, y_max, z_max]
])
pts_2d = project_3d_points(local_corners, obj, cam_pose, img_w, img_h)
if pts_2d is None:
continue
# ワイヤーフレームの描画
edges = [(0, 1), (1, 2), (2, 3), (3, 0), (4, 5), (5, 6), (6, 7), (7, 4), (0, 4), (1, 5), (2, 6), (3, 7)]
for start, end in edges:
cv2.line(img, pts_2d[start], pts_2d[end], color, THICKNESS)
# クラス名のテキストラベル描画
min_x = min([p[0] for p in pts_2d])
min_y = min([p[1] for p in pts_2d])
label_text = f"{class_name}"
(tw, th), baseline = cv2.getTextSize(label_text, FONT, FONT_SCALE, FONT_THICKNESS)
cv2.rectangle(img, (min_x, min_y - th - 5), (min_x + tw, min_y), color, -1)
cv2.putText(img, label_text, (min_x, min_y - 5), FONT, FONT_SCALE, (255, 255, 255), FONT_THICKNESS)
out_filename = os.path.basename(rgb_path).replace("_RGB.png", "_BBox_Overlay.png")
out_path = os.path.join(output_dir, out_filename)
cv2.imwrite(out_path, img)
print(f" [OK] Generated -> {out_filename}")
if __name__ == "__main__":
main()